]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/iD/iD/mapillary-js/mapillary.js
Merge remote-tracking branch 'upstream/pull/2087'
[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":226}],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     var p = ear.prevZ,
2572         n = ear.nextZ;
2573
2574     // look for points inside the triangle in both directions
2575     while (p && p.z >= minZ && n && n.z <= maxZ) {
2576         if (p !== ear.prev && p !== ear.next &&
2577             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2578             area(p.prev, p, p.next) >= 0) return false;
2579         p = p.prevZ;
2580
2581         if (n !== ear.prev && n !== ear.next &&
2582             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
2583             area(n.prev, n, n.next) >= 0) return false;
2584         n = n.nextZ;
2585     }
2586
2587     // look for remaining points in decreasing z-order
2588     while (p && p.z >= minZ) {
2589         if (p !== ear.prev && p !== ear.next &&
2590             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2591             area(p.prev, p, p.next) >= 0) return false;
2592         p = p.prevZ;
2593     }
2594
2595     // look for remaining points in increasing z-order
2596     while (n && n.z <= maxZ) {
2597         if (n !== ear.prev && n !== ear.next &&
2598             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
2599             area(n.prev, n, n.next) >= 0) return false;
2600         n = n.nextZ;
2601     }
2602
2603     return true;
2604 }
2605
2606 // go through all polygon nodes and cure small local self-intersections
2607 function cureLocalIntersections(start, triangles, dim) {
2608     var p = start;
2609     do {
2610         var a = p.prev,
2611             b = p.next.next;
2612
2613         if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
2614
2615             triangles.push(a.i / dim);
2616             triangles.push(p.i / dim);
2617             triangles.push(b.i / dim);
2618
2619             // remove two nodes involved
2620             removeNode(p);
2621             removeNode(p.next);
2622
2623             p = start = b;
2624         }
2625         p = p.next;
2626     } while (p !== start);
2627
2628     return p;
2629 }
2630
2631 // try splitting polygon into two and triangulate them independently
2632 function splitEarcut(start, triangles, dim, minX, minY, invSize) {
2633     // look for a valid diagonal that divides the polygon into two
2634     var a = start;
2635     do {
2636         var b = a.next.next;
2637         while (b !== a.prev) {
2638             if (a.i !== b.i && isValidDiagonal(a, b)) {
2639                 // split the polygon in two by the diagonal
2640                 var c = splitPolygon(a, b);
2641
2642                 // filter colinear points around the cuts
2643                 a = filterPoints(a, a.next);
2644                 c = filterPoints(c, c.next);
2645
2646                 // run earcut on each half
2647                 earcutLinked(a, triangles, dim, minX, minY, invSize);
2648                 earcutLinked(c, triangles, dim, minX, minY, invSize);
2649                 return;
2650             }
2651             b = b.next;
2652         }
2653         a = a.next;
2654     } while (a !== start);
2655 }
2656
2657 // link every hole into the outer loop, producing a single-ring polygon without holes
2658 function eliminateHoles(data, holeIndices, outerNode, dim) {
2659     var queue = [],
2660         i, len, start, end, list;
2661
2662     for (i = 0, len = holeIndices.length; i < len; i++) {
2663         start = holeIndices[i] * dim;
2664         end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2665         list = linkedList(data, start, end, dim, false);
2666         if (list === list.next) list.steiner = true;
2667         queue.push(getLeftmost(list));
2668     }
2669
2670     queue.sort(compareX);
2671
2672     // process holes from left to right
2673     for (i = 0; i < queue.length; i++) {
2674         eliminateHole(queue[i], outerNode);
2675         outerNode = filterPoints(outerNode, outerNode.next);
2676     }
2677
2678     return outerNode;
2679 }
2680
2681 function compareX(a, b) {
2682     return a.x - b.x;
2683 }
2684
2685 // find a bridge between vertices that connects hole with an outer ring and and link it
2686 function eliminateHole(hole, outerNode) {
2687     outerNode = findHoleBridge(hole, outerNode);
2688     if (outerNode) {
2689         var b = splitPolygon(outerNode, hole);
2690         filterPoints(b, b.next);
2691     }
2692 }
2693
2694 // David Eberly's algorithm for finding a bridge between hole and outer polygon
2695 function findHoleBridge(hole, outerNode) {
2696     var p = outerNode,
2697         hx = hole.x,
2698         hy = hole.y,
2699         qx = -Infinity,
2700         m;
2701
2702     // find a segment intersected by a ray from the hole's leftmost point to the left;
2703     // segment's endpoint with lesser x will be potential connection point
2704     do {
2705         if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
2706             var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
2707             if (x <= hx && x > qx) {
2708                 qx = x;
2709                 if (x === hx) {
2710                     if (hy === p.y) return p;
2711                     if (hy === p.next.y) return p.next;
2712                 }
2713                 m = p.x < p.next.x ? p : p.next;
2714             }
2715         }
2716         p = p.next;
2717     } while (p !== outerNode);
2718
2719     if (!m) return null;
2720
2721     if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
2722
2723     // look for points inside the triangle of hole point, segment intersection and endpoint;
2724     // if there are no points found, we have a valid connection;
2725     // otherwise choose the point of the minimum angle with the ray as connection point
2726
2727     var stop = m,
2728         mx = m.x,
2729         my = m.y,
2730         tanMin = Infinity,
2731         tan;
2732
2733     p = m.next;
2734
2735     while (p !== stop) {
2736         if (hx >= p.x && p.x >= mx && hx !== p.x &&
2737                 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
2738
2739             tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
2740
2741             if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
2742                 m = p;
2743                 tanMin = tan;
2744             }
2745         }
2746
2747         p = p.next;
2748     }
2749
2750     return m;
2751 }
2752
2753 // interlink polygon nodes in z-order
2754 function indexCurve(start, minX, minY, invSize) {
2755     var p = start;
2756     do {
2757         if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
2758         p.prevZ = p.prev;
2759         p.nextZ = p.next;
2760         p = p.next;
2761     } while (p !== start);
2762
2763     p.prevZ.nextZ = null;
2764     p.prevZ = null;
2765
2766     sortLinked(p);
2767 }
2768
2769 // Simon Tatham's linked list merge sort algorithm
2770 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
2771 function sortLinked(list) {
2772     var i, p, q, e, tail, numMerges, pSize, qSize,
2773         inSize = 1;
2774
2775     do {
2776         p = list;
2777         list = null;
2778         tail = null;
2779         numMerges = 0;
2780
2781         while (p) {
2782             numMerges++;
2783             q = p;
2784             pSize = 0;
2785             for (i = 0; i < inSize; i++) {
2786                 pSize++;
2787                 q = q.nextZ;
2788                 if (!q) break;
2789             }
2790             qSize = inSize;
2791
2792             while (pSize > 0 || (qSize > 0 && q)) {
2793
2794                 if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
2795                     e = p;
2796                     p = p.nextZ;
2797                     pSize--;
2798                 } else {
2799                     e = q;
2800                     q = q.nextZ;
2801                     qSize--;
2802                 }
2803
2804                 if (tail) tail.nextZ = e;
2805                 else list = e;
2806
2807                 e.prevZ = tail;
2808                 tail = e;
2809             }
2810
2811             p = q;
2812         }
2813
2814         tail.nextZ = null;
2815         inSize *= 2;
2816
2817     } while (numMerges > 1);
2818
2819     return list;
2820 }
2821
2822 // z-order of a point given coords and inverse of the longer side of data bbox
2823 function zOrder(x, y, minX, minY, invSize) {
2824     // coords are transformed into non-negative 15-bit integer range
2825     x = 32767 * (x - minX) * invSize;
2826     y = 32767 * (y - minY) * invSize;
2827
2828     x = (x | (x << 8)) & 0x00FF00FF;
2829     x = (x | (x << 4)) & 0x0F0F0F0F;
2830     x = (x | (x << 2)) & 0x33333333;
2831     x = (x | (x << 1)) & 0x55555555;
2832
2833     y = (y | (y << 8)) & 0x00FF00FF;
2834     y = (y | (y << 4)) & 0x0F0F0F0F;
2835     y = (y | (y << 2)) & 0x33333333;
2836     y = (y | (y << 1)) & 0x55555555;
2837
2838     return x | (y << 1);
2839 }
2840
2841 // find the leftmost node of a polygon ring
2842 function getLeftmost(start) {
2843     var p = start,
2844         leftmost = start;
2845     do {
2846         if (p.x < leftmost.x) leftmost = p;
2847         p = p.next;
2848     } while (p !== start);
2849
2850     return leftmost;
2851 }
2852
2853 // check if a point lies within a convex triangle
2854 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
2855     return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
2856            (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
2857            (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
2858 }
2859
2860 // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
2861 function isValidDiagonal(a, b) {
2862     return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
2863            locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
2864 }
2865
2866 // signed area of a triangle
2867 function area(p, q, r) {
2868     return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
2869 }
2870
2871 // check if two points are equal
2872 function equals(p1, p2) {
2873     return p1.x === p2.x && p1.y === p2.y;
2874 }
2875
2876 // check if two segments intersect
2877 function intersects(p1, q1, p2, q2) {
2878     if ((equals(p1, q1) && equals(p2, q2)) ||
2879         (equals(p1, q2) && equals(p2, q1))) return true;
2880     return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
2881            area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
2882 }
2883
2884 // check if a polygon diagonal intersects any polygon segments
2885 function intersectsPolygon(a, b) {
2886     var p = a;
2887     do {
2888         if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
2889                 intersects(p, p.next, a, b)) return true;
2890         p = p.next;
2891     } while (p !== a);
2892
2893     return false;
2894 }
2895
2896 // check if a polygon diagonal is locally inside the polygon
2897 function locallyInside(a, b) {
2898     return area(a.prev, a, a.next) < 0 ?
2899         area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
2900         area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
2901 }
2902
2903 // check if the middle point of a polygon diagonal is inside the polygon
2904 function middleInside(a, b) {
2905     var p = a,
2906         inside = false,
2907         px = (a.x + b.x) / 2,
2908         py = (a.y + b.y) / 2;
2909     do {
2910         if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
2911                 (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
2912             inside = !inside;
2913         p = p.next;
2914     } while (p !== a);
2915
2916     return inside;
2917 }
2918
2919 // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
2920 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
2921 function splitPolygon(a, b) {
2922     var a2 = new Node(a.i, a.x, a.y),
2923         b2 = new Node(b.i, b.x, b.y),
2924         an = a.next,
2925         bp = b.prev;
2926
2927     a.next = b;
2928     b.prev = a;
2929
2930     a2.next = an;
2931     an.prev = a2;
2932
2933     b2.next = a2;
2934     a2.prev = b2;
2935
2936     bp.next = b2;
2937     b2.prev = bp;
2938
2939     return b2;
2940 }
2941
2942 // create a node and optionally link it with previous one (in a circular doubly linked list)
2943 function insertNode(i, x, y, last) {
2944     var p = new Node(i, x, y);
2945
2946     if (!last) {
2947         p.prev = p;
2948         p.next = p;
2949
2950     } else {
2951         p.next = last.next;
2952         p.prev = last;
2953         last.next.prev = p;
2954         last.next = p;
2955     }
2956     return p;
2957 }
2958
2959 function removeNode(p) {
2960     p.next.prev = p.prev;
2961     p.prev.next = p.next;
2962
2963     if (p.prevZ) p.prevZ.nextZ = p.nextZ;
2964     if (p.nextZ) p.nextZ.prevZ = p.prevZ;
2965 }
2966
2967 function Node(i, x, y) {
2968     // vertice index in coordinates array
2969     this.i = i;
2970
2971     // vertex coordinates
2972     this.x = x;
2973     this.y = y;
2974
2975     // previous and next vertice nodes in a polygon ring
2976     this.prev = null;
2977     this.next = null;
2978
2979     // z-order curve value
2980     this.z = null;
2981
2982     // previous and next nodes in z-order
2983     this.prevZ = null;
2984     this.nextZ = null;
2985
2986     // indicates whether this is a steiner point
2987     this.steiner = false;
2988 }
2989
2990 // return a percentage difference between the polygon area and its triangulation area;
2991 // used to verify correctness of triangulation
2992 earcut.deviation = function (data, holeIndices, dim, triangles) {
2993     var hasHoles = holeIndices && holeIndices.length;
2994     var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
2995
2996     var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
2997     if (hasHoles) {
2998         for (var i = 0, len = holeIndices.length; i < len; i++) {
2999             var start = holeIndices[i] * dim;
3000             var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
3001             polygonArea -= Math.abs(signedArea(data, start, end, dim));
3002         }
3003     }
3004
3005     var trianglesArea = 0;
3006     for (i = 0; i < triangles.length; i += 3) {
3007         var a = triangles[i] * dim;
3008         var b = triangles[i + 1] * dim;
3009         var c = triangles[i + 2] * dim;
3010         trianglesArea += Math.abs(
3011             (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
3012             (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
3013     }
3014
3015     return polygonArea === 0 && trianglesArea === 0 ? 0 :
3016         Math.abs((trianglesArea - polygonArea) / polygonArea);
3017 };
3018
3019 function signedArea(data, start, end, dim) {
3020     var sum = 0;
3021     for (var i = start, j = end - dim; i < end; i += dim) {
3022         sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
3023         j = i;
3024     }
3025     return sum;
3026 }
3027
3028 // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
3029 earcut.flatten = function (data) {
3030     var dim = data[0][0].length,
3031         result = {vertices: [], holes: [], dimensions: dim},
3032         holeIndex = 0;
3033
3034     for (var i = 0; i < data.length; i++) {
3035         for (var j = 0; j < data[i].length; j++) {
3036             for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
3037         }
3038         if (i > 0) {
3039             holeIndex += data[i - 1].length;
3040             result.holes.push(holeIndex);
3041         }
3042     }
3043     return result;
3044 };
3045
3046 },{}],9:[function(require,module,exports){
3047 'use strict';
3048
3049 var OneVersionConstraint = require('individual/one-version');
3050
3051 var MY_VERSION = '7';
3052 OneVersionConstraint('ev-store', MY_VERSION);
3053
3054 var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
3055
3056 module.exports = EvStore;
3057
3058 function EvStore(elem) {
3059     var hash = elem[hashKey];
3060
3061     if (!hash) {
3062         hash = elem[hashKey] = {};
3063     }
3064
3065     return hash;
3066 }
3067
3068 },{"individual/one-version":19}],10:[function(require,module,exports){
3069 'use strict';
3070 var request = require('./request');
3071 var buildQueryObject = require('./buildQueryObject');
3072 var isArray = Array.isArray;
3073
3074 function simpleExtend(obj, obj2) {
3075   var prop;
3076   for (prop in obj2) {
3077     obj[prop] = obj2[prop];
3078   }
3079   return obj;
3080 }
3081
3082 function XMLHttpSource(jsongUrl, config) {
3083   this._jsongUrl = jsongUrl;
3084   if (typeof config === 'number') {
3085     var newConfig = {
3086       timeout: config
3087     };
3088     config = newConfig;
3089   }
3090   this._config = simpleExtend({
3091     timeout: 15000,
3092     headers: {}
3093   }, config || {});
3094 }
3095
3096 XMLHttpSource.prototype = {
3097   // because javascript
3098   constructor: XMLHttpSource,
3099   /**
3100    * buildQueryObject helper
3101    */
3102   buildQueryObject: buildQueryObject,
3103
3104   /**
3105    * @inheritDoc DataSource#get
3106    */
3107   get: function httpSourceGet(pathSet) {
3108     var method = 'GET';
3109     var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3110       paths: pathSet,
3111       method: 'get'
3112     });
3113     var config = simpleExtend(queryObject, this._config);
3114     // pass context for onBeforeRequest callback
3115     var context = this;
3116     return request(method, config, context);
3117   },
3118
3119   /**
3120    * @inheritDoc DataSource#set
3121    */
3122   set: function httpSourceSet(jsongEnv) {
3123     var method = 'POST';
3124     var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3125       jsonGraph: jsongEnv,
3126       method: 'set'
3127     });
3128     var config = simpleExtend(queryObject, this._config);
3129     config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3130     
3131     // pass context for onBeforeRequest callback
3132     var context = this;
3133     return request(method, config, context);
3134
3135   },
3136
3137   /**
3138    * @inheritDoc DataSource#call
3139    */
3140   call: function httpSourceCall(callPath, args, pathSuffix, paths) {
3141     // arguments defaults
3142     args = args || [];
3143     pathSuffix = pathSuffix || [];
3144     paths = paths || [];
3145
3146     var method = 'POST';
3147     var queryData = [];
3148     queryData.push('method=call');
3149     queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
3150     queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
3151     queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
3152     queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
3153
3154     var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
3155     var config = simpleExtend(queryObject, this._config);
3156     config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3157     
3158     // pass context for onBeforeRequest callback
3159     var context = this;
3160     return request(method, config, context);
3161   }
3162 };
3163 // ES6 modules
3164 XMLHttpSource.XMLHttpSource = XMLHttpSource;
3165 XMLHttpSource['default'] = XMLHttpSource;
3166 // commonjs
3167 module.exports = XMLHttpSource;
3168
3169 },{"./buildQueryObject":11,"./request":14}],11:[function(require,module,exports){
3170 'use strict';
3171 module.exports = function buildQueryObject(url, method, queryData) {
3172   var qData = [];
3173   var keys;
3174   var data = {url: url};
3175   var isQueryParamUrl = url.indexOf('?') !== -1;
3176   var startUrl = (isQueryParamUrl) ? '&' : '?';
3177
3178   if (typeof queryData === 'string') {
3179     qData.push(queryData);
3180   } else {
3181
3182     keys = Object.keys(queryData);
3183     keys.forEach(function (k) {
3184       var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
3185       qData.push(k + '=' + encodeURIComponent(value));
3186     });
3187   }
3188
3189   if (method === 'GET') {
3190     data.url += startUrl + qData.join('&');
3191   } else {
3192     data.data = qData.join('&');
3193   }
3194
3195   return data;
3196 };
3197
3198 },{}],12:[function(require,module,exports){
3199 (function (global){
3200 'use strict';
3201 // Get CORS support even for older IE
3202 module.exports = function getCORSRequest() {
3203     var xhr = new global.XMLHttpRequest();
3204     if ('withCredentials' in xhr) {
3205         return xhr;
3206     } else if (!!global.XDomainRequest) {
3207         return new XDomainRequest();
3208     } else {
3209         throw new Error('CORS is not supported by your browser');
3210     }
3211 };
3212
3213 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3214
3215 },{}],13:[function(require,module,exports){
3216 (function (global){
3217 'use strict';
3218 module.exports = function getXMLHttpRequest() {
3219   var progId,
3220     progIds,
3221     i;
3222   if (global.XMLHttpRequest) {
3223     return new global.XMLHttpRequest();
3224   } else {
3225     try {
3226     progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
3227     for (i = 0; i < 3; i++) {
3228       try {
3229         progId = progIds[i];
3230         if (new global.ActiveXObject(progId)) {
3231           break;
3232         }
3233       } catch(e) { }
3234     }
3235     return new global.ActiveXObject(progId);
3236     } catch (e) {
3237     throw new Error('XMLHttpRequest is not supported by your browser');
3238     }
3239   }
3240 };
3241
3242 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3243
3244 },{}],14:[function(require,module,exports){
3245 'use strict';
3246 var getXMLHttpRequest = require('./getXMLHttpRequest');
3247 var getCORSRequest = require('./getCORSRequest');
3248 var hasOwnProp = Object.prototype.hasOwnProperty;
3249
3250 var noop = function() {};
3251
3252 function Observable() {}
3253
3254 Observable.create = function(subscribe) {
3255   var o = new Observable();
3256
3257   o.subscribe = function(onNext, onError, onCompleted) {
3258
3259     var observer;
3260     var disposable;
3261
3262     if (typeof onNext === 'function') {
3263         observer = {
3264             onNext: onNext,
3265             onError: (onError || noop),
3266             onCompleted: (onCompleted || noop)
3267         };
3268     } else {
3269         observer = onNext;
3270     }
3271
3272     disposable = subscribe(observer);
3273
3274     if (typeof disposable === 'function') {
3275       return {
3276         dispose: disposable
3277       };
3278     } else {
3279       return disposable;
3280     }
3281   };
3282
3283   return o;
3284 };
3285
3286 function request(method, options, context) {
3287   return Observable.create(function requestObserver(observer) {
3288
3289     var config = {
3290       method: method || 'GET',
3291       crossDomain: false,
3292       async: true,
3293       headers: {},
3294       responseType: 'json'
3295     };
3296
3297     var xhr,
3298       isDone,
3299       headers,
3300       header,
3301       prop;
3302
3303     for (prop in options) {
3304       if (hasOwnProp.call(options, prop)) {
3305         config[prop] = options[prop];
3306       }
3307     }
3308
3309     // Add request with Headers
3310     if (!config.crossDomain && !config.headers['X-Requested-With']) {
3311       config.headers['X-Requested-With'] = 'XMLHttpRequest';
3312     }
3313
3314     // allow the user to mutate the config open
3315     if (context.onBeforeRequest != null) {
3316       context.onBeforeRequest(config);
3317     }
3318
3319     // create xhr
3320     try {
3321       xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
3322     } catch (err) {
3323       observer.onError(err);
3324     }
3325     try {
3326       // Takes the url and opens the connection
3327       if (config.user) {
3328         xhr.open(config.method, config.url, config.async, config.user, config.password);
3329       } else {
3330         xhr.open(config.method, config.url, config.async);
3331       }
3332
3333       // Sets timeout information
3334       xhr.timeout = config.timeout;
3335
3336       // Anything but explicit false results in true.
3337       xhr.withCredentials = config.withCredentials !== false;
3338
3339       // Fills the request headers
3340       headers = config.headers;
3341       for (header in headers) {
3342         if (hasOwnProp.call(headers, header)) {
3343           xhr.setRequestHeader(header, headers[header]);
3344         }
3345       }
3346
3347       if (config.responseType) {
3348         try {
3349           xhr.responseType = config.responseType;
3350         } catch (e) {
3351           // WebKit added support for the json responseType value on 09/03/2013
3352           // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
3353           // known to throw when setting the value "json" as the response type. Other older
3354           // browsers implementing the responseType
3355           //
3356           // The json response type can be ignored if not supported, because JSON payloads are
3357           // parsed on the client-side regardless.
3358           if (config.responseType !== 'json') {
3359             throw e;
3360           }
3361         }
3362       }
3363
3364       xhr.onreadystatechange = function onreadystatechange(e) {
3365         // Complete
3366         if (xhr.readyState === 4) {
3367           if (!isDone) {
3368             isDone = true;
3369             onXhrLoad(observer, xhr, e);
3370           }
3371         }
3372       };
3373
3374       // Timeout
3375       xhr.ontimeout = function ontimeout(e) {
3376         if (!isDone) {
3377           isDone = true;
3378           onXhrError(observer, xhr, 'timeout error', e);
3379         }
3380       };
3381
3382       // Send Request
3383       xhr.send(config.data);
3384
3385     } catch (e) {
3386       observer.onError(e);
3387     }
3388     // Dispose
3389     return function dispose() {
3390       // Doesn't work in IE9
3391       if (!isDone && xhr.readyState !== 4) {
3392         isDone = true;
3393         xhr.abort();
3394       }
3395     };//Dispose
3396   });
3397 }
3398
3399 /*
3400  * General handling of ultimate failure (after appropriate retries)
3401  */
3402 function _handleXhrError(observer, textStatus, errorThrown) {
3403   // IE9: cross-domain request may be considered errors
3404   if (!errorThrown) {
3405     errorThrown = new Error(textStatus);
3406   }
3407
3408   observer.onError(errorThrown);
3409 }
3410
3411 function onXhrLoad(observer, xhr, e) {
3412   var responseData,
3413     responseObject,
3414     responseType;
3415
3416   // If there's no observer, the request has been (or is being) cancelled.
3417   if (xhr && observer) {
3418     responseType = xhr.responseType;
3419     // responseText is the old-school way of retrieving response (supported by IE8 & 9)
3420     // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
3421     responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
3422
3423     // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
3424     var status = (xhr.status === 1223) ? 204 : xhr.status;
3425
3426     if (status >= 200 && status <= 399) {
3427       try {
3428         if (responseType !== 'json') {
3429           responseData = JSON.parse(responseData || '');
3430         }
3431         if (typeof responseData === 'string') {
3432           responseData = JSON.parse(responseData || '');
3433         }
3434       } catch (e) {
3435         _handleXhrError(observer, 'invalid json', e);
3436       }
3437       observer.onNext(responseData);
3438       observer.onCompleted();
3439       return;
3440
3441     } else if (status === 401 || status === 403 || status === 407) {
3442
3443       return _handleXhrError(observer, responseData);
3444
3445     } else if (status === 410) {
3446       // TODO: Retry ?
3447       return _handleXhrError(observer, responseData);
3448
3449     } else if (status === 408 || status === 504) {
3450       // TODO: Retry ?
3451       return _handleXhrError(observer, responseData);
3452
3453     } else {
3454
3455       return _handleXhrError(observer, responseData || ('Response code ' + status));
3456
3457     }//if
3458   }//if
3459 }//onXhrLoad
3460
3461 function onXhrError(observer, xhr, status, e) {
3462   _handleXhrError(observer, status || xhr.statusText || 'request error', e);
3463 }
3464
3465 module.exports = request;
3466
3467 },{"./getCORSRequest":12,"./getXMLHttpRequest":13}],15:[function(require,module,exports){
3468 (function (global){
3469 !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(){
3470 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);
3471 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(){
3472 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(){
3473 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)});
3474 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3475
3476 },{}],16:[function(require,module,exports){
3477 (function (global){
3478 var topLevel = typeof global !== 'undefined' ? global :
3479     typeof window !== 'undefined' ? window : {}
3480 var minDoc = require('min-document');
3481
3482 var doccy;
3483
3484 if (typeof document !== 'undefined') {
3485     doccy = document;
3486 } else {
3487     doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
3488
3489     if (!doccy) {
3490         doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
3491     }
3492 }
3493
3494 module.exports = doccy;
3495
3496 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3497
3498 },{"min-document":4}],17:[function(require,module,exports){
3499 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3500   var e, m
3501   var eLen = nBytes * 8 - mLen - 1
3502   var eMax = (1 << eLen) - 1
3503   var eBias = eMax >> 1
3504   var nBits = -7
3505   var i = isLE ? (nBytes - 1) : 0
3506   var d = isLE ? -1 : 1
3507   var s = buffer[offset + i]
3508
3509   i += d
3510
3511   e = s & ((1 << (-nBits)) - 1)
3512   s >>= (-nBits)
3513   nBits += eLen
3514   for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3515
3516   m = e & ((1 << (-nBits)) - 1)
3517   e >>= (-nBits)
3518   nBits += mLen
3519   for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3520
3521   if (e === 0) {
3522     e = 1 - eBias
3523   } else if (e === eMax) {
3524     return m ? NaN : ((s ? -1 : 1) * Infinity)
3525   } else {
3526     m = m + Math.pow(2, mLen)
3527     e = e - eBias
3528   }
3529   return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3530 }
3531
3532 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3533   var e, m, c
3534   var eLen = nBytes * 8 - mLen - 1
3535   var eMax = (1 << eLen) - 1
3536   var eBias = eMax >> 1
3537   var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3538   var i = isLE ? 0 : (nBytes - 1)
3539   var d = isLE ? 1 : -1
3540   var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3541
3542   value = Math.abs(value)
3543
3544   if (isNaN(value) || value === Infinity) {
3545     m = isNaN(value) ? 1 : 0
3546     e = eMax
3547   } else {
3548     e = Math.floor(Math.log(value) / Math.LN2)
3549     if (value * (c = Math.pow(2, -e)) < 1) {
3550       e--
3551       c *= 2
3552     }
3553     if (e + eBias >= 1) {
3554       value += rt / c
3555     } else {
3556       value += rt * Math.pow(2, 1 - eBias)
3557     }
3558     if (value * c >= 2) {
3559       e++
3560       c /= 2
3561     }
3562
3563     if (e + eBias >= eMax) {
3564       m = 0
3565       e = eMax
3566     } else if (e + eBias >= 1) {
3567       m = (value * c - 1) * Math.pow(2, mLen)
3568       e = e + eBias
3569     } else {
3570       m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3571       e = 0
3572     }
3573   }
3574
3575   for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3576
3577   e = (e << mLen) | m
3578   eLen += mLen
3579   for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3580
3581   buffer[offset + i - d] |= s * 128
3582 }
3583
3584 },{}],18:[function(require,module,exports){
3585 (function (global){
3586 'use strict';
3587
3588 /*global window, global*/
3589
3590 var root = typeof window !== 'undefined' ?
3591     window : typeof global !== 'undefined' ?
3592     global : {};
3593
3594 module.exports = Individual;
3595
3596 function Individual(key, value) {
3597     if (key in root) {
3598         return root[key];
3599     }
3600
3601     root[key] = value;
3602
3603     return value;
3604 }
3605
3606 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3607
3608 },{}],19:[function(require,module,exports){
3609 'use strict';
3610
3611 var Individual = require('./index.js');
3612
3613 module.exports = OneVersion;
3614
3615 function OneVersion(moduleName, version, defaultValue) {
3616     var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
3617     var enforceKey = key + '_ENFORCE_SINGLETON';
3618
3619     var versionValue = Individual(enforceKey, version);
3620
3621     if (versionValue !== version) {
3622         throw new Error('Can only have one copy of ' +
3623             moduleName + '.\n' +
3624             'You already have version ' + versionValue +
3625             ' installed.\n' +
3626             'This means you cannot install version ' + version);
3627     }
3628
3629     return Individual(key, defaultValue);
3630 }
3631
3632 },{"./index.js":18}],20:[function(require,module,exports){
3633 "use strict";
3634
3635 module.exports = function isObject(x) {
3636         return typeof x === "object" && x !== null;
3637 };
3638
3639 },{}],21:[function(require,module,exports){
3640 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3641 /* Geohash encoding/decoding and associated functions   (c) Chris Veness 2014-2016 / MIT Licence  */
3642 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3643
3644 'use strict';
3645
3646
3647 /**
3648  * Geohash encode, decode, bounds, neighbours.
3649  *
3650  * @namespace
3651  */
3652 var Geohash = {};
3653
3654 /* (Geohash-specific) Base32 map */
3655 Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz';
3656
3657 /**
3658  * Encodes latitude/longitude to geohash, either to specified precision or to automatically
3659  * evaluated precision.
3660  *
3661  * @param   {number} lat - Latitude in degrees.
3662  * @param   {number} lon - Longitude in degrees.
3663  * @param   {number} [precision] - Number of characters in resulting geohash.
3664  * @returns {string} Geohash of supplied latitude/longitude.
3665  * @throws  Invalid geohash.
3666  *
3667  * @example
3668  *     var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw'
3669  */
3670 Geohash.encode = function(lat, lon, precision) {
3671     // infer precision?
3672     if (typeof precision == 'undefined') {
3673         // refine geohash until it matches precision of supplied lat/lon
3674         for (var p=1; p<=12; p++) {
3675             var hash = Geohash.encode(lat, lon, p);
3676             var posn = Geohash.decode(hash);
3677             if (posn.lat==lat && posn.lon==lon) return hash;
3678         }
3679         precision = 12; // set to maximum
3680     }
3681
3682     lat = Number(lat);
3683     lon = Number(lon);
3684     precision = Number(precision);
3685
3686     if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash');
3687
3688     var idx = 0; // index into base32 map
3689     var bit = 0; // each char holds 5 bits
3690     var evenBit = true;
3691     var geohash = '';
3692
3693     var latMin =  -90, latMax =  90;
3694     var lonMin = -180, lonMax = 180;
3695
3696     while (geohash.length < precision) {
3697         if (evenBit) {
3698             // bisect E-W longitude
3699             var lonMid = (lonMin + lonMax) / 2;
3700             if (lon >= lonMid) {
3701                 idx = idx*2 + 1;
3702                 lonMin = lonMid;
3703             } else {
3704                 idx = idx*2;
3705                 lonMax = lonMid;
3706             }
3707         } else {
3708             // bisect N-S latitude
3709             var latMid = (latMin + latMax) / 2;
3710             if (lat >= latMid) {
3711                 idx = idx*2 + 1;
3712                 latMin = latMid;
3713             } else {
3714                 idx = idx*2;
3715                 latMax = latMid;
3716             }
3717         }
3718         evenBit = !evenBit;
3719
3720         if (++bit == 5) {
3721             // 5 bits gives us a character: append it and start over
3722             geohash += Geohash.base32.charAt(idx);
3723             bit = 0;
3724             idx = 0;
3725         }
3726     }
3727
3728     return geohash;
3729 };
3730
3731
3732 /**
3733  * Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
3734  *     to reasonable precision).
3735  *
3736  * @param   {string} geohash - Geohash string to be converted to latitude/longitude.
3737  * @returns {{lat:number, lon:number}} (Center of) geohashed location.
3738  * @throws  Invalid geohash.
3739  *
3740  * @example
3741  *     var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 }
3742  */
3743 Geohash.decode = function(geohash) {
3744
3745     var bounds = Geohash.bounds(geohash); // <-- the hard work
3746     // now just determine the centre of the cell...
3747
3748     var latMin = bounds.sw.lat, lonMin = bounds.sw.lon;
3749     var latMax = bounds.ne.lat, lonMax = bounds.ne.lon;
3750
3751     // cell centre
3752     var lat = (latMin + latMax)/2;
3753     var lon = (lonMin + lonMax)/2;
3754
3755     // round to close to centre without excessive precision: âŒŠ2-log10(Δ°)⌋ decimal places
3756     lat = lat.toFixed(Math.floor(2-Math.log(latMax-latMin)/Math.LN10));
3757     lon = lon.toFixed(Math.floor(2-Math.log(lonMax-lonMin)/Math.LN10));
3758
3759     return { lat: Number(lat), lon: Number(lon) };
3760 };
3761
3762
3763 /**
3764  * Returns SW/NE latitude/longitude bounds of specified geohash.
3765  *
3766  * @param   {string} geohash - Cell that bounds are required of.
3767  * @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
3768  * @throws  Invalid geohash.
3769  */
3770 Geohash.bounds = function(geohash) {
3771     if (geohash.length === 0) throw new Error('Invalid geohash');
3772
3773     geohash = geohash.toLowerCase();
3774
3775     var evenBit = true;
3776     var latMin =  -90, latMax =  90;
3777     var lonMin = -180, lonMax = 180;
3778
3779     for (var i=0; i<geohash.length; i++) {
3780         var chr = geohash.charAt(i);
3781         var idx = Geohash.base32.indexOf(chr);
3782         if (idx == -1) throw new Error('Invalid geohash');
3783
3784         for (var n=4; n>=0; n--) {
3785             var bitN = idx >> n & 1;
3786             if (evenBit) {
3787                 // longitude
3788                 var lonMid = (lonMin+lonMax) / 2;
3789                 if (bitN == 1) {
3790                     lonMin = lonMid;
3791                 } else {
3792                     lonMax = lonMid;
3793                 }
3794             } else {
3795                 // latitude
3796                 var latMid = (latMin+latMax) / 2;
3797                 if (bitN == 1) {
3798                     latMin = latMid;
3799                 } else {
3800                     latMax = latMid;
3801                 }
3802             }
3803             evenBit = !evenBit;
3804         }
3805     }
3806
3807     var bounds = {
3808         sw: { lat: latMin, lon: lonMin },
3809         ne: { lat: latMax, lon: lonMax },
3810     };
3811
3812     return bounds;
3813 };
3814
3815
3816 /**
3817  * Determines adjacent cell in given direction.
3818  *
3819  * @param   geohash - Cell to which adjacent cell is required.
3820  * @param   direction - Direction from geohash (N/S/E/W).
3821  * @returns {string} Geocode of adjacent cell.
3822  * @throws  Invalid geohash.
3823  */
3824 Geohash.adjacent = function(geohash, direction) {
3825     // based on github.com/davetroy/geohash-js
3826
3827     geohash = geohash.toLowerCase();
3828     direction = direction.toLowerCase();
3829
3830     if (geohash.length === 0) throw new Error('Invalid geohash');
3831     if ('nsew'.indexOf(direction) == -1) throw new Error('Invalid direction');
3832
3833     var neighbour = {
3834         n: [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx' ],
3835         s: [ '14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp' ],
3836         e: [ 'bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy' ],
3837         w: [ '238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb' ],
3838     };
3839     var border = {
3840         n: [ 'prxz',     'bcfguvyz' ],
3841         s: [ '028b',     '0145hjnp' ],
3842         e: [ 'bcfguvyz', 'prxz'     ],
3843         w: [ '0145hjnp', '028b'     ],
3844     };
3845
3846     var lastCh = geohash.slice(-1);    // last character of hash
3847     var parent = geohash.slice(0, -1); // hash without last character
3848
3849     var type = geohash.length % 2;
3850
3851     // check for edge-cases which don't share common prefix
3852     if (border[direction][type].indexOf(lastCh) != -1 && parent !== '') {
3853         parent = Geohash.adjacent(parent, direction);
3854     }
3855
3856     // append letter for direction to parent
3857     return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
3858 };
3859
3860
3861 /**
3862  * Returns all 8 adjacent cells to specified geohash.
3863  *
3864  * @param   {string} geohash - Geohash neighbours are required of.
3865  * @returns {{n,ne,e,se,s,sw,w,nw: string}}
3866  * @throws  Invalid geohash.
3867  */
3868 Geohash.neighbours = function(geohash) {
3869     return {
3870         'n':  Geohash.adjacent(geohash, 'n'),
3871         'ne': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'e'),
3872         'e':  Geohash.adjacent(geohash, 'e'),
3873         'se': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'e'),
3874         's':  Geohash.adjacent(geohash, 's'),
3875         'sw': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'w'),
3876         'w':  Geohash.adjacent(geohash, 'w'),
3877         'nw': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'w'),
3878     };
3879 };
3880
3881
3882 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3883 if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js
3884
3885 },{}],22:[function(require,module,exports){
3886 (function (process){
3887 // Copyright Joyent, Inc. and other Node contributors.
3888 //
3889 // Permission is hereby granted, free of charge, to any person obtaining a
3890 // copy of this software and associated documentation files (the
3891 // "Software"), to deal in the Software without restriction, including
3892 // without limitation the rights to use, copy, modify, merge, publish,
3893 // distribute, sublicense, and/or sell copies of the Software, and to permit
3894 // persons to whom the Software is furnished to do so, subject to the
3895 // following conditions:
3896 //
3897 // The above copyright notice and this permission notice shall be included
3898 // in all copies or substantial portions of the Software.
3899 //
3900 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3901 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3902 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3903 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3904 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3905 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3906 // USE OR OTHER DEALINGS IN THE SOFTWARE.
3907
3908 // resolves . and .. elements in a path array with directory names there
3909 // must be no slashes, empty elements, or device names (c:\) in the array
3910 // (so also no leading and trailing slashes - it does not distinguish
3911 // relative and absolute paths)
3912 function normalizeArray(parts, allowAboveRoot) {
3913   // if the path tries to go above the root, `up` ends up > 0
3914   var up = 0;
3915   for (var i = parts.length - 1; i >= 0; i--) {
3916     var last = parts[i];
3917     if (last === '.') {
3918       parts.splice(i, 1);
3919     } else if (last === '..') {
3920       parts.splice(i, 1);
3921       up++;
3922     } else if (up) {
3923       parts.splice(i, 1);
3924       up--;
3925     }
3926   }
3927
3928   // if the path is allowed to go above the root, restore leading ..s
3929   if (allowAboveRoot) {
3930     for (; up--; up) {
3931       parts.unshift('..');
3932     }
3933   }
3934
3935   return parts;
3936 }
3937
3938 // Split a filename into [root, dir, basename, ext], unix version
3939 // 'root' is just a slash, or nothing.
3940 var splitPathRe =
3941     /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3942 var splitPath = function(filename) {
3943   return splitPathRe.exec(filename).slice(1);
3944 };
3945
3946 // path.resolve([from ...], to)
3947 // posix version
3948 exports.resolve = function() {
3949   var resolvedPath = '',
3950       resolvedAbsolute = false;
3951
3952   for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3953     var path = (i >= 0) ? arguments[i] : process.cwd();
3954
3955     // Skip empty and invalid entries
3956     if (typeof path !== 'string') {
3957       throw new TypeError('Arguments to path.resolve must be strings');
3958     } else if (!path) {
3959       continue;
3960     }
3961
3962     resolvedPath = path + '/' + resolvedPath;
3963     resolvedAbsolute = path.charAt(0) === '/';
3964   }
3965
3966   // At this point the path should be resolved to a full absolute path, but
3967   // handle relative paths to be safe (might happen when process.cwd() fails)
3968
3969   // Normalize the path
3970   resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3971     return !!p;
3972   }), !resolvedAbsolute).join('/');
3973
3974   return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3975 };
3976
3977 // path.normalize(path)
3978 // posix version
3979 exports.normalize = function(path) {
3980   var isAbsolute = exports.isAbsolute(path),
3981       trailingSlash = substr(path, -1) === '/';
3982
3983   // Normalize the path
3984   path = normalizeArray(filter(path.split('/'), function(p) {
3985     return !!p;
3986   }), !isAbsolute).join('/');
3987
3988   if (!path && !isAbsolute) {
3989     path = '.';
3990   }
3991   if (path && trailingSlash) {
3992     path += '/';
3993   }
3994
3995   return (isAbsolute ? '/' : '') + path;
3996 };
3997
3998 // posix version
3999 exports.isAbsolute = function(path) {
4000   return path.charAt(0) === '/';
4001 };
4002
4003 // posix version
4004 exports.join = function() {
4005   var paths = Array.prototype.slice.call(arguments, 0);
4006   return exports.normalize(filter(paths, function(p, index) {
4007     if (typeof p !== 'string') {
4008       throw new TypeError('Arguments to path.join must be strings');
4009     }
4010     return p;
4011   }).join('/'));
4012 };
4013
4014
4015 // path.relative(from, to)
4016 // posix version
4017 exports.relative = function(from, to) {
4018   from = exports.resolve(from).substr(1);
4019   to = exports.resolve(to).substr(1);
4020
4021   function trim(arr) {
4022     var start = 0;
4023     for (; start < arr.length; start++) {
4024       if (arr[start] !== '') break;
4025     }
4026
4027     var end = arr.length - 1;
4028     for (; end >= 0; end--) {
4029       if (arr[end] !== '') break;
4030     }
4031
4032     if (start > end) return [];
4033     return arr.slice(start, end - start + 1);
4034   }
4035
4036   var fromParts = trim(from.split('/'));
4037   var toParts = trim(to.split('/'));
4038
4039   var length = Math.min(fromParts.length, toParts.length);
4040   var samePartsLength = length;
4041   for (var i = 0; i < length; i++) {
4042     if (fromParts[i] !== toParts[i]) {
4043       samePartsLength = i;
4044       break;
4045     }
4046   }
4047
4048   var outputParts = [];
4049   for (var i = samePartsLength; i < fromParts.length; i++) {
4050     outputParts.push('..');
4051   }
4052
4053   outputParts = outputParts.concat(toParts.slice(samePartsLength));
4054
4055   return outputParts.join('/');
4056 };
4057
4058 exports.sep = '/';
4059 exports.delimiter = ':';
4060
4061 exports.dirname = function(path) {
4062   var result = splitPath(path),
4063       root = result[0],
4064       dir = result[1];
4065
4066   if (!root && !dir) {
4067     // No dirname whatsoever
4068     return '.';
4069   }
4070
4071   if (dir) {
4072     // It has a dirname, strip trailing slash
4073     dir = dir.substr(0, dir.length - 1);
4074   }
4075
4076   return root + dir;
4077 };
4078
4079
4080 exports.basename = function(path, ext) {
4081   var f = splitPath(path)[2];
4082   // TODO: make this comparison case-insensitive on windows?
4083   if (ext && f.substr(-1 * ext.length) === ext) {
4084     f = f.substr(0, f.length - ext.length);
4085   }
4086   return f;
4087 };
4088
4089
4090 exports.extname = function(path) {
4091   return splitPath(path)[3];
4092 };
4093
4094 function filter (xs, f) {
4095     if (xs.filter) return xs.filter(f);
4096     var res = [];
4097     for (var i = 0; i < xs.length; i++) {
4098         if (f(xs[i], i, xs)) res.push(xs[i]);
4099     }
4100     return res;
4101 }
4102
4103 // String.prototype.substr - negative index don't work in IE8
4104 var substr = 'ab'.substr(-1) === 'b'
4105     ? function (str, start, len) { return str.substr(start, len) }
4106     : function (str, start, len) {
4107         if (start < 0) start = str.length + start;
4108         return str.substr(start, len);
4109     }
4110 ;
4111
4112 }).call(this,require('_process'))
4113
4114 },{"_process":6}],23:[function(require,module,exports){
4115 'use strict';
4116
4117 module.exports = Pbf;
4118
4119 var ieee754 = require('ieee754');
4120
4121 function Pbf(buf) {
4122     this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
4123     this.pos = 0;
4124     this.type = 0;
4125     this.length = this.buf.length;
4126 }
4127
4128 Pbf.Varint  = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
4129 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
4130 Pbf.Bytes   = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
4131 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
4132
4133 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
4134     SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
4135
4136 Pbf.prototype = {
4137
4138     destroy: function() {
4139         this.buf = null;
4140     },
4141
4142     // === READING =================================================================
4143
4144     readFields: function(readField, result, end) {
4145         end = end || this.length;
4146
4147         while (this.pos < end) {
4148             var val = this.readVarint(),
4149                 tag = val >> 3,
4150                 startPos = this.pos;
4151
4152             this.type = val & 0x7;
4153             readField(tag, result, this);
4154
4155             if (this.pos === startPos) this.skip(val);
4156         }
4157         return result;
4158     },
4159
4160     readMessage: function(readField, result) {
4161         return this.readFields(readField, result, this.readVarint() + this.pos);
4162     },
4163
4164     readFixed32: function() {
4165         var val = readUInt32(this.buf, this.pos);
4166         this.pos += 4;
4167         return val;
4168     },
4169
4170     readSFixed32: function() {
4171         var val = readInt32(this.buf, this.pos);
4172         this.pos += 4;
4173         return val;
4174     },
4175
4176     // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
4177
4178     readFixed64: function() {
4179         var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4180         this.pos += 8;
4181         return val;
4182     },
4183
4184     readSFixed64: function() {
4185         var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4186         this.pos += 8;
4187         return val;
4188     },
4189
4190     readFloat: function() {
4191         var val = ieee754.read(this.buf, this.pos, true, 23, 4);
4192         this.pos += 4;
4193         return val;
4194     },
4195
4196     readDouble: function() {
4197         var val = ieee754.read(this.buf, this.pos, true, 52, 8);
4198         this.pos += 8;
4199         return val;
4200     },
4201
4202     readVarint: function(isSigned) {
4203         var buf = this.buf,
4204             val, b;
4205
4206         b = buf[this.pos++]; val  =  b & 0x7f;        if (b < 0x80) return val;
4207         b = buf[this.pos++]; val |= (b & 0x7f) << 7;  if (b < 0x80) return val;
4208         b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
4209         b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
4210         b = buf[this.pos];   val |= (b & 0x0f) << 28;
4211
4212         return readVarintRemainder(val, isSigned, this);
4213     },
4214
4215     readVarint64: function() { // for compatibility with v2.0.1
4216         return this.readVarint(true);
4217     },
4218
4219     readSVarint: function() {
4220         var num = this.readVarint();
4221         return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
4222     },
4223
4224     readBoolean: function() {
4225         return Boolean(this.readVarint());
4226     },
4227
4228     readString: function() {
4229         var end = this.readVarint() + this.pos,
4230             str = readUtf8(this.buf, this.pos, end);
4231         this.pos = end;
4232         return str;
4233     },
4234
4235     readBytes: function() {
4236         var end = this.readVarint() + this.pos,
4237             buffer = this.buf.subarray(this.pos, end);
4238         this.pos = end;
4239         return buffer;
4240     },
4241
4242     // verbose for performance reasons; doesn't affect gzipped size
4243
4244     readPackedVarint: function(arr, isSigned) {
4245         var end = readPackedEnd(this);
4246         arr = arr || [];
4247         while (this.pos < end) arr.push(this.readVarint(isSigned));
4248         return arr;
4249     },
4250     readPackedSVarint: function(arr) {
4251         var end = readPackedEnd(this);
4252         arr = arr || [];
4253         while (this.pos < end) arr.push(this.readSVarint());
4254         return arr;
4255     },
4256     readPackedBoolean: function(arr) {
4257         var end = readPackedEnd(this);
4258         arr = arr || [];
4259         while (this.pos < end) arr.push(this.readBoolean());
4260         return arr;
4261     },
4262     readPackedFloat: function(arr) {
4263         var end = readPackedEnd(this);
4264         arr = arr || [];
4265         while (this.pos < end) arr.push(this.readFloat());
4266         return arr;
4267     },
4268     readPackedDouble: function(arr) {
4269         var end = readPackedEnd(this);
4270         arr = arr || [];
4271         while (this.pos < end) arr.push(this.readDouble());
4272         return arr;
4273     },
4274     readPackedFixed32: function(arr) {
4275         var end = readPackedEnd(this);
4276         arr = arr || [];
4277         while (this.pos < end) arr.push(this.readFixed32());
4278         return arr;
4279     },
4280     readPackedSFixed32: function(arr) {
4281         var end = readPackedEnd(this);
4282         arr = arr || [];
4283         while (this.pos < end) arr.push(this.readSFixed32());
4284         return arr;
4285     },
4286     readPackedFixed64: function(arr) {
4287         var end = readPackedEnd(this);
4288         arr = arr || [];
4289         while (this.pos < end) arr.push(this.readFixed64());
4290         return arr;
4291     },
4292     readPackedSFixed64: function(arr) {
4293         var end = readPackedEnd(this);
4294         arr = arr || [];
4295         while (this.pos < end) arr.push(this.readSFixed64());
4296         return arr;
4297     },
4298
4299     skip: function(val) {
4300         var type = val & 0x7;
4301         if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
4302         else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
4303         else if (type === Pbf.Fixed32) this.pos += 4;
4304         else if (type === Pbf.Fixed64) this.pos += 8;
4305         else throw new Error('Unimplemented type: ' + type);
4306     },
4307
4308     // === WRITING =================================================================
4309
4310     writeTag: function(tag, type) {
4311         this.writeVarint((tag << 3) | type);
4312     },
4313
4314     realloc: function(min) {
4315         var length = this.length || 16;
4316
4317         while (length < this.pos + min) length *= 2;
4318
4319         if (length !== this.length) {
4320             var buf = new Uint8Array(length);
4321             buf.set(this.buf);
4322             this.buf = buf;
4323             this.length = length;
4324         }
4325     },
4326
4327     finish: function() {
4328         this.length = this.pos;
4329         this.pos = 0;
4330         return this.buf.subarray(0, this.length);
4331     },
4332
4333     writeFixed32: function(val) {
4334         this.realloc(4);
4335         writeInt32(this.buf, val, this.pos);
4336         this.pos += 4;
4337     },
4338
4339     writeSFixed32: function(val) {
4340         this.realloc(4);
4341         writeInt32(this.buf, val, this.pos);
4342         this.pos += 4;
4343     },
4344
4345     writeFixed64: function(val) {
4346         this.realloc(8);
4347         writeInt32(this.buf, val & -1, this.pos);
4348         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4349         this.pos += 8;
4350     },
4351
4352     writeSFixed64: function(val) {
4353         this.realloc(8);
4354         writeInt32(this.buf, val & -1, this.pos);
4355         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4356         this.pos += 8;
4357     },
4358
4359     writeVarint: function(val) {
4360         val = +val || 0;
4361
4362         if (val > 0xfffffff || val < 0) {
4363             writeBigVarint(val, this);
4364             return;
4365         }
4366
4367         this.realloc(4);
4368
4369         this.buf[this.pos++] =           val & 0x7f  | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4370         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4371         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4372         this.buf[this.pos++] =   (val >>> 7) & 0x7f;
4373     },
4374
4375     writeSVarint: function(val) {
4376         this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
4377     },
4378
4379     writeBoolean: function(val) {
4380         this.writeVarint(Boolean(val));
4381     },
4382
4383     writeString: function(str) {
4384         str = String(str);
4385         this.realloc(str.length * 4);
4386
4387         this.pos++; // reserve 1 byte for short string length
4388
4389         var startPos = this.pos;
4390         // write the string directly to the buffer and see how much was written
4391         this.pos = writeUtf8(this.buf, str, this.pos);
4392         var len = this.pos - startPos;
4393
4394         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4395
4396         // finally, write the message length in the reserved place and restore the position
4397         this.pos = startPos - 1;
4398         this.writeVarint(len);
4399         this.pos += len;
4400     },
4401
4402     writeFloat: function(val) {
4403         this.realloc(4);
4404         ieee754.write(this.buf, val, this.pos, true, 23, 4);
4405         this.pos += 4;
4406     },
4407
4408     writeDouble: function(val) {
4409         this.realloc(8);
4410         ieee754.write(this.buf, val, this.pos, true, 52, 8);
4411         this.pos += 8;
4412     },
4413
4414     writeBytes: function(buffer) {
4415         var len = buffer.length;
4416         this.writeVarint(len);
4417         this.realloc(len);
4418         for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
4419     },
4420
4421     writeRawMessage: function(fn, obj) {
4422         this.pos++; // reserve 1 byte for short message length
4423
4424         // write the message directly to the buffer and see how much was written
4425         var startPos = this.pos;
4426         fn(obj, this);
4427         var len = this.pos - startPos;
4428
4429         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4430
4431         // finally, write the message length in the reserved place and restore the position
4432         this.pos = startPos - 1;
4433         this.writeVarint(len);
4434         this.pos += len;
4435     },
4436
4437     writeMessage: function(tag, fn, obj) {
4438         this.writeTag(tag, Pbf.Bytes);
4439         this.writeRawMessage(fn, obj);
4440     },
4441
4442     writePackedVarint:   function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr);   },
4443     writePackedSVarint:  function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr);  },
4444     writePackedBoolean:  function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr);  },
4445     writePackedFloat:    function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr);    },
4446     writePackedDouble:   function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr);   },
4447     writePackedFixed32:  function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr);  },
4448     writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
4449     writePackedFixed64:  function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr);  },
4450     writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
4451
4452     writeBytesField: function(tag, buffer) {
4453         this.writeTag(tag, Pbf.Bytes);
4454         this.writeBytes(buffer);
4455     },
4456     writeFixed32Field: function(tag, val) {
4457         this.writeTag(tag, Pbf.Fixed32);
4458         this.writeFixed32(val);
4459     },
4460     writeSFixed32Field: function(tag, val) {
4461         this.writeTag(tag, Pbf.Fixed32);
4462         this.writeSFixed32(val);
4463     },
4464     writeFixed64Field: function(tag, val) {
4465         this.writeTag(tag, Pbf.Fixed64);
4466         this.writeFixed64(val);
4467     },
4468     writeSFixed64Field: function(tag, val) {
4469         this.writeTag(tag, Pbf.Fixed64);
4470         this.writeSFixed64(val);
4471     },
4472     writeVarintField: function(tag, val) {
4473         this.writeTag(tag, Pbf.Varint);
4474         this.writeVarint(val);
4475     },
4476     writeSVarintField: function(tag, val) {
4477         this.writeTag(tag, Pbf.Varint);
4478         this.writeSVarint(val);
4479     },
4480     writeStringField: function(tag, str) {
4481         this.writeTag(tag, Pbf.Bytes);
4482         this.writeString(str);
4483     },
4484     writeFloatField: function(tag, val) {
4485         this.writeTag(tag, Pbf.Fixed32);
4486         this.writeFloat(val);
4487     },
4488     writeDoubleField: function(tag, val) {
4489         this.writeTag(tag, Pbf.Fixed64);
4490         this.writeDouble(val);
4491     },
4492     writeBooleanField: function(tag, val) {
4493         this.writeVarintField(tag, Boolean(val));
4494     }
4495 };
4496
4497 function readVarintRemainder(l, s, p) {
4498     var buf = p.buf,
4499         h, b;
4500
4501     b = buf[p.pos++]; h  = (b & 0x70) >> 4;  if (b < 0x80) return toNum(l, h, s);
4502     b = buf[p.pos++]; h |= (b & 0x7f) << 3;  if (b < 0x80) return toNum(l, h, s);
4503     b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
4504     b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
4505     b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
4506     b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
4507
4508     throw new Error('Expected varint not more than 10 bytes');
4509 }
4510
4511 function readPackedEnd(pbf) {
4512     return pbf.type === Pbf.Bytes ?
4513         pbf.readVarint() + pbf.pos : pbf.pos + 1;
4514 }
4515
4516 function toNum(low, high, isSigned) {
4517     if (isSigned) {
4518         return high * 0x100000000 + (low >>> 0);
4519     }
4520
4521     return ((high >>> 0) * 0x100000000) + (low >>> 0);
4522 }
4523
4524 function writeBigVarint(val, pbf) {
4525     var low, high;
4526
4527     if (val >= 0) {
4528         low  = (val % 0x100000000) | 0;
4529         high = (val / 0x100000000) | 0;
4530     } else {
4531         low  = ~(-val % 0x100000000);
4532         high = ~(-val / 0x100000000);
4533
4534         if (low ^ 0xffffffff) {
4535             low = (low + 1) | 0;
4536         } else {
4537             low = 0;
4538             high = (high + 1) | 0;
4539         }
4540     }
4541
4542     if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
4543         throw new Error('Given varint doesn\'t fit into 10 bytes');
4544     }
4545
4546     pbf.realloc(10);
4547
4548     writeBigVarintLow(low, high, pbf);
4549     writeBigVarintHigh(high, pbf);
4550 }
4551
4552 function writeBigVarintLow(low, high, pbf) {
4553     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4554     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4555     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4556     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4557     pbf.buf[pbf.pos]   = low & 0x7f;
4558 }
4559
4560 function writeBigVarintHigh(high, pbf) {
4561     var lsb = (high & 0x07) << 4;
4562
4563     pbf.buf[pbf.pos++] |= lsb         | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
4564     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4565     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4566     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4567     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4568     pbf.buf[pbf.pos++]  = high & 0x7f;
4569 }
4570
4571 function makeRoomForExtraLength(startPos, len, pbf) {
4572     var extraLen =
4573         len <= 0x3fff ? 1 :
4574         len <= 0x1fffff ? 2 :
4575         len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
4576
4577     // if 1 byte isn't enough for encoding message length, shift the data to the right
4578     pbf.realloc(extraLen);
4579     for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
4580 }
4581
4582 function writePackedVarint(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]);   }
4583 function writePackedSVarint(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]);  }
4584 function writePackedFloat(arr, pbf)    { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]);    }
4585 function writePackedDouble(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]);   }
4586 function writePackedBoolean(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]);  }
4587 function writePackedFixed32(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]);  }
4588 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
4589 function writePackedFixed64(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]);  }
4590 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
4591
4592 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
4593
4594 function readUInt32(buf, pos) {
4595     return ((buf[pos]) |
4596         (buf[pos + 1] << 8) |
4597         (buf[pos + 2] << 16)) +
4598         (buf[pos + 3] * 0x1000000);
4599 }
4600
4601 function writeInt32(buf, val, pos) {
4602     buf[pos] = val;
4603     buf[pos + 1] = (val >>> 8);
4604     buf[pos + 2] = (val >>> 16);
4605     buf[pos + 3] = (val >>> 24);
4606 }
4607
4608 function readInt32(buf, pos) {
4609     return ((buf[pos]) |
4610         (buf[pos + 1] << 8) |
4611         (buf[pos + 2] << 16)) +
4612         (buf[pos + 3] << 24);
4613 }
4614
4615 function readUtf8(buf, pos, end) {
4616     var str = '';
4617     var i = pos;
4618
4619     while (i < end) {
4620         var b0 = buf[i];
4621         var c = null; // codepoint
4622         var bytesPerSequence =
4623             b0 > 0xEF ? 4 :
4624             b0 > 0xDF ? 3 :
4625             b0 > 0xBF ? 2 : 1;
4626
4627         if (i + bytesPerSequence > end) break;
4628
4629         var b1, b2, b3;
4630
4631         if (bytesPerSequence === 1) {
4632             if (b0 < 0x80) {
4633                 c = b0;
4634             }
4635         } else if (bytesPerSequence === 2) {
4636             b1 = buf[i + 1];
4637             if ((b1 & 0xC0) === 0x80) {
4638                 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
4639                 if (c <= 0x7F) {
4640                     c = null;
4641                 }
4642             }
4643         } else if (bytesPerSequence === 3) {
4644             b1 = buf[i + 1];
4645             b2 = buf[i + 2];
4646             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
4647                 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
4648                 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
4649                     c = null;
4650                 }
4651             }
4652         } else if (bytesPerSequence === 4) {
4653             b1 = buf[i + 1];
4654             b2 = buf[i + 2];
4655             b3 = buf[i + 3];
4656             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
4657                 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
4658                 if (c <= 0xFFFF || c >= 0x110000) {
4659                     c = null;
4660                 }
4661             }
4662         }
4663
4664         if (c === null) {
4665             c = 0xFFFD;
4666             bytesPerSequence = 1;
4667
4668         } else if (c > 0xFFFF) {
4669             c -= 0x10000;
4670             str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
4671             c = 0xDC00 | c & 0x3FF;
4672         }
4673
4674         str += String.fromCharCode(c);
4675         i += bytesPerSequence;
4676     }
4677
4678     return str;
4679 }
4680
4681 function writeUtf8(buf, str, pos) {
4682     for (var i = 0, c, lead; i < str.length; i++) {
4683         c = str.charCodeAt(i); // code point
4684
4685         if (c > 0xD7FF && c < 0xE000) {
4686             if (lead) {
4687                 if (c < 0xDC00) {
4688                     buf[pos++] = 0xEF;
4689                     buf[pos++] = 0xBF;
4690                     buf[pos++] = 0xBD;
4691                     lead = c;
4692                     continue;
4693                 } else {
4694                     c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
4695                     lead = null;
4696                 }
4697             } else {
4698                 if (c > 0xDBFF || (i + 1 === str.length)) {
4699                     buf[pos++] = 0xEF;
4700                     buf[pos++] = 0xBF;
4701                     buf[pos++] = 0xBD;
4702                 } else {
4703                     lead = c;
4704                 }
4705                 continue;
4706             }
4707         } else if (lead) {
4708             buf[pos++] = 0xEF;
4709             buf[pos++] = 0xBF;
4710             buf[pos++] = 0xBD;
4711             lead = null;
4712         }
4713
4714         if (c < 0x80) {
4715             buf[pos++] = c;
4716         } else {
4717             if (c < 0x800) {
4718                 buf[pos++] = c >> 0x6 | 0xC0;
4719             } else {
4720                 if (c < 0x10000) {
4721                     buf[pos++] = c >> 0xC | 0xE0;
4722                 } else {
4723                     buf[pos++] = c >> 0x12 | 0xF0;
4724                     buf[pos++] = c >> 0xC & 0x3F | 0x80;
4725                 }
4726                 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
4727             }
4728             buf[pos++] = c & 0x3F | 0x80;
4729         }
4730     }
4731     return pos;
4732 }
4733
4734 },{"ieee754":17}],24:[function(require,module,exports){
4735 (function (global, factory) {
4736         typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
4737         typeof define === 'function' && define.amd ? define(factory) :
4738         (global.quickselect = factory());
4739 }(this, (function () { 'use strict';
4740
4741 function quickselect(arr, k, left, right, compare) {
4742     quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);
4743 }
4744
4745 function quickselectStep(arr, k, left, right, compare) {
4746
4747     while (right > left) {
4748         if (right - left > 600) {
4749             var n = right - left + 1;
4750             var m = k - left + 1;
4751             var z = Math.log(n);
4752             var s = 0.5 * Math.exp(2 * z / 3);
4753             var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
4754             var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
4755             var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
4756             quickselectStep(arr, k, newLeft, newRight, compare);
4757         }
4758
4759         var t = arr[k];
4760         var i = left;
4761         var j = right;
4762
4763         swap(arr, left, k);
4764         if (compare(arr[right], t) > 0) swap(arr, left, right);
4765
4766         while (i < j) {
4767             swap(arr, i, j);
4768             i++;
4769             j--;
4770             while (compare(arr[i], t) < 0) i++;
4771             while (compare(arr[j], t) > 0) j--;
4772         }
4773
4774         if (compare(arr[left], t) === 0) swap(arr, left, j);
4775         else {
4776             j++;
4777             swap(arr, j, right);
4778         }
4779
4780         if (j <= k) left = j + 1;
4781         if (k <= j) right = j - 1;
4782     }
4783 }
4784
4785 function swap(arr, i, j) {
4786     var tmp = arr[i];
4787     arr[i] = arr[j];
4788     arr[j] = tmp;
4789 }
4790
4791 function defaultCompare(a, b) {
4792     return a < b ? -1 : a > b ? 1 : 0;
4793 }
4794
4795 return quickselect;
4796
4797 })));
4798
4799 },{}],25:[function(require,module,exports){
4800 'use strict';
4801
4802 module.exports = rbush;
4803 module.exports.default = rbush;
4804
4805 var quickselect = require('quickselect');
4806
4807 function rbush(maxEntries, format) {
4808     if (!(this instanceof rbush)) return new rbush(maxEntries, format);
4809
4810     // max entries in a node is 9 by default; min node fill is 40% for best performance
4811     this._maxEntries = Math.max(4, maxEntries || 9);
4812     this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
4813
4814     if (format) {
4815         this._initFormat(format);
4816     }
4817
4818     this.clear();
4819 }
4820
4821 rbush.prototype = {
4822
4823     all: function () {
4824         return this._all(this.data, []);
4825     },
4826
4827     search: function (bbox) {
4828
4829         var node = this.data,
4830             result = [],
4831             toBBox = this.toBBox;
4832
4833         if (!intersects(bbox, node)) return result;
4834
4835         var nodesToSearch = [],
4836             i, len, child, childBBox;
4837
4838         while (node) {
4839             for (i = 0, len = node.children.length; i < len; i++) {
4840
4841                 child = node.children[i];
4842                 childBBox = node.leaf ? toBBox(child) : child;
4843
4844                 if (intersects(bbox, childBBox)) {
4845                     if (node.leaf) result.push(child);
4846                     else if (contains(bbox, childBBox)) this._all(child, result);
4847                     else nodesToSearch.push(child);
4848                 }
4849             }
4850             node = nodesToSearch.pop();
4851         }
4852
4853         return result;
4854     },
4855
4856     collides: function (bbox) {
4857
4858         var node = this.data,
4859             toBBox = this.toBBox;
4860
4861         if (!intersects(bbox, node)) return false;
4862
4863         var nodesToSearch = [],
4864             i, len, child, childBBox;
4865
4866         while (node) {
4867             for (i = 0, len = node.children.length; i < len; i++) {
4868
4869                 child = node.children[i];
4870                 childBBox = node.leaf ? toBBox(child) : child;
4871
4872                 if (intersects(bbox, childBBox)) {
4873                     if (node.leaf || contains(bbox, childBBox)) return true;
4874                     nodesToSearch.push(child);
4875                 }
4876             }
4877             node = nodesToSearch.pop();
4878         }
4879
4880         return false;
4881     },
4882
4883     load: function (data) {
4884         if (!(data && data.length)) return this;
4885
4886         if (data.length < this._minEntries) {
4887             for (var i = 0, len = data.length; i < len; i++) {
4888                 this.insert(data[i]);
4889             }
4890             return this;
4891         }
4892
4893         // recursively build the tree with the given data from scratch using OMT algorithm
4894         var node = this._build(data.slice(), 0, data.length - 1, 0);
4895
4896         if (!this.data.children.length) {
4897             // save as is if tree is empty
4898             this.data = node;
4899
4900         } else if (this.data.height === node.height) {
4901             // split root if trees have the same height
4902             this._splitRoot(this.data, node);
4903
4904         } else {
4905             if (this.data.height < node.height) {
4906                 // swap trees if inserted one is bigger
4907                 var tmpNode = this.data;
4908                 this.data = node;
4909                 node = tmpNode;
4910             }
4911
4912             // insert the small tree into the large tree at appropriate level
4913             this._insert(node, this.data.height - node.height - 1, true);
4914         }
4915
4916         return this;
4917     },
4918
4919     insert: function (item) {
4920         if (item) this._insert(item, this.data.height - 1);
4921         return this;
4922     },
4923
4924     clear: function () {
4925         this.data = createNode([]);
4926         return this;
4927     },
4928
4929     remove: function (item, equalsFn) {
4930         if (!item) return this;
4931
4932         var node = this.data,
4933             bbox = this.toBBox(item),
4934             path = [],
4935             indexes = [],
4936             i, parent, index, goingUp;
4937
4938         // depth-first iterative tree traversal
4939         while (node || path.length) {
4940
4941             if (!node) { // go up
4942                 node = path.pop();
4943                 parent = path[path.length - 1];
4944                 i = indexes.pop();
4945                 goingUp = true;
4946             }
4947
4948             if (node.leaf) { // check current node
4949                 index = findItem(item, node.children, equalsFn);
4950
4951                 if (index !== -1) {
4952                     // item found, remove the item and condense tree upwards
4953                     node.children.splice(index, 1);
4954                     path.push(node);
4955                     this._condense(path);
4956                     return this;
4957                 }
4958             }
4959
4960             if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
4961                 path.push(node);
4962                 indexes.push(i);
4963                 i = 0;
4964                 parent = node;
4965                 node = node.children[0];
4966
4967             } else if (parent) { // go right
4968                 i++;
4969                 node = parent.children[i];
4970                 goingUp = false;
4971
4972             } else node = null; // nothing found
4973         }
4974
4975         return this;
4976     },
4977
4978     toBBox: function (item) { return item; },
4979
4980     compareMinX: compareNodeMinX,
4981     compareMinY: compareNodeMinY,
4982
4983     toJSON: function () { return this.data; },
4984
4985     fromJSON: function (data) {
4986         this.data = data;
4987         return this;
4988     },
4989
4990     _all: function (node, result) {
4991         var nodesToSearch = [];
4992         while (node) {
4993             if (node.leaf) result.push.apply(result, node.children);
4994             else nodesToSearch.push.apply(nodesToSearch, node.children);
4995
4996             node = nodesToSearch.pop();
4997         }
4998         return result;
4999     },
5000
5001     _build: function (items, left, right, height) {
5002
5003         var N = right - left + 1,
5004             M = this._maxEntries,
5005             node;
5006
5007         if (N <= M) {
5008             // reached leaf level; return leaf
5009             node = createNode(items.slice(left, right + 1));
5010             calcBBox(node, this.toBBox);
5011             return node;
5012         }
5013
5014         if (!height) {
5015             // target height of the bulk-loaded tree
5016             height = Math.ceil(Math.log(N) / Math.log(M));
5017
5018             // target number of root entries to maximize storage utilization
5019             M = Math.ceil(N / Math.pow(M, height - 1));
5020         }
5021
5022         node = createNode([]);
5023         node.leaf = false;
5024         node.height = height;
5025
5026         // split the items into M mostly square tiles
5027
5028         var N2 = Math.ceil(N / M),
5029             N1 = N2 * Math.ceil(Math.sqrt(M)),
5030             i, j, right2, right3;
5031
5032         multiSelect(items, left, right, N1, this.compareMinX);
5033
5034         for (i = left; i <= right; i += N1) {
5035
5036             right2 = Math.min(i + N1 - 1, right);
5037
5038             multiSelect(items, i, right2, N2, this.compareMinY);
5039
5040             for (j = i; j <= right2; j += N2) {
5041
5042                 right3 = Math.min(j + N2 - 1, right2);
5043
5044                 // pack each entry recursively
5045                 node.children.push(this._build(items, j, right3, height - 1));
5046             }
5047         }
5048
5049         calcBBox(node, this.toBBox);
5050
5051         return node;
5052     },
5053
5054     _chooseSubtree: function (bbox, node, level, path) {
5055
5056         var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
5057
5058         while (true) {
5059             path.push(node);
5060
5061             if (node.leaf || path.length - 1 === level) break;
5062
5063             minArea = minEnlargement = Infinity;
5064
5065             for (i = 0, len = node.children.length; i < len; i++) {
5066                 child = node.children[i];
5067                 area = bboxArea(child);
5068                 enlargement = enlargedArea(bbox, child) - area;
5069
5070                 // choose entry with the least area enlargement
5071                 if (enlargement < minEnlargement) {
5072                     minEnlargement = enlargement;
5073                     minArea = area < minArea ? area : minArea;
5074                     targetNode = child;
5075
5076                 } else if (enlargement === minEnlargement) {
5077                     // otherwise choose one with the smallest area
5078                     if (area < minArea) {
5079                         minArea = area;
5080                         targetNode = child;
5081                     }
5082                 }
5083             }
5084
5085             node = targetNode || node.children[0];
5086         }
5087
5088         return node;
5089     },
5090
5091     _insert: function (item, level, isNode) {
5092
5093         var toBBox = this.toBBox,
5094             bbox = isNode ? item : toBBox(item),
5095             insertPath = [];
5096
5097         // find the best node for accommodating the item, saving all nodes along the path too
5098         var node = this._chooseSubtree(bbox, this.data, level, insertPath);
5099
5100         // put the item into the node
5101         node.children.push(item);
5102         extend(node, bbox);
5103
5104         // split on node overflow; propagate upwards if necessary
5105         while (level >= 0) {
5106             if (insertPath[level].children.length > this._maxEntries) {
5107                 this._split(insertPath, level);
5108                 level--;
5109             } else break;
5110         }
5111
5112         // adjust bboxes along the insertion path
5113         this._adjustParentBBoxes(bbox, insertPath, level);
5114     },
5115
5116     // split overflowed node into two
5117     _split: function (insertPath, level) {
5118
5119         var node = insertPath[level],
5120             M = node.children.length,
5121             m = this._minEntries;
5122
5123         this._chooseSplitAxis(node, m, M);
5124
5125         var splitIndex = this._chooseSplitIndex(node, m, M);
5126
5127         var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
5128         newNode.height = node.height;
5129         newNode.leaf = node.leaf;
5130
5131         calcBBox(node, this.toBBox);
5132         calcBBox(newNode, this.toBBox);
5133
5134         if (level) insertPath[level - 1].children.push(newNode);
5135         else this._splitRoot(node, newNode);
5136     },
5137
5138     _splitRoot: function (node, newNode) {
5139         // split root node
5140         this.data = createNode([node, newNode]);
5141         this.data.height = node.height + 1;
5142         this.data.leaf = false;
5143         calcBBox(this.data, this.toBBox);
5144     },
5145
5146     _chooseSplitIndex: function (node, m, M) {
5147
5148         var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
5149
5150         minOverlap = minArea = Infinity;
5151
5152         for (i = m; i <= M - m; i++) {
5153             bbox1 = distBBox(node, 0, i, this.toBBox);
5154             bbox2 = distBBox(node, i, M, this.toBBox);
5155
5156             overlap = intersectionArea(bbox1, bbox2);
5157             area = bboxArea(bbox1) + bboxArea(bbox2);
5158
5159             // choose distribution with minimum overlap
5160             if (overlap < minOverlap) {
5161                 minOverlap = overlap;
5162                 index = i;
5163
5164                 minArea = area < minArea ? area : minArea;
5165
5166             } else if (overlap === minOverlap) {
5167                 // otherwise choose distribution with minimum area
5168                 if (area < minArea) {
5169                     minArea = area;
5170                     index = i;
5171                 }
5172             }
5173         }
5174
5175         return index;
5176     },
5177
5178     // sorts node children by the best axis for split
5179     _chooseSplitAxis: function (node, m, M) {
5180
5181         var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
5182             compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
5183             xMargin = this._allDistMargin(node, m, M, compareMinX),
5184             yMargin = this._allDistMargin(node, m, M, compareMinY);
5185
5186         // if total distributions margin value is minimal for x, sort by minX,
5187         // otherwise it's already sorted by minY
5188         if (xMargin < yMargin) node.children.sort(compareMinX);
5189     },
5190
5191     // total margin of all possible split distributions where each node is at least m full
5192     _allDistMargin: function (node, m, M, compare) {
5193
5194         node.children.sort(compare);
5195
5196         var toBBox = this.toBBox,
5197             leftBBox = distBBox(node, 0, m, toBBox),
5198             rightBBox = distBBox(node, M - m, M, toBBox),
5199             margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
5200             i, child;
5201
5202         for (i = m; i < M - m; i++) {
5203             child = node.children[i];
5204             extend(leftBBox, node.leaf ? toBBox(child) : child);
5205             margin += bboxMargin(leftBBox);
5206         }
5207
5208         for (i = M - m - 1; i >= m; i--) {
5209             child = node.children[i];
5210             extend(rightBBox, node.leaf ? toBBox(child) : child);
5211             margin += bboxMargin(rightBBox);
5212         }
5213
5214         return margin;
5215     },
5216
5217     _adjustParentBBoxes: function (bbox, path, level) {
5218         // adjust bboxes along the given tree path
5219         for (var i = level; i >= 0; i--) {
5220             extend(path[i], bbox);
5221         }
5222     },
5223
5224     _condense: function (path) {
5225         // go through the path, removing empty nodes and updating bboxes
5226         for (var i = path.length - 1, siblings; i >= 0; i--) {
5227             if (path[i].children.length === 0) {
5228                 if (i > 0) {
5229                     siblings = path[i - 1].children;
5230                     siblings.splice(siblings.indexOf(path[i]), 1);
5231
5232                 } else this.clear();
5233
5234             } else calcBBox(path[i], this.toBBox);
5235         }
5236     },
5237
5238     _initFormat: function (format) {
5239         // data format (minX, minY, maxX, maxY accessors)
5240
5241         // uses eval-type function compilation instead of just accepting a toBBox function
5242         // because the algorithms are very sensitive to sorting functions performance,
5243         // so they should be dead simple and without inner calls
5244
5245         var compareArr = ['return a', ' - b', ';'];
5246
5247         this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
5248         this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
5249
5250         this.toBBox = new Function('a',
5251             'return {minX: a' + format[0] +
5252             ', minY: a' + format[1] +
5253             ', maxX: a' + format[2] +
5254             ', maxY: a' + format[3] + '};');
5255     }
5256 };
5257
5258 function findItem(item, items, equalsFn) {
5259     if (!equalsFn) return items.indexOf(item);
5260
5261     for (var i = 0; i < items.length; i++) {
5262         if (equalsFn(item, items[i])) return i;
5263     }
5264     return -1;
5265 }
5266
5267 // calculate node's bbox from bboxes of its children
5268 function calcBBox(node, toBBox) {
5269     distBBox(node, 0, node.children.length, toBBox, node);
5270 }
5271
5272 // min bounding rectangle of node children from k to p-1
5273 function distBBox(node, k, p, toBBox, destNode) {
5274     if (!destNode) destNode = createNode(null);
5275     destNode.minX = Infinity;
5276     destNode.minY = Infinity;
5277     destNode.maxX = -Infinity;
5278     destNode.maxY = -Infinity;
5279
5280     for (var i = k, child; i < p; i++) {
5281         child = node.children[i];
5282         extend(destNode, node.leaf ? toBBox(child) : child);
5283     }
5284
5285     return destNode;
5286 }
5287
5288 function extend(a, b) {
5289     a.minX = Math.min(a.minX, b.minX);
5290     a.minY = Math.min(a.minY, b.minY);
5291     a.maxX = Math.max(a.maxX, b.maxX);
5292     a.maxY = Math.max(a.maxY, b.maxY);
5293     return a;
5294 }
5295
5296 function compareNodeMinX(a, b) { return a.minX - b.minX; }
5297 function compareNodeMinY(a, b) { return a.minY - b.minY; }
5298
5299 function bboxArea(a)   { return (a.maxX - a.minX) * (a.maxY - a.minY); }
5300 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
5301
5302 function enlargedArea(a, b) {
5303     return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
5304            (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
5305 }
5306
5307 function intersectionArea(a, b) {
5308     var minX = Math.max(a.minX, b.minX),
5309         minY = Math.max(a.minY, b.minY),
5310         maxX = Math.min(a.maxX, b.maxX),
5311         maxY = Math.min(a.maxY, b.maxY);
5312
5313     return Math.max(0, maxX - minX) *
5314            Math.max(0, maxY - minY);
5315 }
5316
5317 function contains(a, b) {
5318     return a.minX <= b.minX &&
5319            a.minY <= b.minY &&
5320            b.maxX <= a.maxX &&
5321            b.maxY <= a.maxY;
5322 }
5323
5324 function intersects(a, b) {
5325     return b.minX <= a.maxX &&
5326            b.minY <= a.maxY &&
5327            b.maxX >= a.minX &&
5328            b.maxY >= a.minY;
5329 }
5330
5331 function createNode(children) {
5332     return {
5333         children: children,
5334         height: 1,
5335         leaf: true,
5336         minX: Infinity,
5337         minY: Infinity,
5338         maxX: -Infinity,
5339         maxY: -Infinity
5340     };
5341 }
5342
5343 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
5344 // combines selection algorithm with binary divide & conquer approach
5345
5346 function multiSelect(arr, left, right, n, compare) {
5347     var stack = [left, right],
5348         mid;
5349
5350     while (stack.length) {
5351         right = stack.pop();
5352         left = stack.pop();
5353
5354         if (right - left <= n) continue;
5355
5356         mid = left + Math.ceil((right - left) / n / 2) * n;
5357         quickselect(arr, mid, left, right, compare);
5358
5359         stack.push(left, mid, mid, right);
5360     }
5361 }
5362
5363 },{"quickselect":24}],26:[function(require,module,exports){
5364 "use strict";
5365 Object.defineProperty(exports, "__esModule", { value: true });
5366 var Observable_1 = require("./internal/Observable");
5367 exports.Observable = Observable_1.Observable;
5368 var ConnectableObservable_1 = require("./internal/observable/ConnectableObservable");
5369 exports.ConnectableObservable = ConnectableObservable_1.ConnectableObservable;
5370 var groupBy_1 = require("./internal/operators/groupBy");
5371 exports.GroupedObservable = groupBy_1.GroupedObservable;
5372 var observable_1 = require("./internal/symbol/observable");
5373 exports.observable = observable_1.observable;
5374 var Subject_1 = require("./internal/Subject");
5375 exports.Subject = Subject_1.Subject;
5376 var BehaviorSubject_1 = require("./internal/BehaviorSubject");
5377 exports.BehaviorSubject = BehaviorSubject_1.BehaviorSubject;
5378 var ReplaySubject_1 = require("./internal/ReplaySubject");
5379 exports.ReplaySubject = ReplaySubject_1.ReplaySubject;
5380 var AsyncSubject_1 = require("./internal/AsyncSubject");
5381 exports.AsyncSubject = AsyncSubject_1.AsyncSubject;
5382 var asap_1 = require("./internal/scheduler/asap");
5383 exports.asapScheduler = asap_1.asap;
5384 var async_1 = require("./internal/scheduler/async");
5385 exports.asyncScheduler = async_1.async;
5386 var queue_1 = require("./internal/scheduler/queue");
5387 exports.queueScheduler = queue_1.queue;
5388 var animationFrame_1 = require("./internal/scheduler/animationFrame");
5389 exports.animationFrameScheduler = animationFrame_1.animationFrame;
5390 var VirtualTimeScheduler_1 = require("./internal/scheduler/VirtualTimeScheduler");
5391 exports.VirtualTimeScheduler = VirtualTimeScheduler_1.VirtualTimeScheduler;
5392 exports.VirtualAction = VirtualTimeScheduler_1.VirtualAction;
5393 var Scheduler_1 = require("./internal/Scheduler");
5394 exports.Scheduler = Scheduler_1.Scheduler;
5395 var Subscription_1 = require("./internal/Subscription");
5396 exports.Subscription = Subscription_1.Subscription;
5397 var Subscriber_1 = require("./internal/Subscriber");
5398 exports.Subscriber = Subscriber_1.Subscriber;
5399 var Notification_1 = require("./internal/Notification");
5400 exports.Notification = Notification_1.Notification;
5401 var pipe_1 = require("./internal/util/pipe");
5402 exports.pipe = pipe_1.pipe;
5403 var noop_1 = require("./internal/util/noop");
5404 exports.noop = noop_1.noop;
5405 var identity_1 = require("./internal/util/identity");
5406 exports.identity = identity_1.identity;
5407 var isObservable_1 = require("./internal/util/isObservable");
5408 exports.isObservable = isObservable_1.isObservable;
5409 var ArgumentOutOfRangeError_1 = require("./internal/util/ArgumentOutOfRangeError");
5410 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
5411 var EmptyError_1 = require("./internal/util/EmptyError");
5412 exports.EmptyError = EmptyError_1.EmptyError;
5413 var ObjectUnsubscribedError_1 = require("./internal/util/ObjectUnsubscribedError");
5414 exports.ObjectUnsubscribedError = ObjectUnsubscribedError_1.ObjectUnsubscribedError;
5415 var UnsubscriptionError_1 = require("./internal/util/UnsubscriptionError");
5416 exports.UnsubscriptionError = UnsubscriptionError_1.UnsubscriptionError;
5417 var TimeoutError_1 = require("./internal/util/TimeoutError");
5418 exports.TimeoutError = TimeoutError_1.TimeoutError;
5419 var bindCallback_1 = require("./internal/observable/bindCallback");
5420 exports.bindCallback = bindCallback_1.bindCallback;
5421 var bindNodeCallback_1 = require("./internal/observable/bindNodeCallback");
5422 exports.bindNodeCallback = bindNodeCallback_1.bindNodeCallback;
5423 var combineLatest_1 = require("./internal/observable/combineLatest");
5424 exports.combineLatest = combineLatest_1.combineLatest;
5425 var concat_1 = require("./internal/observable/concat");
5426 exports.concat = concat_1.concat;
5427 var defer_1 = require("./internal/observable/defer");
5428 exports.defer = defer_1.defer;
5429 var empty_1 = require("./internal/observable/empty");
5430 exports.empty = empty_1.empty;
5431 var forkJoin_1 = require("./internal/observable/forkJoin");
5432 exports.forkJoin = forkJoin_1.forkJoin;
5433 var from_1 = require("./internal/observable/from");
5434 exports.from = from_1.from;
5435 var fromEvent_1 = require("./internal/observable/fromEvent");
5436 exports.fromEvent = fromEvent_1.fromEvent;
5437 var fromEventPattern_1 = require("./internal/observable/fromEventPattern");
5438 exports.fromEventPattern = fromEventPattern_1.fromEventPattern;
5439 var generate_1 = require("./internal/observable/generate");
5440 exports.generate = generate_1.generate;
5441 var iif_1 = require("./internal/observable/iif");
5442 exports.iif = iif_1.iif;
5443 var interval_1 = require("./internal/observable/interval");
5444 exports.interval = interval_1.interval;
5445 var merge_1 = require("./internal/observable/merge");
5446 exports.merge = merge_1.merge;
5447 var never_1 = require("./internal/observable/never");
5448 exports.never = never_1.never;
5449 var of_1 = require("./internal/observable/of");
5450 exports.of = of_1.of;
5451 var onErrorResumeNext_1 = require("./internal/observable/onErrorResumeNext");
5452 exports.onErrorResumeNext = onErrorResumeNext_1.onErrorResumeNext;
5453 var pairs_1 = require("./internal/observable/pairs");
5454 exports.pairs = pairs_1.pairs;
5455 var race_1 = require("./internal/observable/race");
5456 exports.race = race_1.race;
5457 var range_1 = require("./internal/observable/range");
5458 exports.range = range_1.range;
5459 var throwError_1 = require("./internal/observable/throwError");
5460 exports.throwError = throwError_1.throwError;
5461 var timer_1 = require("./internal/observable/timer");
5462 exports.timer = timer_1.timer;
5463 var using_1 = require("./internal/observable/using");
5464 exports.using = using_1.using;
5465 var zip_1 = require("./internal/observable/zip");
5466 exports.zip = zip_1.zip;
5467 var empty_2 = require("./internal/observable/empty");
5468 exports.EMPTY = empty_2.EMPTY;
5469 var never_2 = require("./internal/observable/never");
5470 exports.NEVER = never_2.NEVER;
5471 var config_1 = require("./internal/config");
5472 exports.config = config_1.config;
5473
5474 },{"./internal/AsyncSubject":27,"./internal/BehaviorSubject":28,"./internal/Notification":30,"./internal/Observable":31,"./internal/ReplaySubject":34,"./internal/Scheduler":35,"./internal/Subject":36,"./internal/Subscriber":38,"./internal/Subscription":39,"./internal/config":40,"./internal/observable/ConnectableObservable":41,"./internal/observable/bindCallback":43,"./internal/observable/bindNodeCallback":44,"./internal/observable/combineLatest":45,"./internal/observable/concat":46,"./internal/observable/defer":47,"./internal/observable/empty":48,"./internal/observable/forkJoin":49,"./internal/observable/from":50,"./internal/observable/fromEvent":52,"./internal/observable/fromEventPattern":53,"./internal/observable/generate":57,"./internal/observable/iif":58,"./internal/observable/interval":59,"./internal/observable/merge":60,"./internal/observable/never":61,"./internal/observable/of":62,"./internal/observable/onErrorResumeNext":63,"./internal/observable/pairs":64,"./internal/observable/race":65,"./internal/observable/range":66,"./internal/observable/throwError":68,"./internal/observable/timer":69,"./internal/observable/using":70,"./internal/observable/zip":71,"./internal/operators/groupBy":107,"./internal/scheduler/VirtualTimeScheduler":184,"./internal/scheduler/animationFrame":185,"./internal/scheduler/asap":186,"./internal/scheduler/async":187,"./internal/scheduler/queue":188,"./internal/symbol/observable":190,"./internal/util/ArgumentOutOfRangeError":192,"./internal/util/EmptyError":193,"./internal/util/ObjectUnsubscribedError":195,"./internal/util/TimeoutError":196,"./internal/util/UnsubscriptionError":197,"./internal/util/identity":201,"./internal/util/isObservable":210,"./internal/util/noop":213,"./internal/util/pipe":215}],27:[function(require,module,exports){
5475 "use strict";
5476 var __extends = (this && this.__extends) || (function () {
5477     var extendStatics = function (d, b) {
5478         extendStatics = Object.setPrototypeOf ||
5479             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5480             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
5481         return extendStatics(d, b);
5482     }
5483     return function (d, b) {
5484         extendStatics(d, b);
5485         function __() { this.constructor = d; }
5486         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5487     };
5488 })();
5489 Object.defineProperty(exports, "__esModule", { value: true });
5490 var Subject_1 = require("./Subject");
5491 var Subscription_1 = require("./Subscription");
5492 var AsyncSubject = (function (_super) {
5493     __extends(AsyncSubject, _super);
5494     function AsyncSubject() {
5495         var _this = _super !== null && _super.apply(this, arguments) || this;
5496         _this.value = null;
5497         _this.hasNext = false;
5498         _this.hasCompleted = false;
5499         return _this;
5500     }
5501     AsyncSubject.prototype._subscribe = function (subscriber) {
5502         if (this.hasError) {
5503             subscriber.error(this.thrownError);
5504             return Subscription_1.Subscription.EMPTY;
5505         }
5506         else if (this.hasCompleted && this.hasNext) {
5507             subscriber.next(this.value);
5508             subscriber.complete();
5509             return Subscription_1.Subscription.EMPTY;
5510         }
5511         return _super.prototype._subscribe.call(this, subscriber);
5512     };
5513     AsyncSubject.prototype.next = function (value) {
5514         if (!this.hasCompleted) {
5515             this.value = value;
5516             this.hasNext = true;
5517         }
5518     };
5519     AsyncSubject.prototype.error = function (error) {
5520         if (!this.hasCompleted) {
5521             _super.prototype.error.call(this, error);
5522         }
5523     };
5524     AsyncSubject.prototype.complete = function () {
5525         this.hasCompleted = true;
5526         if (this.hasNext) {
5527             _super.prototype.next.call(this, this.value);
5528         }
5529         _super.prototype.complete.call(this);
5530     };
5531     return AsyncSubject;
5532 }(Subject_1.Subject));
5533 exports.AsyncSubject = AsyncSubject;
5534
5535 },{"./Subject":36,"./Subscription":39}],28:[function(require,module,exports){
5536 "use strict";
5537 var __extends = (this && this.__extends) || (function () {
5538     var extendStatics = function (d, b) {
5539         extendStatics = Object.setPrototypeOf ||
5540             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5541             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
5542         return extendStatics(d, b);
5543     }
5544     return function (d, b) {
5545         extendStatics(d, b);
5546         function __() { this.constructor = d; }
5547         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5548     };
5549 })();
5550 Object.defineProperty(exports, "__esModule", { value: true });
5551 var Subject_1 = require("./Subject");
5552 var ObjectUnsubscribedError_1 = require("./util/ObjectUnsubscribedError");
5553 var BehaviorSubject = (function (_super) {
5554     __extends(BehaviorSubject, _super);
5555     function BehaviorSubject(_value) {
5556         var _this = _super.call(this) || this;
5557         _this._value = _value;
5558         return _this;
5559     }
5560     Object.defineProperty(BehaviorSubject.prototype, "value", {
5561         get: function () {
5562             return this.getValue();
5563         },
5564         enumerable: true,
5565         configurable: true
5566     });
5567     BehaviorSubject.prototype._subscribe = function (subscriber) {
5568         var subscription = _super.prototype._subscribe.call(this, subscriber);
5569         if (subscription && !subscription.closed) {
5570             subscriber.next(this._value);
5571         }
5572         return subscription;
5573     };
5574     BehaviorSubject.prototype.getValue = function () {
5575         if (this.hasError) {
5576             throw this.thrownError;
5577         }
5578         else if (this.closed) {
5579             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5580         }
5581         else {
5582             return this._value;
5583         }
5584     };
5585     BehaviorSubject.prototype.next = function (value) {
5586         _super.prototype.next.call(this, this._value = value);
5587     };
5588     return BehaviorSubject;
5589 }(Subject_1.Subject));
5590 exports.BehaviorSubject = BehaviorSubject;
5591
5592 },{"./Subject":36,"./util/ObjectUnsubscribedError":195}],29:[function(require,module,exports){
5593 "use strict";
5594 var __extends = (this && this.__extends) || (function () {
5595     var extendStatics = function (d, b) {
5596         extendStatics = Object.setPrototypeOf ||
5597             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5598             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
5599         return extendStatics(d, b);
5600     }
5601     return function (d, b) {
5602         extendStatics(d, b);
5603         function __() { this.constructor = d; }
5604         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5605     };
5606 })();
5607 Object.defineProperty(exports, "__esModule", { value: true });
5608 var Subscriber_1 = require("./Subscriber");
5609 var InnerSubscriber = (function (_super) {
5610     __extends(InnerSubscriber, _super);
5611     function InnerSubscriber(parent, outerValue, outerIndex) {
5612         var _this = _super.call(this) || this;
5613         _this.parent = parent;
5614         _this.outerValue = outerValue;
5615         _this.outerIndex = outerIndex;
5616         _this.index = 0;
5617         return _this;
5618     }
5619     InnerSubscriber.prototype._next = function (value) {
5620         this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
5621     };
5622     InnerSubscriber.prototype._error = function (error) {
5623         this.parent.notifyError(error, this);
5624         this.unsubscribe();
5625     };
5626     InnerSubscriber.prototype._complete = function () {
5627         this.parent.notifyComplete(this);
5628         this.unsubscribe();
5629     };
5630     return InnerSubscriber;
5631 }(Subscriber_1.Subscriber));
5632 exports.InnerSubscriber = InnerSubscriber;
5633
5634 },{"./Subscriber":38}],30:[function(require,module,exports){
5635 "use strict";
5636 Object.defineProperty(exports, "__esModule", { value: true });
5637 var empty_1 = require("./observable/empty");
5638 var of_1 = require("./observable/of");
5639 var throwError_1 = require("./observable/throwError");
5640 var Notification = (function () {
5641     function Notification(kind, value, error) {
5642         this.kind = kind;
5643         this.value = value;
5644         this.error = error;
5645         this.hasValue = kind === 'N';
5646     }
5647     Notification.prototype.observe = function (observer) {
5648         switch (this.kind) {
5649             case 'N':
5650                 return observer.next && observer.next(this.value);
5651             case 'E':
5652                 return observer.error && observer.error(this.error);
5653             case 'C':
5654                 return observer.complete && observer.complete();
5655         }
5656     };
5657     Notification.prototype.do = function (next, error, complete) {
5658         var kind = this.kind;
5659         switch (kind) {
5660             case 'N':
5661                 return next && next(this.value);
5662             case 'E':
5663                 return error && error(this.error);
5664             case 'C':
5665                 return complete && complete();
5666         }
5667     };
5668     Notification.prototype.accept = function (nextOrObserver, error, complete) {
5669         if (nextOrObserver && typeof nextOrObserver.next === 'function') {
5670             return this.observe(nextOrObserver);
5671         }
5672         else {
5673             return this.do(nextOrObserver, error, complete);
5674         }
5675     };
5676     Notification.prototype.toObservable = function () {
5677         var kind = this.kind;
5678         switch (kind) {
5679             case 'N':
5680                 return of_1.of(this.value);
5681             case 'E':
5682                 return throwError_1.throwError(this.error);
5683             case 'C':
5684                 return empty_1.empty();
5685         }
5686         throw new Error('unexpected notification kind value');
5687     };
5688     Notification.createNext = function (value) {
5689         if (typeof value !== 'undefined') {
5690             return new Notification('N', value);
5691         }
5692         return Notification.undefinedValueNotification;
5693     };
5694     Notification.createError = function (err) {
5695         return new Notification('E', undefined, err);
5696     };
5697     Notification.createComplete = function () {
5698         return Notification.completeNotification;
5699     };
5700     Notification.completeNotification = new Notification('C');
5701     Notification.undefinedValueNotification = new Notification('N', undefined);
5702     return Notification;
5703 }());
5704 exports.Notification = Notification;
5705
5706 },{"./observable/empty":48,"./observable/of":62,"./observable/throwError":68}],31:[function(require,module,exports){
5707 "use strict";
5708 Object.defineProperty(exports, "__esModule", { value: true });
5709 var canReportError_1 = require("./util/canReportError");
5710 var toSubscriber_1 = require("./util/toSubscriber");
5711 var observable_1 = require("../internal/symbol/observable");
5712 var pipe_1 = require("./util/pipe");
5713 var config_1 = require("./config");
5714 var Observable = (function () {
5715     function Observable(subscribe) {
5716         this._isScalar = false;
5717         if (subscribe) {
5718             this._subscribe = subscribe;
5719         }
5720     }
5721     Observable.prototype.lift = function (operator) {
5722         var observable = new Observable();
5723         observable.source = this;
5724         observable.operator = operator;
5725         return observable;
5726     };
5727     Observable.prototype.subscribe = function (observerOrNext, error, complete) {
5728         var operator = this.operator;
5729         var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
5730         if (operator) {
5731             operator.call(sink, this.source);
5732         }
5733         else {
5734             sink.add(this.source || (config_1.config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
5735                 this._subscribe(sink) :
5736                 this._trySubscribe(sink));
5737         }
5738         if (config_1.config.useDeprecatedSynchronousErrorHandling) {
5739             if (sink.syncErrorThrowable) {
5740                 sink.syncErrorThrowable = false;
5741                 if (sink.syncErrorThrown) {
5742                     throw sink.syncErrorValue;
5743                 }
5744             }
5745         }
5746         return sink;
5747     };
5748     Observable.prototype._trySubscribe = function (sink) {
5749         try {
5750             return this._subscribe(sink);
5751         }
5752         catch (err) {
5753             if (config_1.config.useDeprecatedSynchronousErrorHandling) {
5754                 sink.syncErrorThrown = true;
5755                 sink.syncErrorValue = err;
5756             }
5757             if (canReportError_1.canReportError(sink)) {
5758                 sink.error(err);
5759             }
5760             else {
5761                 console.warn(err);
5762             }
5763         }
5764     };
5765     Observable.prototype.forEach = function (next, promiseCtor) {
5766         var _this = this;
5767         promiseCtor = getPromiseCtor(promiseCtor);
5768         return new promiseCtor(function (resolve, reject) {
5769             var subscription;
5770             subscription = _this.subscribe(function (value) {
5771                 try {
5772                     next(value);
5773                 }
5774                 catch (err) {
5775                     reject(err);
5776                     if (subscription) {
5777                         subscription.unsubscribe();
5778                     }
5779                 }
5780             }, reject, resolve);
5781         });
5782     };
5783     Observable.prototype._subscribe = function (subscriber) {
5784         var source = this.source;
5785         return source && source.subscribe(subscriber);
5786     };
5787     Observable.prototype[observable_1.observable] = function () {
5788         return this;
5789     };
5790     Observable.prototype.pipe = function () {
5791         var operations = [];
5792         for (var _i = 0; _i < arguments.length; _i++) {
5793             operations[_i] = arguments[_i];
5794         }
5795         if (operations.length === 0) {
5796             return this;
5797         }
5798         return pipe_1.pipeFromArray(operations)(this);
5799     };
5800     Observable.prototype.toPromise = function (promiseCtor) {
5801         var _this = this;
5802         promiseCtor = getPromiseCtor(promiseCtor);
5803         return new promiseCtor(function (resolve, reject) {
5804             var value;
5805             _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
5806         });
5807     };
5808     Observable.create = function (subscribe) {
5809         return new Observable(subscribe);
5810     };
5811     return Observable;
5812 }());
5813 exports.Observable = Observable;
5814 function getPromiseCtor(promiseCtor) {
5815     if (!promiseCtor) {
5816         promiseCtor = config_1.config.Promise || Promise;
5817     }
5818     if (!promiseCtor) {
5819         throw new Error('no Promise impl found');
5820     }
5821     return promiseCtor;
5822 }
5823
5824 },{"../internal/symbol/observable":190,"./config":40,"./util/canReportError":198,"./util/pipe":215,"./util/toSubscriber":222}],32:[function(require,module,exports){
5825 "use strict";
5826 Object.defineProperty(exports, "__esModule", { value: true });
5827 var config_1 = require("./config");
5828 var hostReportError_1 = require("./util/hostReportError");
5829 exports.empty = {
5830     closed: true,
5831     next: function (value) { },
5832     error: function (err) {
5833         if (config_1.config.useDeprecatedSynchronousErrorHandling) {
5834             throw err;
5835         }
5836         else {
5837             hostReportError_1.hostReportError(err);
5838         }
5839     },
5840     complete: function () { }
5841 };
5842
5843 },{"./config":40,"./util/hostReportError":200}],33:[function(require,module,exports){
5844 "use strict";
5845 var __extends = (this && this.__extends) || (function () {
5846     var extendStatics = function (d, b) {
5847         extendStatics = Object.setPrototypeOf ||
5848             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5849             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
5850         return extendStatics(d, b);
5851     }
5852     return function (d, b) {
5853         extendStatics(d, b);
5854         function __() { this.constructor = d; }
5855         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5856     };
5857 })();
5858 Object.defineProperty(exports, "__esModule", { value: true });
5859 var Subscriber_1 = require("./Subscriber");
5860 var OuterSubscriber = (function (_super) {
5861     __extends(OuterSubscriber, _super);
5862     function OuterSubscriber() {
5863         return _super !== null && _super.apply(this, arguments) || this;
5864     }
5865     OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5866         this.destination.next(innerValue);
5867     };
5868     OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5869         this.destination.error(error);
5870     };
5871     OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5872         this.destination.complete();
5873     };
5874     return OuterSubscriber;
5875 }(Subscriber_1.Subscriber));
5876 exports.OuterSubscriber = OuterSubscriber;
5877
5878 },{"./Subscriber":38}],34:[function(require,module,exports){
5879 "use strict";
5880 var __extends = (this && this.__extends) || (function () {
5881     var extendStatics = function (d, b) {
5882         extendStatics = Object.setPrototypeOf ||
5883             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5884             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
5885         return extendStatics(d, b);
5886     }
5887     return function (d, b) {
5888         extendStatics(d, b);
5889         function __() { this.constructor = d; }
5890         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5891     };
5892 })();
5893 Object.defineProperty(exports, "__esModule", { value: true });
5894 var Subject_1 = require("./Subject");
5895 var queue_1 = require("./scheduler/queue");
5896 var Subscription_1 = require("./Subscription");
5897 var observeOn_1 = require("./operators/observeOn");
5898 var ObjectUnsubscribedError_1 = require("./util/ObjectUnsubscribedError");
5899 var SubjectSubscription_1 = require("./SubjectSubscription");
5900 var ReplaySubject = (function (_super) {
5901     __extends(ReplaySubject, _super);
5902     function ReplaySubject(bufferSize, windowTime, scheduler) {
5903         if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5904         if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5905         var _this = _super.call(this) || this;
5906         _this.scheduler = scheduler;
5907         _this._events = [];
5908         _this._infiniteTimeWindow = false;
5909         _this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5910         _this._windowTime = windowTime < 1 ? 1 : windowTime;
5911         if (windowTime === Number.POSITIVE_INFINITY) {
5912             _this._infiniteTimeWindow = true;
5913             _this.next = _this.nextInfiniteTimeWindow;
5914         }
5915         else {
5916             _this.next = _this.nextTimeWindow;
5917         }
5918         return _this;
5919     }
5920     ReplaySubject.prototype.nextInfiniteTimeWindow = function (value) {
5921         var _events = this._events;
5922         _events.push(value);
5923         if (_events.length > this._bufferSize) {
5924             _events.shift();
5925         }
5926         _super.prototype.next.call(this, value);
5927     };
5928     ReplaySubject.prototype.nextTimeWindow = function (value) {
5929         this._events.push(new ReplayEvent(this._getNow(), value));
5930         this._trimBufferThenGetEvents();
5931         _super.prototype.next.call(this, value);
5932     };
5933     ReplaySubject.prototype._subscribe = function (subscriber) {
5934         var _infiniteTimeWindow = this._infiniteTimeWindow;
5935         var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();
5936         var scheduler = this.scheduler;
5937         var len = _events.length;
5938         var subscription;
5939         if (this.closed) {
5940             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5941         }
5942         else if (this.isStopped || this.hasError) {
5943             subscription = Subscription_1.Subscription.EMPTY;
5944         }
5945         else {
5946             this.observers.push(subscriber);
5947             subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5948         }
5949         if (scheduler) {
5950             subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5951         }
5952         if (_infiniteTimeWindow) {
5953             for (var i = 0; i < len && !subscriber.closed; i++) {
5954                 subscriber.next(_events[i]);
5955             }
5956         }
5957         else {
5958             for (var i = 0; i < len && !subscriber.closed; i++) {
5959                 subscriber.next(_events[i].value);
5960             }
5961         }
5962         if (this.hasError) {
5963             subscriber.error(this.thrownError);
5964         }
5965         else if (this.isStopped) {
5966             subscriber.complete();
5967         }
5968         return subscription;
5969     };
5970     ReplaySubject.prototype._getNow = function () {
5971         return (this.scheduler || queue_1.queue).now();
5972     };
5973     ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5974         var now = this._getNow();
5975         var _bufferSize = this._bufferSize;
5976         var _windowTime = this._windowTime;
5977         var _events = this._events;
5978         var eventsCount = _events.length;
5979         var spliceCount = 0;
5980         while (spliceCount < eventsCount) {
5981             if ((now - _events[spliceCount].time) < _windowTime) {
5982                 break;
5983             }
5984             spliceCount++;
5985         }
5986         if (eventsCount > _bufferSize) {
5987             spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5988         }
5989         if (spliceCount > 0) {
5990             _events.splice(0, spliceCount);
5991         }
5992         return _events;
5993     };
5994     return ReplaySubject;
5995 }(Subject_1.Subject));
5996 exports.ReplaySubject = ReplaySubject;
5997 var ReplayEvent = (function () {
5998     function ReplayEvent(time, value) {
5999         this.time = time;
6000         this.value = value;
6001     }
6002     return ReplayEvent;
6003 }());
6004
6005 },{"./Subject":36,"./SubjectSubscription":37,"./Subscription":39,"./operators/observeOn":122,"./scheduler/queue":188,"./util/ObjectUnsubscribedError":195}],35:[function(require,module,exports){
6006 "use strict";
6007 Object.defineProperty(exports, "__esModule", { value: true });
6008 var Scheduler = (function () {
6009     function Scheduler(SchedulerAction, now) {
6010         if (now === void 0) { now = Scheduler.now; }
6011         this.SchedulerAction = SchedulerAction;
6012         this.now = now;
6013     }
6014     Scheduler.prototype.schedule = function (work, delay, state) {
6015         if (delay === void 0) { delay = 0; }
6016         return new this.SchedulerAction(this, work).schedule(state, delay);
6017     };
6018     Scheduler.now = function () { return Date.now(); };
6019     return Scheduler;
6020 }());
6021 exports.Scheduler = Scheduler;
6022
6023 },{}],36:[function(require,module,exports){
6024 "use strict";
6025 var __extends = (this && this.__extends) || (function () {
6026     var extendStatics = function (d, b) {
6027         extendStatics = Object.setPrototypeOf ||
6028             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6029             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6030         return extendStatics(d, b);
6031     }
6032     return function (d, b) {
6033         extendStatics(d, b);
6034         function __() { this.constructor = d; }
6035         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6036     };
6037 })();
6038 Object.defineProperty(exports, "__esModule", { value: true });
6039 var Observable_1 = require("./Observable");
6040 var Subscriber_1 = require("./Subscriber");
6041 var Subscription_1 = require("./Subscription");
6042 var ObjectUnsubscribedError_1 = require("./util/ObjectUnsubscribedError");
6043 var SubjectSubscription_1 = require("./SubjectSubscription");
6044 var rxSubscriber_1 = require("../internal/symbol/rxSubscriber");
6045 var SubjectSubscriber = (function (_super) {
6046     __extends(SubjectSubscriber, _super);
6047     function SubjectSubscriber(destination) {
6048         var _this = _super.call(this, destination) || this;
6049         _this.destination = destination;
6050         return _this;
6051     }
6052     return SubjectSubscriber;
6053 }(Subscriber_1.Subscriber));
6054 exports.SubjectSubscriber = SubjectSubscriber;
6055 var Subject = (function (_super) {
6056     __extends(Subject, _super);
6057     function Subject() {
6058         var _this = _super.call(this) || this;
6059         _this.observers = [];
6060         _this.closed = false;
6061         _this.isStopped = false;
6062         _this.hasError = false;
6063         _this.thrownError = null;
6064         return _this;
6065     }
6066     Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
6067         return new SubjectSubscriber(this);
6068     };
6069     Subject.prototype.lift = function (operator) {
6070         var subject = new AnonymousSubject(this, this);
6071         subject.operator = operator;
6072         return subject;
6073     };
6074     Subject.prototype.next = function (value) {
6075         if (this.closed) {
6076             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6077         }
6078         if (!this.isStopped) {
6079             var observers = this.observers;
6080             var len = observers.length;
6081             var copy = observers.slice();
6082             for (var i = 0; i < len; i++) {
6083                 copy[i].next(value);
6084             }
6085         }
6086     };
6087     Subject.prototype.error = function (err) {
6088         if (this.closed) {
6089             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6090         }
6091         this.hasError = true;
6092         this.thrownError = err;
6093         this.isStopped = true;
6094         var observers = this.observers;
6095         var len = observers.length;
6096         var copy = observers.slice();
6097         for (var i = 0; i < len; i++) {
6098             copy[i].error(err);
6099         }
6100         this.observers.length = 0;
6101     };
6102     Subject.prototype.complete = function () {
6103         if (this.closed) {
6104             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6105         }
6106         this.isStopped = true;
6107         var observers = this.observers;
6108         var len = observers.length;
6109         var copy = observers.slice();
6110         for (var i = 0; i < len; i++) {
6111             copy[i].complete();
6112         }
6113         this.observers.length = 0;
6114     };
6115     Subject.prototype.unsubscribe = function () {
6116         this.isStopped = true;
6117         this.closed = true;
6118         this.observers = null;
6119     };
6120     Subject.prototype._trySubscribe = function (subscriber) {
6121         if (this.closed) {
6122             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6123         }
6124         else {
6125             return _super.prototype._trySubscribe.call(this, subscriber);
6126         }
6127     };
6128     Subject.prototype._subscribe = function (subscriber) {
6129         if (this.closed) {
6130             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6131         }
6132         else if (this.hasError) {
6133             subscriber.error(this.thrownError);
6134             return Subscription_1.Subscription.EMPTY;
6135         }
6136         else if (this.isStopped) {
6137             subscriber.complete();
6138             return Subscription_1.Subscription.EMPTY;
6139         }
6140         else {
6141             this.observers.push(subscriber);
6142             return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
6143         }
6144     };
6145     Subject.prototype.asObservable = function () {
6146         var observable = new Observable_1.Observable();
6147         observable.source = this;
6148         return observable;
6149     };
6150     Subject.create = function (destination, source) {
6151         return new AnonymousSubject(destination, source);
6152     };
6153     return Subject;
6154 }(Observable_1.Observable));
6155 exports.Subject = Subject;
6156 var AnonymousSubject = (function (_super) {
6157     __extends(AnonymousSubject, _super);
6158     function AnonymousSubject(destination, source) {
6159         var _this = _super.call(this) || this;
6160         _this.destination = destination;
6161         _this.source = source;
6162         return _this;
6163     }
6164     AnonymousSubject.prototype.next = function (value) {
6165         var destination = this.destination;
6166         if (destination && destination.next) {
6167             destination.next(value);
6168         }
6169     };
6170     AnonymousSubject.prototype.error = function (err) {
6171         var destination = this.destination;
6172         if (destination && destination.error) {
6173             this.destination.error(err);
6174         }
6175     };
6176     AnonymousSubject.prototype.complete = function () {
6177         var destination = this.destination;
6178         if (destination && destination.complete) {
6179             this.destination.complete();
6180         }
6181     };
6182     AnonymousSubject.prototype._subscribe = function (subscriber) {
6183         var source = this.source;
6184         if (source) {
6185             return this.source.subscribe(subscriber);
6186         }
6187         else {
6188             return Subscription_1.Subscription.EMPTY;
6189         }
6190     };
6191     return AnonymousSubject;
6192 }(Subject));
6193 exports.AnonymousSubject = AnonymousSubject;
6194
6195 },{"../internal/symbol/rxSubscriber":191,"./Observable":31,"./SubjectSubscription":37,"./Subscriber":38,"./Subscription":39,"./util/ObjectUnsubscribedError":195}],37:[function(require,module,exports){
6196 "use strict";
6197 var __extends = (this && this.__extends) || (function () {
6198     var extendStatics = function (d, b) {
6199         extendStatics = Object.setPrototypeOf ||
6200             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6201             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6202         return extendStatics(d, b);
6203     }
6204     return function (d, b) {
6205         extendStatics(d, b);
6206         function __() { this.constructor = d; }
6207         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6208     };
6209 })();
6210 Object.defineProperty(exports, "__esModule", { value: true });
6211 var Subscription_1 = require("./Subscription");
6212 var SubjectSubscription = (function (_super) {
6213     __extends(SubjectSubscription, _super);
6214     function SubjectSubscription(subject, subscriber) {
6215         var _this = _super.call(this) || this;
6216         _this.subject = subject;
6217         _this.subscriber = subscriber;
6218         _this.closed = false;
6219         return _this;
6220     }
6221     SubjectSubscription.prototype.unsubscribe = function () {
6222         if (this.closed) {
6223             return;
6224         }
6225         this.closed = true;
6226         var subject = this.subject;
6227         var observers = subject.observers;
6228         this.subject = null;
6229         if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
6230             return;
6231         }
6232         var subscriberIndex = observers.indexOf(this.subscriber);
6233         if (subscriberIndex !== -1) {
6234             observers.splice(subscriberIndex, 1);
6235         }
6236     };
6237     return SubjectSubscription;
6238 }(Subscription_1.Subscription));
6239 exports.SubjectSubscription = SubjectSubscription;
6240
6241 },{"./Subscription":39}],38:[function(require,module,exports){
6242 "use strict";
6243 var __extends = (this && this.__extends) || (function () {
6244     var extendStatics = function (d, b) {
6245         extendStatics = Object.setPrototypeOf ||
6246             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6247             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6248         return extendStatics(d, b);
6249     }
6250     return function (d, b) {
6251         extendStatics(d, b);
6252         function __() { this.constructor = d; }
6253         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6254     };
6255 })();
6256 Object.defineProperty(exports, "__esModule", { value: true });
6257 var isFunction_1 = require("./util/isFunction");
6258 var Observer_1 = require("./Observer");
6259 var Subscription_1 = require("./Subscription");
6260 var rxSubscriber_1 = require("../internal/symbol/rxSubscriber");
6261 var config_1 = require("./config");
6262 var hostReportError_1 = require("./util/hostReportError");
6263 var Subscriber = (function (_super) {
6264     __extends(Subscriber, _super);
6265     function Subscriber(destinationOrNext, error, complete) {
6266         var _this = _super.call(this) || this;
6267         _this.syncErrorValue = null;
6268         _this.syncErrorThrown = false;
6269         _this.syncErrorThrowable = false;
6270         _this.isStopped = false;
6271         _this._parentSubscription = null;
6272         switch (arguments.length) {
6273             case 0:
6274                 _this.destination = Observer_1.empty;
6275                 break;
6276             case 1:
6277                 if (!destinationOrNext) {
6278                     _this.destination = Observer_1.empty;
6279                     break;
6280                 }
6281                 if (typeof destinationOrNext === 'object') {
6282                     if (destinationOrNext instanceof Subscriber) {
6283                         _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
6284                         _this.destination = destinationOrNext;
6285                         destinationOrNext.add(_this);
6286                     }
6287                     else {
6288                         _this.syncErrorThrowable = true;
6289                         _this.destination = new SafeSubscriber(_this, destinationOrNext);
6290                     }
6291                     break;
6292                 }
6293             default:
6294                 _this.syncErrorThrowable = true;
6295                 _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);
6296                 break;
6297         }
6298         return _this;
6299     }
6300     Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
6301     Subscriber.create = function (next, error, complete) {
6302         var subscriber = new Subscriber(next, error, complete);
6303         subscriber.syncErrorThrowable = false;
6304         return subscriber;
6305     };
6306     Subscriber.prototype.next = function (value) {
6307         if (!this.isStopped) {
6308             this._next(value);
6309         }
6310     };
6311     Subscriber.prototype.error = function (err) {
6312         if (!this.isStopped) {
6313             this.isStopped = true;
6314             this._error(err);
6315         }
6316     };
6317     Subscriber.prototype.complete = function () {
6318         if (!this.isStopped) {
6319             this.isStopped = true;
6320             this._complete();
6321         }
6322     };
6323     Subscriber.prototype.unsubscribe = function () {
6324         if (this.closed) {
6325             return;
6326         }
6327         this.isStopped = true;
6328         _super.prototype.unsubscribe.call(this);
6329     };
6330     Subscriber.prototype._next = function (value) {
6331         this.destination.next(value);
6332     };
6333     Subscriber.prototype._error = function (err) {
6334         this.destination.error(err);
6335         this.unsubscribe();
6336     };
6337     Subscriber.prototype._complete = function () {
6338         this.destination.complete();
6339         this.unsubscribe();
6340     };
6341     Subscriber.prototype._unsubscribeAndRecycle = function () {
6342         var _a = this, _parent = _a._parent, _parents = _a._parents;
6343         this._parent = null;
6344         this._parents = null;
6345         this.unsubscribe();
6346         this.closed = false;
6347         this.isStopped = false;
6348         this._parent = _parent;
6349         this._parents = _parents;
6350         this._parentSubscription = null;
6351         return this;
6352     };
6353     return Subscriber;
6354 }(Subscription_1.Subscription));
6355 exports.Subscriber = Subscriber;
6356 var SafeSubscriber = (function (_super) {
6357     __extends(SafeSubscriber, _super);
6358     function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
6359         var _this = _super.call(this) || this;
6360         _this._parentSubscriber = _parentSubscriber;
6361         var next;
6362         var context = _this;
6363         if (isFunction_1.isFunction(observerOrNext)) {
6364             next = observerOrNext;
6365         }
6366         else if (observerOrNext) {
6367             next = observerOrNext.next;
6368             error = observerOrNext.error;
6369             complete = observerOrNext.complete;
6370             if (observerOrNext !== Observer_1.empty) {
6371                 context = Object.create(observerOrNext);
6372                 if (isFunction_1.isFunction(context.unsubscribe)) {
6373                     _this.add(context.unsubscribe.bind(context));
6374                 }
6375                 context.unsubscribe = _this.unsubscribe.bind(_this);
6376             }
6377         }
6378         _this._context = context;
6379         _this._next = next;
6380         _this._error = error;
6381         _this._complete = complete;
6382         return _this;
6383     }
6384     SafeSubscriber.prototype.next = function (value) {
6385         if (!this.isStopped && this._next) {
6386             var _parentSubscriber = this._parentSubscriber;
6387             if (!config_1.config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
6388                 this.__tryOrUnsub(this._next, value);
6389             }
6390             else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
6391                 this.unsubscribe();
6392             }
6393         }
6394     };
6395     SafeSubscriber.prototype.error = function (err) {
6396         if (!this.isStopped) {
6397             var _parentSubscriber = this._parentSubscriber;
6398             var useDeprecatedSynchronousErrorHandling = config_1.config.useDeprecatedSynchronousErrorHandling;
6399             if (this._error) {
6400                 if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
6401                     this.__tryOrUnsub(this._error, err);
6402                     this.unsubscribe();
6403                 }
6404                 else {
6405                     this.__tryOrSetError(_parentSubscriber, this._error, err);
6406                     this.unsubscribe();
6407                 }
6408             }
6409             else if (!_parentSubscriber.syncErrorThrowable) {
6410                 this.unsubscribe();
6411                 if (useDeprecatedSynchronousErrorHandling) {
6412                     throw err;
6413                 }
6414                 hostReportError_1.hostReportError(err);
6415             }
6416             else {
6417                 if (useDeprecatedSynchronousErrorHandling) {
6418                     _parentSubscriber.syncErrorValue = err;
6419                     _parentSubscriber.syncErrorThrown = true;
6420                 }
6421                 else {
6422                     hostReportError_1.hostReportError(err);
6423                 }
6424                 this.unsubscribe();
6425             }
6426         }
6427     };
6428     SafeSubscriber.prototype.complete = function () {
6429         var _this = this;
6430         if (!this.isStopped) {
6431             var _parentSubscriber = this._parentSubscriber;
6432             if (this._complete) {
6433                 var wrappedComplete = function () { return _this._complete.call(_this._context); };
6434                 if (!config_1.config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
6435                     this.__tryOrUnsub(wrappedComplete);
6436                     this.unsubscribe();
6437                 }
6438                 else {
6439                     this.__tryOrSetError(_parentSubscriber, wrappedComplete);
6440                     this.unsubscribe();
6441                 }
6442             }
6443             else {
6444                 this.unsubscribe();
6445             }
6446         }
6447     };
6448     SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6449         try {
6450             fn.call(this._context, value);
6451         }
6452         catch (err) {
6453             this.unsubscribe();
6454             if (config_1.config.useDeprecatedSynchronousErrorHandling) {
6455                 throw err;
6456             }
6457             else {
6458                 hostReportError_1.hostReportError(err);
6459             }
6460         }
6461     };
6462     SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6463         if (!config_1.config.useDeprecatedSynchronousErrorHandling) {
6464             throw new Error('bad call');
6465         }
6466         try {
6467             fn.call(this._context, value);
6468         }
6469         catch (err) {
6470             if (config_1.config.useDeprecatedSynchronousErrorHandling) {
6471                 parent.syncErrorValue = err;
6472                 parent.syncErrorThrown = true;
6473                 return true;
6474             }
6475             else {
6476                 hostReportError_1.hostReportError(err);
6477                 return true;
6478             }
6479         }
6480         return false;
6481     };
6482     SafeSubscriber.prototype._unsubscribe = function () {
6483         var _parentSubscriber = this._parentSubscriber;
6484         this._context = null;
6485         this._parentSubscriber = null;
6486         _parentSubscriber.unsubscribe();
6487     };
6488     return SafeSubscriber;
6489 }(Subscriber));
6490 exports.SafeSubscriber = SafeSubscriber;
6491
6492 },{"../internal/symbol/rxSubscriber":191,"./Observer":32,"./Subscription":39,"./config":40,"./util/hostReportError":200,"./util/isFunction":205}],39:[function(require,module,exports){
6493 "use strict";
6494 Object.defineProperty(exports, "__esModule", { value: true });
6495 var isArray_1 = require("./util/isArray");
6496 var isObject_1 = require("./util/isObject");
6497 var isFunction_1 = require("./util/isFunction");
6498 var tryCatch_1 = require("./util/tryCatch");
6499 var errorObject_1 = require("./util/errorObject");
6500 var UnsubscriptionError_1 = require("./util/UnsubscriptionError");
6501 var Subscription = (function () {
6502     function Subscription(unsubscribe) {
6503         this.closed = false;
6504         this._parent = null;
6505         this._parents = null;
6506         this._subscriptions = null;
6507         if (unsubscribe) {
6508             this._unsubscribe = unsubscribe;
6509         }
6510     }
6511     Subscription.prototype.unsubscribe = function () {
6512         var hasErrors = false;
6513         var errors;
6514         if (this.closed) {
6515             return;
6516         }
6517         var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6518         this.closed = true;
6519         this._parent = null;
6520         this._parents = null;
6521         this._subscriptions = null;
6522         var index = -1;
6523         var len = _parents ? _parents.length : 0;
6524         while (_parent) {
6525             _parent.remove(this);
6526             _parent = ++index < len && _parents[index] || null;
6527         }
6528         if (isFunction_1.isFunction(_unsubscribe)) {
6529             var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6530             if (trial === errorObject_1.errorObject) {
6531                 hasErrors = true;
6532                 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
6533                     flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
6534             }
6535         }
6536         if (isArray_1.isArray(_subscriptions)) {
6537             index = -1;
6538             len = _subscriptions.length;
6539             while (++index < len) {
6540                 var sub = _subscriptions[index];
6541                 if (isObject_1.isObject(sub)) {
6542                     var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6543                     if (trial === errorObject_1.errorObject) {
6544                         hasErrors = true;
6545                         errors = errors || [];
6546                         var err = errorObject_1.errorObject.e;
6547                         if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6548                             errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
6549                         }
6550                         else {
6551                             errors.push(err);
6552                         }
6553                     }
6554                 }
6555             }
6556         }
6557         if (hasErrors) {
6558             throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6559         }
6560     };
6561     Subscription.prototype.add = function (teardown) {
6562         if (!teardown || (teardown === Subscription.EMPTY)) {
6563             return Subscription.EMPTY;
6564         }
6565         if (teardown === this) {
6566             return this;
6567         }
6568         var subscription = teardown;
6569         switch (typeof teardown) {
6570             case 'function':
6571                 subscription = new Subscription(teardown);
6572             case 'object':
6573                 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
6574                     return subscription;
6575                 }
6576                 else if (this.closed) {
6577                     subscription.unsubscribe();
6578                     return subscription;
6579                 }
6580                 else if (typeof subscription._addParent !== 'function') {
6581                     var tmp = subscription;
6582                     subscription = new Subscription();
6583                     subscription._subscriptions = [tmp];
6584                 }
6585                 break;
6586             default:
6587                 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6588         }
6589         var subscriptions = this._subscriptions || (this._subscriptions = []);
6590         subscriptions.push(subscription);
6591         subscription._addParent(this);
6592         return subscription;
6593     };
6594     Subscription.prototype.remove = function (subscription) {
6595         var subscriptions = this._subscriptions;
6596         if (subscriptions) {
6597             var subscriptionIndex = subscriptions.indexOf(subscription);
6598             if (subscriptionIndex !== -1) {
6599                 subscriptions.splice(subscriptionIndex, 1);
6600             }
6601         }
6602     };
6603     Subscription.prototype._addParent = function (parent) {
6604         var _a = this, _parent = _a._parent, _parents = _a._parents;
6605         if (!_parent || _parent === parent) {
6606             this._parent = parent;
6607         }
6608         else if (!_parents) {
6609             this._parents = [parent];
6610         }
6611         else if (_parents.indexOf(parent) === -1) {
6612             _parents.push(parent);
6613         }
6614     };
6615     Subscription.EMPTY = (function (empty) {
6616         empty.closed = true;
6617         return empty;
6618     }(new Subscription()));
6619     return Subscription;
6620 }());
6621 exports.Subscription = Subscription;
6622 function flattenUnsubscriptionErrors(errors) {
6623     return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
6624 }
6625
6626 },{"./util/UnsubscriptionError":197,"./util/errorObject":199,"./util/isArray":202,"./util/isFunction":205,"./util/isObject":209,"./util/tryCatch":223}],40:[function(require,module,exports){
6627 "use strict";
6628 Object.defineProperty(exports, "__esModule", { value: true });
6629 var _enable_super_gross_mode_that_will_cause_bad_things = false;
6630 exports.config = {
6631     Promise: undefined,
6632     set useDeprecatedSynchronousErrorHandling(value) {
6633         if (value) {
6634             var error = new Error();
6635             console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
6636         }
6637         else if (_enable_super_gross_mode_that_will_cause_bad_things) {
6638             console.log('RxJS: Back to a better error behavior. Thank you. <3');
6639         }
6640         _enable_super_gross_mode_that_will_cause_bad_things = value;
6641     },
6642     get useDeprecatedSynchronousErrorHandling() {
6643         return _enable_super_gross_mode_that_will_cause_bad_things;
6644     },
6645 };
6646
6647 },{}],41:[function(require,module,exports){
6648 "use strict";
6649 var __extends = (this && this.__extends) || (function () {
6650     var extendStatics = function (d, b) {
6651         extendStatics = Object.setPrototypeOf ||
6652             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6653             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6654         return extendStatics(d, b);
6655     }
6656     return function (d, b) {
6657         extendStatics(d, b);
6658         function __() { this.constructor = d; }
6659         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6660     };
6661 })();
6662 Object.defineProperty(exports, "__esModule", { value: true });
6663 var Subject_1 = require("../Subject");
6664 var Observable_1 = require("../Observable");
6665 var Subscriber_1 = require("../Subscriber");
6666 var Subscription_1 = require("../Subscription");
6667 var refCount_1 = require("../operators/refCount");
6668 var ConnectableObservable = (function (_super) {
6669     __extends(ConnectableObservable, _super);
6670     function ConnectableObservable(source, subjectFactory) {
6671         var _this = _super.call(this) || this;
6672         _this.source = source;
6673         _this.subjectFactory = subjectFactory;
6674         _this._refCount = 0;
6675         _this._isComplete = false;
6676         return _this;
6677     }
6678     ConnectableObservable.prototype._subscribe = function (subscriber) {
6679         return this.getSubject().subscribe(subscriber);
6680     };
6681     ConnectableObservable.prototype.getSubject = function () {
6682         var subject = this._subject;
6683         if (!subject || subject.isStopped) {
6684             this._subject = this.subjectFactory();
6685         }
6686         return this._subject;
6687     };
6688     ConnectableObservable.prototype.connect = function () {
6689         var connection = this._connection;
6690         if (!connection) {
6691             this._isComplete = false;
6692             connection = this._connection = new Subscription_1.Subscription();
6693             connection.add(this.source
6694                 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
6695             if (connection.closed) {
6696                 this._connection = null;
6697                 connection = Subscription_1.Subscription.EMPTY;
6698             }
6699             else {
6700                 this._connection = connection;
6701             }
6702         }
6703         return connection;
6704     };
6705     ConnectableObservable.prototype.refCount = function () {
6706         return refCount_1.refCount()(this);
6707     };
6708     return ConnectableObservable;
6709 }(Observable_1.Observable));
6710 exports.ConnectableObservable = ConnectableObservable;
6711 var connectableProto = ConnectableObservable.prototype;
6712 exports.connectableObservableDescriptor = {
6713     operator: { value: null },
6714     _refCount: { value: 0, writable: true },
6715     _subject: { value: null, writable: true },
6716     _connection: { value: null, writable: true },
6717     _subscribe: { value: connectableProto._subscribe },
6718     _isComplete: { value: connectableProto._isComplete, writable: true },
6719     getSubject: { value: connectableProto.getSubject },
6720     connect: { value: connectableProto.connect },
6721     refCount: { value: connectableProto.refCount }
6722 };
6723 var ConnectableSubscriber = (function (_super) {
6724     __extends(ConnectableSubscriber, _super);
6725     function ConnectableSubscriber(destination, connectable) {
6726         var _this = _super.call(this, destination) || this;
6727         _this.connectable = connectable;
6728         return _this;
6729     }
6730     ConnectableSubscriber.prototype._error = function (err) {
6731         this._unsubscribe();
6732         _super.prototype._error.call(this, err);
6733     };
6734     ConnectableSubscriber.prototype._complete = function () {
6735         this.connectable._isComplete = true;
6736         this._unsubscribe();
6737         _super.prototype._complete.call(this);
6738     };
6739     ConnectableSubscriber.prototype._unsubscribe = function () {
6740         var connectable = this.connectable;
6741         if (connectable) {
6742             this.connectable = null;
6743             var connection = connectable._connection;
6744             connectable._refCount = 0;
6745             connectable._subject = null;
6746             connectable._connection = null;
6747             if (connection) {
6748                 connection.unsubscribe();
6749             }
6750         }
6751     };
6752     return ConnectableSubscriber;
6753 }(Subject_1.SubjectSubscriber));
6754 var RefCountOperator = (function () {
6755     function RefCountOperator(connectable) {
6756         this.connectable = connectable;
6757     }
6758     RefCountOperator.prototype.call = function (subscriber, source) {
6759         var connectable = this.connectable;
6760         connectable._refCount++;
6761         var refCounter = new RefCountSubscriber(subscriber, connectable);
6762         var subscription = source.subscribe(refCounter);
6763         if (!refCounter.closed) {
6764             refCounter.connection = connectable.connect();
6765         }
6766         return subscription;
6767     };
6768     return RefCountOperator;
6769 }());
6770 var RefCountSubscriber = (function (_super) {
6771     __extends(RefCountSubscriber, _super);
6772     function RefCountSubscriber(destination, connectable) {
6773         var _this = _super.call(this, destination) || this;
6774         _this.connectable = connectable;
6775         return _this;
6776     }
6777     RefCountSubscriber.prototype._unsubscribe = function () {
6778         var connectable = this.connectable;
6779         if (!connectable) {
6780             this.connection = null;
6781             return;
6782         }
6783         this.connectable = null;
6784         var refCount = connectable._refCount;
6785         if (refCount <= 0) {
6786             this.connection = null;
6787             return;
6788         }
6789         connectable._refCount = refCount - 1;
6790         if (refCount > 1) {
6791             this.connection = null;
6792             return;
6793         }
6794         var connection = this.connection;
6795         var sharedConnection = connectable._connection;
6796         this.connection = null;
6797         if (sharedConnection && (!connection || sharedConnection === connection)) {
6798             sharedConnection.unsubscribe();
6799         }
6800     };
6801     return RefCountSubscriber;
6802 }(Subscriber_1.Subscriber));
6803
6804 },{"../Observable":31,"../Subject":36,"../Subscriber":38,"../Subscription":39,"../operators/refCount":133}],42:[function(require,module,exports){
6805 "use strict";
6806 var __extends = (this && this.__extends) || (function () {
6807     var extendStatics = function (d, b) {
6808         extendStatics = Object.setPrototypeOf ||
6809             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6810             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6811         return extendStatics(d, b);
6812     }
6813     return function (d, b) {
6814         extendStatics(d, b);
6815         function __() { this.constructor = d; }
6816         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6817     };
6818 })();
6819 Object.defineProperty(exports, "__esModule", { value: true });
6820 var Observable_1 = require("../Observable");
6821 var asap_1 = require("../scheduler/asap");
6822 var isNumeric_1 = require("../util/isNumeric");
6823 var SubscribeOnObservable = (function (_super) {
6824     __extends(SubscribeOnObservable, _super);
6825     function SubscribeOnObservable(source, delayTime, scheduler) {
6826         if (delayTime === void 0) { delayTime = 0; }
6827         if (scheduler === void 0) { scheduler = asap_1.asap; }
6828         var _this = _super.call(this) || this;
6829         _this.source = source;
6830         _this.delayTime = delayTime;
6831         _this.scheduler = scheduler;
6832         if (!isNumeric_1.isNumeric(delayTime) || delayTime < 0) {
6833             _this.delayTime = 0;
6834         }
6835         if (!scheduler || typeof scheduler.schedule !== 'function') {
6836             _this.scheduler = asap_1.asap;
6837         }
6838         return _this;
6839     }
6840     SubscribeOnObservable.create = function (source, delay, scheduler) {
6841         if (delay === void 0) { delay = 0; }
6842         if (scheduler === void 0) { scheduler = asap_1.asap; }
6843         return new SubscribeOnObservable(source, delay, scheduler);
6844     };
6845     SubscribeOnObservable.dispatch = function (arg) {
6846         var source = arg.source, subscriber = arg.subscriber;
6847         return this.add(source.subscribe(subscriber));
6848     };
6849     SubscribeOnObservable.prototype._subscribe = function (subscriber) {
6850         var delay = this.delayTime;
6851         var source = this.source;
6852         var scheduler = this.scheduler;
6853         return scheduler.schedule(SubscribeOnObservable.dispatch, delay, {
6854             source: source, subscriber: subscriber
6855         });
6856     };
6857     return SubscribeOnObservable;
6858 }(Observable_1.Observable));
6859 exports.SubscribeOnObservable = SubscribeOnObservable;
6860
6861 },{"../Observable":31,"../scheduler/asap":186,"../util/isNumeric":208}],43:[function(require,module,exports){
6862 "use strict";
6863 Object.defineProperty(exports, "__esModule", { value: true });
6864 var Observable_1 = require("../Observable");
6865 var AsyncSubject_1 = require("../AsyncSubject");
6866 var map_1 = require("../operators/map");
6867 var canReportError_1 = require("../util/canReportError");
6868 var isArray_1 = require("../util/isArray");
6869 var isScheduler_1 = require("../util/isScheduler");
6870 function bindCallback(callbackFunc, resultSelector, scheduler) {
6871     if (resultSelector) {
6872         if (isScheduler_1.isScheduler(resultSelector)) {
6873             scheduler = resultSelector;
6874         }
6875         else {
6876             return function () {
6877                 var args = [];
6878                 for (var _i = 0; _i < arguments.length; _i++) {
6879                     args[_i] = arguments[_i];
6880                 }
6881                 return bindCallback(callbackFunc, scheduler).apply(void 0, args).pipe(map_1.map(function (args) { return isArray_1.isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
6882             };
6883         }
6884     }
6885     return function () {
6886         var args = [];
6887         for (var _i = 0; _i < arguments.length; _i++) {
6888             args[_i] = arguments[_i];
6889         }
6890         var context = this;
6891         var subject;
6892         var params = {
6893             context: context,
6894             subject: subject,
6895             callbackFunc: callbackFunc,
6896             scheduler: scheduler,
6897         };
6898         return new Observable_1.Observable(function (subscriber) {
6899             if (!scheduler) {
6900                 if (!subject) {
6901                     subject = new AsyncSubject_1.AsyncSubject();
6902                     var handler = function () {
6903                         var innerArgs = [];
6904                         for (var _i = 0; _i < arguments.length; _i++) {
6905                             innerArgs[_i] = arguments[_i];
6906                         }
6907                         subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
6908                         subject.complete();
6909                     };
6910                     try {
6911                         callbackFunc.apply(context, args.concat([handler]));
6912                     }
6913                     catch (err) {
6914                         if (canReportError_1.canReportError(subject)) {
6915                             subject.error(err);
6916                         }
6917                         else {
6918                             console.warn(err);
6919                         }
6920                     }
6921                 }
6922                 return subject.subscribe(subscriber);
6923             }
6924             else {
6925                 var state = {
6926                     args: args, subscriber: subscriber, params: params,
6927                 };
6928                 return scheduler.schedule(dispatch, 0, state);
6929             }
6930         });
6931     };
6932 }
6933 exports.bindCallback = bindCallback;
6934 function dispatch(state) {
6935     var _this = this;
6936     var self = this;
6937     var args = state.args, subscriber = state.subscriber, params = state.params;
6938     var callbackFunc = params.callbackFunc, context = params.context, scheduler = params.scheduler;
6939     var subject = params.subject;
6940     if (!subject) {
6941         subject = params.subject = new AsyncSubject_1.AsyncSubject();
6942         var handler = function () {
6943             var innerArgs = [];
6944             for (var _i = 0; _i < arguments.length; _i++) {
6945                 innerArgs[_i] = arguments[_i];
6946             }
6947             var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
6948             _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject }));
6949         };
6950         try {
6951             callbackFunc.apply(context, args.concat([handler]));
6952         }
6953         catch (err) {
6954             subject.error(err);
6955         }
6956     }
6957     this.add(subject.subscribe(subscriber));
6958 }
6959 function dispatchNext(state) {
6960     var value = state.value, subject = state.subject;
6961     subject.next(value);
6962     subject.complete();
6963 }
6964 function dispatchError(state) {
6965     var err = state.err, subject = state.subject;
6966     subject.error(err);
6967 }
6968
6969 },{"../AsyncSubject":27,"../Observable":31,"../operators/map":111,"../util/canReportError":198,"../util/isArray":202,"../util/isScheduler":212}],44:[function(require,module,exports){
6970 "use strict";
6971 Object.defineProperty(exports, "__esModule", { value: true });
6972 var Observable_1 = require("../Observable");
6973 var AsyncSubject_1 = require("../AsyncSubject");
6974 var map_1 = require("../operators/map");
6975 var canReportError_1 = require("../util/canReportError");
6976 var isScheduler_1 = require("../util/isScheduler");
6977 var isArray_1 = require("../util/isArray");
6978 function bindNodeCallback(callbackFunc, resultSelector, scheduler) {
6979     if (resultSelector) {
6980         if (isScheduler_1.isScheduler(resultSelector)) {
6981             scheduler = resultSelector;
6982         }
6983         else {
6984             return function () {
6985                 var args = [];
6986                 for (var _i = 0; _i < arguments.length; _i++) {
6987                     args[_i] = arguments[_i];
6988                 }
6989                 return bindNodeCallback(callbackFunc, scheduler).apply(void 0, args).pipe(map_1.map(function (args) { return isArray_1.isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
6990             };
6991         }
6992     }
6993     return function () {
6994         var args = [];
6995         for (var _i = 0; _i < arguments.length; _i++) {
6996             args[_i] = arguments[_i];
6997         }
6998         var params = {
6999             subject: undefined,
7000             args: args,
7001             callbackFunc: callbackFunc,
7002             scheduler: scheduler,
7003             context: this,
7004         };
7005         return new Observable_1.Observable(function (subscriber) {
7006             var context = params.context;
7007             var subject = params.subject;
7008             if (!scheduler) {
7009                 if (!subject) {
7010                     subject = params.subject = new AsyncSubject_1.AsyncSubject();
7011                     var handler = function () {
7012                         var innerArgs = [];
7013                         for (var _i = 0; _i < arguments.length; _i++) {
7014                             innerArgs[_i] = arguments[_i];
7015                         }
7016                         var err = innerArgs.shift();
7017                         if (err) {
7018                             subject.error(err);
7019                             return;
7020                         }
7021                         subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
7022                         subject.complete();
7023                     };
7024                     try {
7025                         callbackFunc.apply(context, args.concat([handler]));
7026                     }
7027                     catch (err) {
7028                         if (canReportError_1.canReportError(subject)) {
7029                             subject.error(err);
7030                         }
7031                         else {
7032                             console.warn(err);
7033                         }
7034                     }
7035                 }
7036                 return subject.subscribe(subscriber);
7037             }
7038             else {
7039                 return scheduler.schedule(dispatch, 0, { params: params, subscriber: subscriber, context: context });
7040             }
7041         });
7042     };
7043 }
7044 exports.bindNodeCallback = bindNodeCallback;
7045 function dispatch(state) {
7046     var _this = this;
7047     var params = state.params, subscriber = state.subscriber, context = state.context;
7048     var callbackFunc = params.callbackFunc, args = params.args, scheduler = params.scheduler;
7049     var subject = params.subject;
7050     if (!subject) {
7051         subject = params.subject = new AsyncSubject_1.AsyncSubject();
7052         var handler = function () {
7053             var innerArgs = [];
7054             for (var _i = 0; _i < arguments.length; _i++) {
7055                 innerArgs[_i] = arguments[_i];
7056             }
7057             var err = innerArgs.shift();
7058             if (err) {
7059                 _this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject }));
7060             }
7061             else {
7062                 var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
7063                 _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject }));
7064             }
7065         };
7066         try {
7067             callbackFunc.apply(context, args.concat([handler]));
7068         }
7069         catch (err) {
7070             this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject }));
7071         }
7072     }
7073     this.add(subject.subscribe(subscriber));
7074 }
7075 function dispatchNext(arg) {
7076     var value = arg.value, subject = arg.subject;
7077     subject.next(value);
7078     subject.complete();
7079 }
7080 function dispatchError(arg) {
7081     var err = arg.err, subject = arg.subject;
7082     subject.error(err);
7083 }
7084
7085 },{"../AsyncSubject":27,"../Observable":31,"../operators/map":111,"../util/canReportError":198,"../util/isArray":202,"../util/isScheduler":212}],45:[function(require,module,exports){
7086 "use strict";
7087 var __extends = (this && this.__extends) || (function () {
7088     var extendStatics = function (d, b) {
7089         extendStatics = Object.setPrototypeOf ||
7090             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7091             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7092         return extendStatics(d, b);
7093     }
7094     return function (d, b) {
7095         extendStatics(d, b);
7096         function __() { this.constructor = d; }
7097         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7098     };
7099 })();
7100 Object.defineProperty(exports, "__esModule", { value: true });
7101 var isScheduler_1 = require("../util/isScheduler");
7102 var isArray_1 = require("../util/isArray");
7103 var OuterSubscriber_1 = require("../OuterSubscriber");
7104 var subscribeToResult_1 = require("../util/subscribeToResult");
7105 var fromArray_1 = require("./fromArray");
7106 var NONE = {};
7107 function combineLatest() {
7108     var observables = [];
7109     for (var _i = 0; _i < arguments.length; _i++) {
7110         observables[_i] = arguments[_i];
7111     }
7112     var resultSelector = null;
7113     var scheduler = null;
7114     if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
7115         scheduler = observables.pop();
7116     }
7117     if (typeof observables[observables.length - 1] === 'function') {
7118         resultSelector = observables.pop();
7119     }
7120     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
7121         observables = observables[0];
7122     }
7123     return fromArray_1.fromArray(observables, scheduler).lift(new CombineLatestOperator(resultSelector));
7124 }
7125 exports.combineLatest = combineLatest;
7126 var CombineLatestOperator = (function () {
7127     function CombineLatestOperator(resultSelector) {
7128         this.resultSelector = resultSelector;
7129     }
7130     CombineLatestOperator.prototype.call = function (subscriber, source) {
7131         return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));
7132     };
7133     return CombineLatestOperator;
7134 }());
7135 exports.CombineLatestOperator = CombineLatestOperator;
7136 var CombineLatestSubscriber = (function (_super) {
7137     __extends(CombineLatestSubscriber, _super);
7138     function CombineLatestSubscriber(destination, resultSelector) {
7139         var _this = _super.call(this, destination) || this;
7140         _this.resultSelector = resultSelector;
7141         _this.active = 0;
7142         _this.values = [];
7143         _this.observables = [];
7144         return _this;
7145     }
7146     CombineLatestSubscriber.prototype._next = function (observable) {
7147         this.values.push(NONE);
7148         this.observables.push(observable);
7149     };
7150     CombineLatestSubscriber.prototype._complete = function () {
7151         var observables = this.observables;
7152         var len = observables.length;
7153         if (len === 0) {
7154             this.destination.complete();
7155         }
7156         else {
7157             this.active = len;
7158             this.toRespond = len;
7159             for (var i = 0; i < len; i++) {
7160                 var observable = observables[i];
7161                 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
7162             }
7163         }
7164     };
7165     CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
7166         if ((this.active -= 1) === 0) {
7167             this.destination.complete();
7168         }
7169     };
7170     CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
7171         var values = this.values;
7172         var oldVal = values[outerIndex];
7173         var toRespond = !this.toRespond
7174             ? 0
7175             : oldVal === NONE ? --this.toRespond : this.toRespond;
7176         values[outerIndex] = innerValue;
7177         if (toRespond === 0) {
7178             if (this.resultSelector) {
7179                 this._tryResultSelector(values);
7180             }
7181             else {
7182                 this.destination.next(values.slice());
7183             }
7184         }
7185     };
7186     CombineLatestSubscriber.prototype._tryResultSelector = function (values) {
7187         var result;
7188         try {
7189             result = this.resultSelector.apply(this, values);
7190         }
7191         catch (err) {
7192             this.destination.error(err);
7193             return;
7194         }
7195         this.destination.next(result);
7196     };
7197     return CombineLatestSubscriber;
7198 }(OuterSubscriber_1.OuterSubscriber));
7199 exports.CombineLatestSubscriber = CombineLatestSubscriber;
7200
7201 },{"../OuterSubscriber":33,"../util/isArray":202,"../util/isScheduler":212,"../util/subscribeToResult":221,"./fromArray":51}],46:[function(require,module,exports){
7202 "use strict";
7203 Object.defineProperty(exports, "__esModule", { value: true });
7204 var isScheduler_1 = require("../util/isScheduler");
7205 var of_1 = require("./of");
7206 var from_1 = require("./from");
7207 var concatAll_1 = require("../operators/concatAll");
7208 function concat() {
7209     var observables = [];
7210     for (var _i = 0; _i < arguments.length; _i++) {
7211         observables[_i] = arguments[_i];
7212     }
7213     if (observables.length === 1 || (observables.length === 2 && isScheduler_1.isScheduler(observables[1]))) {
7214         return from_1.from(observables[0]);
7215     }
7216     return concatAll_1.concatAll()(of_1.of.apply(void 0, observables));
7217 }
7218 exports.concat = concat;
7219
7220 },{"../operators/concatAll":83,"../util/isScheduler":212,"./from":50,"./of":62}],47:[function(require,module,exports){
7221 "use strict";
7222 Object.defineProperty(exports, "__esModule", { value: true });
7223 var Observable_1 = require("../Observable");
7224 var from_1 = require("./from");
7225 var empty_1 = require("./empty");
7226 function defer(observableFactory) {
7227     return new Observable_1.Observable(function (subscriber) {
7228         var input;
7229         try {
7230             input = observableFactory();
7231         }
7232         catch (err) {
7233             subscriber.error(err);
7234             return undefined;
7235         }
7236         var source = input ? from_1.from(input) : empty_1.empty();
7237         return source.subscribe(subscriber);
7238     });
7239 }
7240 exports.defer = defer;
7241
7242 },{"../Observable":31,"./empty":48,"./from":50}],48:[function(require,module,exports){
7243 "use strict";
7244 Object.defineProperty(exports, "__esModule", { value: true });
7245 var Observable_1 = require("../Observable");
7246 exports.EMPTY = new Observable_1.Observable(function (subscriber) { return subscriber.complete(); });
7247 function empty(scheduler) {
7248     return scheduler ? emptyScheduled(scheduler) : exports.EMPTY;
7249 }
7250 exports.empty = empty;
7251 function emptyScheduled(scheduler) {
7252     return new Observable_1.Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); });
7253 }
7254 exports.emptyScheduled = emptyScheduled;
7255
7256 },{"../Observable":31}],49:[function(require,module,exports){
7257 "use strict";
7258 var __extends = (this && this.__extends) || (function () {
7259     var extendStatics = function (d, b) {
7260         extendStatics = Object.setPrototypeOf ||
7261             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7262             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7263         return extendStatics(d, b);
7264     }
7265     return function (d, b) {
7266         extendStatics(d, b);
7267         function __() { this.constructor = d; }
7268         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7269     };
7270 })();
7271 Object.defineProperty(exports, "__esModule", { value: true });
7272 var Observable_1 = require("../Observable");
7273 var isArray_1 = require("../util/isArray");
7274 var empty_1 = require("./empty");
7275 var subscribeToResult_1 = require("../util/subscribeToResult");
7276 var OuterSubscriber_1 = require("../OuterSubscriber");
7277 var map_1 = require("../operators/map");
7278 function forkJoin() {
7279     var sources = [];
7280     for (var _i = 0; _i < arguments.length; _i++) {
7281         sources[_i] = arguments[_i];
7282     }
7283     var resultSelector;
7284     if (typeof sources[sources.length - 1] === 'function') {
7285         resultSelector = sources.pop();
7286     }
7287     if (sources.length === 1 && isArray_1.isArray(sources[0])) {
7288         sources = sources[0];
7289     }
7290     if (sources.length === 0) {
7291         return empty_1.EMPTY;
7292     }
7293     if (resultSelector) {
7294         return forkJoin(sources).pipe(map_1.map(function (args) { return resultSelector.apply(void 0, args); }));
7295     }
7296     return new Observable_1.Observable(function (subscriber) {
7297         return new ForkJoinSubscriber(subscriber, sources);
7298     });
7299 }
7300 exports.forkJoin = forkJoin;
7301 var ForkJoinSubscriber = (function (_super) {
7302     __extends(ForkJoinSubscriber, _super);
7303     function ForkJoinSubscriber(destination, sources) {
7304         var _this = _super.call(this, destination) || this;
7305         _this.sources = sources;
7306         _this.completed = 0;
7307         _this.haveValues = 0;
7308         var len = sources.length;
7309         _this.values = new Array(len);
7310         for (var i = 0; i < len; i++) {
7311             var source = sources[i];
7312             var innerSubscription = subscribeToResult_1.subscribeToResult(_this, source, null, i);
7313             if (innerSubscription) {
7314                 _this.add(innerSubscription);
7315             }
7316         }
7317         return _this;
7318     }
7319     ForkJoinSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
7320         this.values[outerIndex] = innerValue;
7321         if (!innerSub._hasValue) {
7322             innerSub._hasValue = true;
7323             this.haveValues++;
7324         }
7325     };
7326     ForkJoinSubscriber.prototype.notifyComplete = function (innerSub) {
7327         var _a = this, destination = _a.destination, haveValues = _a.haveValues, values = _a.values;
7328         var len = values.length;
7329         if (!innerSub._hasValue) {
7330             destination.complete();
7331             return;
7332         }
7333         this.completed++;
7334         if (this.completed !== len) {
7335             return;
7336         }
7337         if (haveValues === len) {
7338             destination.next(values);
7339         }
7340         destination.complete();
7341     };
7342     return ForkJoinSubscriber;
7343 }(OuterSubscriber_1.OuterSubscriber));
7344
7345 },{"../Observable":31,"../OuterSubscriber":33,"../operators/map":111,"../util/isArray":202,"../util/subscribeToResult":221,"./empty":48}],50:[function(require,module,exports){
7346 "use strict";
7347 Object.defineProperty(exports, "__esModule", { value: true });
7348 var Observable_1 = require("../Observable");
7349 var isPromise_1 = require("../util/isPromise");
7350 var isArrayLike_1 = require("../util/isArrayLike");
7351 var isInteropObservable_1 = require("../util/isInteropObservable");
7352 var isIterable_1 = require("../util/isIterable");
7353 var fromArray_1 = require("./fromArray");
7354 var fromPromise_1 = require("./fromPromise");
7355 var fromIterable_1 = require("./fromIterable");
7356 var fromObservable_1 = require("./fromObservable");
7357 var subscribeTo_1 = require("../util/subscribeTo");
7358 function from(input, scheduler) {
7359     if (!scheduler) {
7360         if (input instanceof Observable_1.Observable) {
7361             return input;
7362         }
7363         return new Observable_1.Observable(subscribeTo_1.subscribeTo(input));
7364     }
7365     if (input != null) {
7366         if (isInteropObservable_1.isInteropObservable(input)) {
7367             return fromObservable_1.fromObservable(input, scheduler);
7368         }
7369         else if (isPromise_1.isPromise(input)) {
7370             return fromPromise_1.fromPromise(input, scheduler);
7371         }
7372         else if (isArrayLike_1.isArrayLike(input)) {
7373             return fromArray_1.fromArray(input, scheduler);
7374         }
7375         else if (isIterable_1.isIterable(input) || typeof input === 'string') {
7376             return fromIterable_1.fromIterable(input, scheduler);
7377         }
7378     }
7379     throw new TypeError((input !== null && typeof input || input) + ' is not observable');
7380 }
7381 exports.from = from;
7382
7383 },{"../Observable":31,"../util/isArrayLike":203,"../util/isInteropObservable":206,"../util/isIterable":207,"../util/isPromise":211,"../util/subscribeTo":216,"./fromArray":51,"./fromIterable":54,"./fromObservable":55,"./fromPromise":56}],51:[function(require,module,exports){
7384 "use strict";
7385 Object.defineProperty(exports, "__esModule", { value: true });
7386 var Observable_1 = require("../Observable");
7387 var Subscription_1 = require("../Subscription");
7388 var subscribeToArray_1 = require("../util/subscribeToArray");
7389 function fromArray(input, scheduler) {
7390     if (!scheduler) {
7391         return new Observable_1.Observable(subscribeToArray_1.subscribeToArray(input));
7392     }
7393     else {
7394         return new Observable_1.Observable(function (subscriber) {
7395             var sub = new Subscription_1.Subscription();
7396             var i = 0;
7397             sub.add(scheduler.schedule(function () {
7398                 if (i === input.length) {
7399                     subscriber.complete();
7400                     return;
7401                 }
7402                 subscriber.next(input[i++]);
7403                 if (!subscriber.closed) {
7404                     sub.add(this.schedule());
7405                 }
7406             }));
7407             return sub;
7408         });
7409     }
7410 }
7411 exports.fromArray = fromArray;
7412
7413 },{"../Observable":31,"../Subscription":39,"../util/subscribeToArray":217}],52:[function(require,module,exports){
7414 "use strict";
7415 Object.defineProperty(exports, "__esModule", { value: true });
7416 var Observable_1 = require("../Observable");
7417 var isArray_1 = require("../util/isArray");
7418 var isFunction_1 = require("../util/isFunction");
7419 var map_1 = require("../operators/map");
7420 var toString = Object.prototype.toString;
7421 function fromEvent(target, eventName, options, resultSelector) {
7422     if (isFunction_1.isFunction(options)) {
7423         resultSelector = options;
7424         options = undefined;
7425     }
7426     if (resultSelector) {
7427         return fromEvent(target, eventName, options).pipe(map_1.map(function (args) { return isArray_1.isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
7428     }
7429     return new Observable_1.Observable(function (subscriber) {
7430         function handler(e) {
7431             if (arguments.length > 1) {
7432                 subscriber.next(Array.prototype.slice.call(arguments));
7433             }
7434             else {
7435                 subscriber.next(e);
7436             }
7437         }
7438         setupSubscription(target, eventName, handler, subscriber, options);
7439     });
7440 }
7441 exports.fromEvent = fromEvent;
7442 function setupSubscription(sourceObj, eventName, handler, subscriber, options) {
7443     var unsubscribe;
7444     if (isEventTarget(sourceObj)) {
7445         var source_1 = sourceObj;
7446         sourceObj.addEventListener(eventName, handler, options);
7447         unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); };
7448     }
7449     else if (isJQueryStyleEventEmitter(sourceObj)) {
7450         var source_2 = sourceObj;
7451         sourceObj.on(eventName, handler);
7452         unsubscribe = function () { return source_2.off(eventName, handler); };
7453     }
7454     else if (isNodeStyleEventEmitter(sourceObj)) {
7455         var source_3 = sourceObj;
7456         sourceObj.addListener(eventName, handler);
7457         unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7458     }
7459     else if (sourceObj && sourceObj.length) {
7460         for (var i = 0, len = sourceObj.length; i < len; i++) {
7461             setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7462         }
7463     }
7464     else {
7465         throw new TypeError('Invalid event target');
7466     }
7467     subscriber.add(unsubscribe);
7468 }
7469 function isNodeStyleEventEmitter(sourceObj) {
7470     return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7471 }
7472 function isJQueryStyleEventEmitter(sourceObj) {
7473     return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7474 }
7475 function isEventTarget(sourceObj) {
7476     return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7477 }
7478
7479 },{"../Observable":31,"../operators/map":111,"../util/isArray":202,"../util/isFunction":205}],53:[function(require,module,exports){
7480 "use strict";
7481 Object.defineProperty(exports, "__esModule", { value: true });
7482 var Observable_1 = require("../Observable");
7483 var isArray_1 = require("../util/isArray");
7484 var isFunction_1 = require("../util/isFunction");
7485 var map_1 = require("../operators/map");
7486 function fromEventPattern(addHandler, removeHandler, resultSelector) {
7487     if (resultSelector) {
7488         return fromEventPattern(addHandler, removeHandler).pipe(map_1.map(function (args) { return isArray_1.isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
7489     }
7490     return new Observable_1.Observable(function (subscriber) {
7491         var handler = function () {
7492             var e = [];
7493             for (var _i = 0; _i < arguments.length; _i++) {
7494                 e[_i] = arguments[_i];
7495             }
7496             return subscriber.next(e.length === 1 ? e[0] : e);
7497         };
7498         var retValue;
7499         try {
7500             retValue = addHandler(handler);
7501         }
7502         catch (err) {
7503             subscriber.error(err);
7504             return undefined;
7505         }
7506         if (!isFunction_1.isFunction(removeHandler)) {
7507             return undefined;
7508         }
7509         return function () { return removeHandler(handler, retValue); };
7510     });
7511 }
7512 exports.fromEventPattern = fromEventPattern;
7513
7514 },{"../Observable":31,"../operators/map":111,"../util/isArray":202,"../util/isFunction":205}],54:[function(require,module,exports){
7515 "use strict";
7516 Object.defineProperty(exports, "__esModule", { value: true });
7517 var Observable_1 = require("../Observable");
7518 var Subscription_1 = require("../Subscription");
7519 var iterator_1 = require("../symbol/iterator");
7520 var subscribeToIterable_1 = require("../util/subscribeToIterable");
7521 function fromIterable(input, scheduler) {
7522     if (!input) {
7523         throw new Error('Iterable cannot be null');
7524     }
7525     if (!scheduler) {
7526         return new Observable_1.Observable(subscribeToIterable_1.subscribeToIterable(input));
7527     }
7528     else {
7529         return new Observable_1.Observable(function (subscriber) {
7530             var sub = new Subscription_1.Subscription();
7531             var iterator;
7532             sub.add(function () {
7533                 if (iterator && typeof iterator.return === 'function') {
7534                     iterator.return();
7535                 }
7536             });
7537             sub.add(scheduler.schedule(function () {
7538                 iterator = input[iterator_1.iterator]();
7539                 sub.add(scheduler.schedule(function () {
7540                     if (subscriber.closed) {
7541                         return;
7542                     }
7543                     var value;
7544                     var done;
7545                     try {
7546                         var result = iterator.next();
7547                         value = result.value;
7548                         done = result.done;
7549                     }
7550                     catch (err) {
7551                         subscriber.error(err);
7552                         return;
7553                     }
7554                     if (done) {
7555                         subscriber.complete();
7556                     }
7557                     else {
7558                         subscriber.next(value);
7559                         this.schedule();
7560                     }
7561                 }));
7562             }));
7563             return sub;
7564         });
7565     }
7566 }
7567 exports.fromIterable = fromIterable;
7568
7569 },{"../Observable":31,"../Subscription":39,"../symbol/iterator":189,"../util/subscribeToIterable":218}],55:[function(require,module,exports){
7570 "use strict";
7571 Object.defineProperty(exports, "__esModule", { value: true });
7572 var Observable_1 = require("../Observable");
7573 var Subscription_1 = require("../Subscription");
7574 var observable_1 = require("../symbol/observable");
7575 var subscribeToObservable_1 = require("../util/subscribeToObservable");
7576 function fromObservable(input, scheduler) {
7577     if (!scheduler) {
7578         return new Observable_1.Observable(subscribeToObservable_1.subscribeToObservable(input));
7579     }
7580     else {
7581         return new Observable_1.Observable(function (subscriber) {
7582             var sub = new Subscription_1.Subscription();
7583             sub.add(scheduler.schedule(function () {
7584                 var observable = input[observable_1.observable]();
7585                 sub.add(observable.subscribe({
7586                     next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); },
7587                     error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); },
7588                     complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); },
7589                 }));
7590             }));
7591             return sub;
7592         });
7593     }
7594 }
7595 exports.fromObservable = fromObservable;
7596
7597 },{"../Observable":31,"../Subscription":39,"../symbol/observable":190,"../util/subscribeToObservable":219}],56:[function(require,module,exports){
7598 "use strict";
7599 Object.defineProperty(exports, "__esModule", { value: true });
7600 var Observable_1 = require("../Observable");
7601 var Subscription_1 = require("../Subscription");
7602 var subscribeToPromise_1 = require("../util/subscribeToPromise");
7603 function fromPromise(input, scheduler) {
7604     if (!scheduler) {
7605         return new Observable_1.Observable(subscribeToPromise_1.subscribeToPromise(input));
7606     }
7607     else {
7608         return new Observable_1.Observable(function (subscriber) {
7609             var sub = new Subscription_1.Subscription();
7610             sub.add(scheduler.schedule(function () { return input.then(function (value) {
7611                 sub.add(scheduler.schedule(function () {
7612                     subscriber.next(value);
7613                     sub.add(scheduler.schedule(function () { return subscriber.complete(); }));
7614                 }));
7615             }, function (err) {
7616                 sub.add(scheduler.schedule(function () { return subscriber.error(err); }));
7617             }); }));
7618             return sub;
7619         });
7620     }
7621 }
7622 exports.fromPromise = fromPromise;
7623
7624 },{"../Observable":31,"../Subscription":39,"../util/subscribeToPromise":220}],57:[function(require,module,exports){
7625 "use strict";
7626 Object.defineProperty(exports, "__esModule", { value: true });
7627 var Observable_1 = require("../Observable");
7628 var identity_1 = require("../util/identity");
7629 var isScheduler_1 = require("../util/isScheduler");
7630 function generate(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) {
7631     var resultSelector;
7632     var initialState;
7633     if (arguments.length == 1) {
7634         var options = initialStateOrOptions;
7635         initialState = options.initialState;
7636         condition = options.condition;
7637         iterate = options.iterate;
7638         resultSelector = options.resultSelector || identity_1.identity;
7639         scheduler = options.scheduler;
7640     }
7641     else if (resultSelectorOrObservable === undefined || isScheduler_1.isScheduler(resultSelectorOrObservable)) {
7642         initialState = initialStateOrOptions;
7643         resultSelector = identity_1.identity;
7644         scheduler = resultSelectorOrObservable;
7645     }
7646     else {
7647         initialState = initialStateOrOptions;
7648         resultSelector = resultSelectorOrObservable;
7649     }
7650     return new Observable_1.Observable(function (subscriber) {
7651         var state = initialState;
7652         if (scheduler) {
7653             return scheduler.schedule(dispatch, 0, {
7654                 subscriber: subscriber,
7655                 iterate: iterate,
7656                 condition: condition,
7657                 resultSelector: resultSelector,
7658                 state: state
7659             });
7660         }
7661         do {
7662             if (condition) {
7663                 var conditionResult = void 0;
7664                 try {
7665                     conditionResult = condition(state);
7666                 }
7667                 catch (err) {
7668                     subscriber.error(err);
7669                     return undefined;
7670                 }
7671                 if (!conditionResult) {
7672                     subscriber.complete();
7673                     break;
7674                 }
7675             }
7676             var value = void 0;
7677             try {
7678                 value = resultSelector(state);
7679             }
7680             catch (err) {
7681                 subscriber.error(err);
7682                 return undefined;
7683             }
7684             subscriber.next(value);
7685             if (subscriber.closed) {
7686                 break;
7687             }
7688             try {
7689                 state = iterate(state);
7690             }
7691             catch (err) {
7692                 subscriber.error(err);
7693                 return undefined;
7694             }
7695         } while (true);
7696         return undefined;
7697     });
7698 }
7699 exports.generate = generate;
7700 function dispatch(state) {
7701     var subscriber = state.subscriber, condition = state.condition;
7702     if (subscriber.closed) {
7703         return undefined;
7704     }
7705     if (state.needIterate) {
7706         try {
7707             state.state = state.iterate(state.state);
7708         }
7709         catch (err) {
7710             subscriber.error(err);
7711             return undefined;
7712         }
7713     }
7714     else {
7715         state.needIterate = true;
7716     }
7717     if (condition) {
7718         var conditionResult = void 0;
7719         try {
7720             conditionResult = condition(state.state);
7721         }
7722         catch (err) {
7723             subscriber.error(err);
7724             return undefined;
7725         }
7726         if (!conditionResult) {
7727             subscriber.complete();
7728             return undefined;
7729         }
7730         if (subscriber.closed) {
7731             return undefined;
7732         }
7733     }
7734     var value;
7735     try {
7736         value = state.resultSelector(state.state);
7737     }
7738     catch (err) {
7739         subscriber.error(err);
7740         return undefined;
7741     }
7742     if (subscriber.closed) {
7743         return undefined;
7744     }
7745     subscriber.next(value);
7746     if (subscriber.closed) {
7747         return undefined;
7748     }
7749     return this.schedule(state);
7750 }
7751
7752 },{"../Observable":31,"../util/identity":201,"../util/isScheduler":212}],58:[function(require,module,exports){
7753 "use strict";
7754 Object.defineProperty(exports, "__esModule", { value: true });
7755 var defer_1 = require("./defer");
7756 var empty_1 = require("./empty");
7757 function iif(condition, trueResult, falseResult) {
7758     if (trueResult === void 0) { trueResult = empty_1.EMPTY; }
7759     if (falseResult === void 0) { falseResult = empty_1.EMPTY; }
7760     return defer_1.defer(function () { return condition() ? trueResult : falseResult; });
7761 }
7762 exports.iif = iif;
7763
7764 },{"./defer":47,"./empty":48}],59:[function(require,module,exports){
7765 "use strict";
7766 Object.defineProperty(exports, "__esModule", { value: true });
7767 var Observable_1 = require("../Observable");
7768 var async_1 = require("../scheduler/async");
7769 var isNumeric_1 = require("../util/isNumeric");
7770 function interval(period, scheduler) {
7771     if (period === void 0) { period = 0; }
7772     if (scheduler === void 0) { scheduler = async_1.async; }
7773     if (!isNumeric_1.isNumeric(period) || period < 0) {
7774         period = 0;
7775     }
7776     if (!scheduler || typeof scheduler.schedule !== 'function') {
7777         scheduler = async_1.async;
7778     }
7779     return new Observable_1.Observable(function (subscriber) {
7780         subscriber.add(scheduler.schedule(dispatch, period, { subscriber: subscriber, counter: 0, period: period }));
7781         return subscriber;
7782     });
7783 }
7784 exports.interval = interval;
7785 function dispatch(state) {
7786     var subscriber = state.subscriber, counter = state.counter, period = state.period;
7787     subscriber.next(counter);
7788     this.schedule({ subscriber: subscriber, counter: counter + 1, period: period }, period);
7789 }
7790
7791 },{"../Observable":31,"../scheduler/async":187,"../util/isNumeric":208}],60:[function(require,module,exports){
7792 "use strict";
7793 Object.defineProperty(exports, "__esModule", { value: true });
7794 var Observable_1 = require("../Observable");
7795 var isScheduler_1 = require("../util/isScheduler");
7796 var mergeAll_1 = require("../operators/mergeAll");
7797 var fromArray_1 = require("./fromArray");
7798 function merge() {
7799     var observables = [];
7800     for (var _i = 0; _i < arguments.length; _i++) {
7801         observables[_i] = arguments[_i];
7802     }
7803     var concurrent = Number.POSITIVE_INFINITY;
7804     var scheduler = null;
7805     var last = observables[observables.length - 1];
7806     if (isScheduler_1.isScheduler(last)) {
7807         scheduler = observables.pop();
7808         if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
7809             concurrent = observables.pop();
7810         }
7811     }
7812     else if (typeof last === 'number') {
7813         concurrent = observables.pop();
7814     }
7815     if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
7816         return observables[0];
7817     }
7818     return mergeAll_1.mergeAll(concurrent)(fromArray_1.fromArray(observables, scheduler));
7819 }
7820 exports.merge = merge;
7821
7822 },{"../Observable":31,"../operators/mergeAll":116,"../util/isScheduler":212,"./fromArray":51}],61:[function(require,module,exports){
7823 "use strict";
7824 Object.defineProperty(exports, "__esModule", { value: true });
7825 var Observable_1 = require("../Observable");
7826 var noop_1 = require("../util/noop");
7827 exports.NEVER = new Observable_1.Observable(noop_1.noop);
7828 function never() {
7829     return exports.NEVER;
7830 }
7831 exports.never = never;
7832
7833 },{"../Observable":31,"../util/noop":213}],62:[function(require,module,exports){
7834 "use strict";
7835 Object.defineProperty(exports, "__esModule", { value: true });
7836 var isScheduler_1 = require("../util/isScheduler");
7837 var fromArray_1 = require("./fromArray");
7838 var empty_1 = require("./empty");
7839 var scalar_1 = require("./scalar");
7840 function of() {
7841     var args = [];
7842     for (var _i = 0; _i < arguments.length; _i++) {
7843         args[_i] = arguments[_i];
7844     }
7845     var scheduler = args[args.length - 1];
7846     if (isScheduler_1.isScheduler(scheduler)) {
7847         args.pop();
7848     }
7849     else {
7850         scheduler = undefined;
7851     }
7852     switch (args.length) {
7853         case 0:
7854             return empty_1.empty(scheduler);
7855         case 1:
7856             return scheduler ? fromArray_1.fromArray(args, scheduler) : scalar_1.scalar(args[0]);
7857         default:
7858             return fromArray_1.fromArray(args, scheduler);
7859     }
7860 }
7861 exports.of = of;
7862
7863 },{"../util/isScheduler":212,"./empty":48,"./fromArray":51,"./scalar":67}],63:[function(require,module,exports){
7864 "use strict";
7865 Object.defineProperty(exports, "__esModule", { value: true });
7866 var Observable_1 = require("../Observable");
7867 var from_1 = require("./from");
7868 var isArray_1 = require("../util/isArray");
7869 var empty_1 = require("./empty");
7870 function onErrorResumeNext() {
7871     var sources = [];
7872     for (var _i = 0; _i < arguments.length; _i++) {
7873         sources[_i] = arguments[_i];
7874     }
7875     if (sources.length === 0) {
7876         return empty_1.EMPTY;
7877     }
7878     var first = sources[0], remainder = sources.slice(1);
7879     if (sources.length === 1 && isArray_1.isArray(first)) {
7880         return onErrorResumeNext.apply(void 0, first);
7881     }
7882     return new Observable_1.Observable(function (subscriber) {
7883         var subNext = function () { return subscriber.add(onErrorResumeNext.apply(void 0, remainder).subscribe(subscriber)); };
7884         return from_1.from(first).subscribe({
7885             next: function (value) { subscriber.next(value); },
7886             error: subNext,
7887             complete: subNext,
7888         });
7889     });
7890 }
7891 exports.onErrorResumeNext = onErrorResumeNext;
7892
7893 },{"../Observable":31,"../util/isArray":202,"./empty":48,"./from":50}],64:[function(require,module,exports){
7894 "use strict";
7895 Object.defineProperty(exports, "__esModule", { value: true });
7896 var Observable_1 = require("../Observable");
7897 var Subscription_1 = require("../Subscription");
7898 function pairs(obj, scheduler) {
7899     if (!scheduler) {
7900         return new Observable_1.Observable(function (subscriber) {
7901             var keys = Object.keys(obj);
7902             for (var i = 0; i < keys.length && !subscriber.closed; i++) {
7903                 var key = keys[i];
7904                 if (obj.hasOwnProperty(key)) {
7905                     subscriber.next([key, obj[key]]);
7906                 }
7907             }
7908             subscriber.complete();
7909         });
7910     }
7911     else {
7912         return new Observable_1.Observable(function (subscriber) {
7913             var keys = Object.keys(obj);
7914             var subscription = new Subscription_1.Subscription();
7915             subscription.add(scheduler.schedule(dispatch, 0, { keys: keys, index: 0, subscriber: subscriber, subscription: subscription, obj: obj }));
7916             return subscription;
7917         });
7918     }
7919 }
7920 exports.pairs = pairs;
7921 function dispatch(state) {
7922     var keys = state.keys, index = state.index, subscriber = state.subscriber, subscription = state.subscription, obj = state.obj;
7923     if (!subscriber.closed) {
7924         if (index < keys.length) {
7925             var key = keys[index];
7926             subscriber.next([key, obj[key]]);
7927             subscription.add(this.schedule({ keys: keys, index: index + 1, subscriber: subscriber, subscription: subscription, obj: obj }));
7928         }
7929         else {
7930             subscriber.complete();
7931         }
7932     }
7933 }
7934 exports.dispatch = dispatch;
7935
7936 },{"../Observable":31,"../Subscription":39}],65:[function(require,module,exports){
7937 "use strict";
7938 var __extends = (this && this.__extends) || (function () {
7939     var extendStatics = function (d, b) {
7940         extendStatics = Object.setPrototypeOf ||
7941             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7942             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7943         return extendStatics(d, b);
7944     }
7945     return function (d, b) {
7946         extendStatics(d, b);
7947         function __() { this.constructor = d; }
7948         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7949     };
7950 })();
7951 Object.defineProperty(exports, "__esModule", { value: true });
7952 var isArray_1 = require("../util/isArray");
7953 var fromArray_1 = require("./fromArray");
7954 var OuterSubscriber_1 = require("../OuterSubscriber");
7955 var subscribeToResult_1 = require("../util/subscribeToResult");
7956 function race() {
7957     var observables = [];
7958     for (var _i = 0; _i < arguments.length; _i++) {
7959         observables[_i] = arguments[_i];
7960     }
7961     if (observables.length === 1) {
7962         if (isArray_1.isArray(observables[0])) {
7963             observables = observables[0];
7964         }
7965         else {
7966             return observables[0];
7967         }
7968     }
7969     return fromArray_1.fromArray(observables, undefined).lift(new RaceOperator());
7970 }
7971 exports.race = race;
7972 var RaceOperator = (function () {
7973     function RaceOperator() {
7974     }
7975     RaceOperator.prototype.call = function (subscriber, source) {
7976         return source.subscribe(new RaceSubscriber(subscriber));
7977     };
7978     return RaceOperator;
7979 }());
7980 exports.RaceOperator = RaceOperator;
7981 var RaceSubscriber = (function (_super) {
7982     __extends(RaceSubscriber, _super);
7983     function RaceSubscriber(destination) {
7984         var _this = _super.call(this, destination) || this;
7985         _this.hasFirst = false;
7986         _this.observables = [];
7987         _this.subscriptions = [];
7988         return _this;
7989     }
7990     RaceSubscriber.prototype._next = function (observable) {
7991         this.observables.push(observable);
7992     };
7993     RaceSubscriber.prototype._complete = function () {
7994         var observables = this.observables;
7995         var len = observables.length;
7996         if (len === 0) {
7997             this.destination.complete();
7998         }
7999         else {
8000             for (var i = 0; i < len && !this.hasFirst; i++) {
8001                 var observable = observables[i];
8002                 var subscription = subscribeToResult_1.subscribeToResult(this, observable, observable, i);
8003                 if (this.subscriptions) {
8004                     this.subscriptions.push(subscription);
8005                 }
8006                 this.add(subscription);
8007             }
8008             this.observables = null;
8009         }
8010     };
8011     RaceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8012         if (!this.hasFirst) {
8013             this.hasFirst = true;
8014             for (var i = 0; i < this.subscriptions.length; i++) {
8015                 if (i !== outerIndex) {
8016                     var subscription = this.subscriptions[i];
8017                     subscription.unsubscribe();
8018                     this.remove(subscription);
8019                 }
8020             }
8021             this.subscriptions = null;
8022         }
8023         this.destination.next(innerValue);
8024     };
8025     return RaceSubscriber;
8026 }(OuterSubscriber_1.OuterSubscriber));
8027 exports.RaceSubscriber = RaceSubscriber;
8028
8029 },{"../OuterSubscriber":33,"../util/isArray":202,"../util/subscribeToResult":221,"./fromArray":51}],66:[function(require,module,exports){
8030 "use strict";
8031 Object.defineProperty(exports, "__esModule", { value: true });
8032 var Observable_1 = require("../Observable");
8033 function range(start, count, scheduler) {
8034     if (start === void 0) { start = 0; }
8035     if (count === void 0) { count = 0; }
8036     return new Observable_1.Observable(function (subscriber) {
8037         var index = 0;
8038         var current = start;
8039         if (scheduler) {
8040             return scheduler.schedule(dispatch, 0, {
8041                 index: index, count: count, start: start, subscriber: subscriber
8042             });
8043         }
8044         else {
8045             do {
8046                 if (index++ >= count) {
8047                     subscriber.complete();
8048                     break;
8049                 }
8050                 subscriber.next(current++);
8051                 if (subscriber.closed) {
8052                     break;
8053                 }
8054             } while (true);
8055         }
8056         return undefined;
8057     });
8058 }
8059 exports.range = range;
8060 function dispatch(state) {
8061     var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber;
8062     if (index >= count) {
8063         subscriber.complete();
8064         return;
8065     }
8066     subscriber.next(start);
8067     if (subscriber.closed) {
8068         return;
8069     }
8070     state.index = index + 1;
8071     state.start = start + 1;
8072     this.schedule(state);
8073 }
8074 exports.dispatch = dispatch;
8075
8076 },{"../Observable":31}],67:[function(require,module,exports){
8077 "use strict";
8078 Object.defineProperty(exports, "__esModule", { value: true });
8079 var Observable_1 = require("../Observable");
8080 function scalar(value) {
8081     var result = new Observable_1.Observable(function (subscriber) {
8082         subscriber.next(value);
8083         subscriber.complete();
8084     });
8085     result._isScalar = true;
8086     result.value = value;
8087     return result;
8088 }
8089 exports.scalar = scalar;
8090
8091 },{"../Observable":31}],68:[function(require,module,exports){
8092 "use strict";
8093 Object.defineProperty(exports, "__esModule", { value: true });
8094 var Observable_1 = require("../Observable");
8095 function throwError(error, scheduler) {
8096     if (!scheduler) {
8097         return new Observable_1.Observable(function (subscriber) { return subscriber.error(error); });
8098     }
8099     else {
8100         return new Observable_1.Observable(function (subscriber) { return scheduler.schedule(dispatch, 0, { error: error, subscriber: subscriber }); });
8101     }
8102 }
8103 exports.throwError = throwError;
8104 function dispatch(_a) {
8105     var error = _a.error, subscriber = _a.subscriber;
8106     subscriber.error(error);
8107 }
8108
8109 },{"../Observable":31}],69:[function(require,module,exports){
8110 "use strict";
8111 Object.defineProperty(exports, "__esModule", { value: true });
8112 var Observable_1 = require("../Observable");
8113 var async_1 = require("../scheduler/async");
8114 var isNumeric_1 = require("../util/isNumeric");
8115 var isScheduler_1 = require("../util/isScheduler");
8116 function timer(dueTime, periodOrScheduler, scheduler) {
8117     if (dueTime === void 0) { dueTime = 0; }
8118     var period = -1;
8119     if (isNumeric_1.isNumeric(periodOrScheduler)) {
8120         period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);
8121     }
8122     else if (isScheduler_1.isScheduler(periodOrScheduler)) {
8123         scheduler = periodOrScheduler;
8124     }
8125     if (!isScheduler_1.isScheduler(scheduler)) {
8126         scheduler = async_1.async;
8127     }
8128     return new Observable_1.Observable(function (subscriber) {
8129         var due = isNumeric_1.isNumeric(dueTime)
8130             ? dueTime
8131             : (+dueTime - scheduler.now());
8132         return scheduler.schedule(dispatch, due, {
8133             index: 0, period: period, subscriber: subscriber
8134         });
8135     });
8136 }
8137 exports.timer = timer;
8138 function dispatch(state) {
8139     var index = state.index, period = state.period, subscriber = state.subscriber;
8140     subscriber.next(index);
8141     if (subscriber.closed) {
8142         return;
8143     }
8144     else if (period === -1) {
8145         return subscriber.complete();
8146     }
8147     state.index = index + 1;
8148     this.schedule(state, period);
8149 }
8150
8151 },{"../Observable":31,"../scheduler/async":187,"../util/isNumeric":208,"../util/isScheduler":212}],70:[function(require,module,exports){
8152 "use strict";
8153 Object.defineProperty(exports, "__esModule", { value: true });
8154 var Observable_1 = require("../Observable");
8155 var from_1 = require("./from");
8156 var empty_1 = require("./empty");
8157 function using(resourceFactory, observableFactory) {
8158     return new Observable_1.Observable(function (subscriber) {
8159         var resource;
8160         try {
8161             resource = resourceFactory();
8162         }
8163         catch (err) {
8164             subscriber.error(err);
8165             return undefined;
8166         }
8167         var result;
8168         try {
8169             result = observableFactory(resource);
8170         }
8171         catch (err) {
8172             subscriber.error(err);
8173             return undefined;
8174         }
8175         var source = result ? from_1.from(result) : empty_1.EMPTY;
8176         var subscription = source.subscribe(subscriber);
8177         return function () {
8178             subscription.unsubscribe();
8179             if (resource) {
8180                 resource.unsubscribe();
8181             }
8182         };
8183     });
8184 }
8185 exports.using = using;
8186
8187 },{"../Observable":31,"./empty":48,"./from":50}],71:[function(require,module,exports){
8188 "use strict";
8189 var __extends = (this && this.__extends) || (function () {
8190     var extendStatics = function (d, b) {
8191         extendStatics = Object.setPrototypeOf ||
8192             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8193             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8194         return extendStatics(d, b);
8195     }
8196     return function (d, b) {
8197         extendStatics(d, b);
8198         function __() { this.constructor = d; }
8199         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8200     };
8201 })();
8202 Object.defineProperty(exports, "__esModule", { value: true });
8203 var fromArray_1 = require("./fromArray");
8204 var isArray_1 = require("../util/isArray");
8205 var Subscriber_1 = require("../Subscriber");
8206 var OuterSubscriber_1 = require("../OuterSubscriber");
8207 var subscribeToResult_1 = require("../util/subscribeToResult");
8208 var iterator_1 = require("../../internal/symbol/iterator");
8209 function zip() {
8210     var observables = [];
8211     for (var _i = 0; _i < arguments.length; _i++) {
8212         observables[_i] = arguments[_i];
8213     }
8214     var resultSelector = observables[observables.length - 1];
8215     if (typeof resultSelector === 'function') {
8216         observables.pop();
8217     }
8218     return fromArray_1.fromArray(observables, undefined).lift(new ZipOperator(resultSelector));
8219 }
8220 exports.zip = zip;
8221 var ZipOperator = (function () {
8222     function ZipOperator(resultSelector) {
8223         this.resultSelector = resultSelector;
8224     }
8225     ZipOperator.prototype.call = function (subscriber, source) {
8226         return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));
8227     };
8228     return ZipOperator;
8229 }());
8230 exports.ZipOperator = ZipOperator;
8231 var ZipSubscriber = (function (_super) {
8232     __extends(ZipSubscriber, _super);
8233     function ZipSubscriber(destination, resultSelector, values) {
8234         if (values === void 0) { values = Object.create(null); }
8235         var _this = _super.call(this, destination) || this;
8236         _this.iterators = [];
8237         _this.active = 0;
8238         _this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : null;
8239         _this.values = values;
8240         return _this;
8241     }
8242     ZipSubscriber.prototype._next = function (value) {
8243         var iterators = this.iterators;
8244         if (isArray_1.isArray(value)) {
8245             iterators.push(new StaticArrayIterator(value));
8246         }
8247         else if (typeof value[iterator_1.iterator] === 'function') {
8248             iterators.push(new StaticIterator(value[iterator_1.iterator]()));
8249         }
8250         else {
8251             iterators.push(new ZipBufferIterator(this.destination, this, value));
8252         }
8253     };
8254     ZipSubscriber.prototype._complete = function () {
8255         var iterators = this.iterators;
8256         var len = iterators.length;
8257         this.unsubscribe();
8258         if (len === 0) {
8259             this.destination.complete();
8260             return;
8261         }
8262         this.active = len;
8263         for (var i = 0; i < len; i++) {
8264             var iterator = iterators[i];
8265             if (iterator.stillUnsubscribed) {
8266                 var destination = this.destination;
8267                 destination.add(iterator.subscribe(iterator, i));
8268             }
8269             else {
8270                 this.active--;
8271             }
8272         }
8273     };
8274     ZipSubscriber.prototype.notifyInactive = function () {
8275         this.active--;
8276         if (this.active === 0) {
8277             this.destination.complete();
8278         }
8279     };
8280     ZipSubscriber.prototype.checkIterators = function () {
8281         var iterators = this.iterators;
8282         var len = iterators.length;
8283         var destination = this.destination;
8284         for (var i = 0; i < len; i++) {
8285             var iterator = iterators[i];
8286             if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
8287                 return;
8288             }
8289         }
8290         var shouldComplete = false;
8291         var args = [];
8292         for (var i = 0; i < len; i++) {
8293             var iterator = iterators[i];
8294             var result = iterator.next();
8295             if (iterator.hasCompleted()) {
8296                 shouldComplete = true;
8297             }
8298             if (result.done) {
8299                 destination.complete();
8300                 return;
8301             }
8302             args.push(result.value);
8303         }
8304         if (this.resultSelector) {
8305             this._tryresultSelector(args);
8306         }
8307         else {
8308             destination.next(args);
8309         }
8310         if (shouldComplete) {
8311             destination.complete();
8312         }
8313     };
8314     ZipSubscriber.prototype._tryresultSelector = function (args) {
8315         var result;
8316         try {
8317             result = this.resultSelector.apply(this, args);
8318         }
8319         catch (err) {
8320             this.destination.error(err);
8321             return;
8322         }
8323         this.destination.next(result);
8324     };
8325     return ZipSubscriber;
8326 }(Subscriber_1.Subscriber));
8327 exports.ZipSubscriber = ZipSubscriber;
8328 var StaticIterator = (function () {
8329     function StaticIterator(iterator) {
8330         this.iterator = iterator;
8331         this.nextResult = iterator.next();
8332     }
8333     StaticIterator.prototype.hasValue = function () {
8334         return true;
8335     };
8336     StaticIterator.prototype.next = function () {
8337         var result = this.nextResult;
8338         this.nextResult = this.iterator.next();
8339         return result;
8340     };
8341     StaticIterator.prototype.hasCompleted = function () {
8342         var nextResult = this.nextResult;
8343         return nextResult && nextResult.done;
8344     };
8345     return StaticIterator;
8346 }());
8347 var StaticArrayIterator = (function () {
8348     function StaticArrayIterator(array) {
8349         this.array = array;
8350         this.index = 0;
8351         this.length = 0;
8352         this.length = array.length;
8353     }
8354     StaticArrayIterator.prototype[iterator_1.iterator] = function () {
8355         return this;
8356     };
8357     StaticArrayIterator.prototype.next = function (value) {
8358         var i = this.index++;
8359         var array = this.array;
8360         return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
8361     };
8362     StaticArrayIterator.prototype.hasValue = function () {
8363         return this.array.length > this.index;
8364     };
8365     StaticArrayIterator.prototype.hasCompleted = function () {
8366         return this.array.length === this.index;
8367     };
8368     return StaticArrayIterator;
8369 }());
8370 var ZipBufferIterator = (function (_super) {
8371     __extends(ZipBufferIterator, _super);
8372     function ZipBufferIterator(destination, parent, observable) {
8373         var _this = _super.call(this, destination) || this;
8374         _this.parent = parent;
8375         _this.observable = observable;
8376         _this.stillUnsubscribed = true;
8377         _this.buffer = [];
8378         _this.isComplete = false;
8379         return _this;
8380     }
8381     ZipBufferIterator.prototype[iterator_1.iterator] = function () {
8382         return this;
8383     };
8384     ZipBufferIterator.prototype.next = function () {
8385         var buffer = this.buffer;
8386         if (buffer.length === 0 && this.isComplete) {
8387             return { value: null, done: true };
8388         }
8389         else {
8390             return { value: buffer.shift(), done: false };
8391         }
8392     };
8393     ZipBufferIterator.prototype.hasValue = function () {
8394         return this.buffer.length > 0;
8395     };
8396     ZipBufferIterator.prototype.hasCompleted = function () {
8397         return this.buffer.length === 0 && this.isComplete;
8398     };
8399     ZipBufferIterator.prototype.notifyComplete = function () {
8400         if (this.buffer.length > 0) {
8401             this.isComplete = true;
8402             this.parent.notifyInactive();
8403         }
8404         else {
8405             this.destination.complete();
8406         }
8407     };
8408     ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8409         this.buffer.push(innerValue);
8410         this.parent.checkIterators();
8411     };
8412     ZipBufferIterator.prototype.subscribe = function (value, index) {
8413         return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
8414     };
8415     return ZipBufferIterator;
8416 }(OuterSubscriber_1.OuterSubscriber));
8417
8418 },{"../../internal/symbol/iterator":189,"../OuterSubscriber":33,"../Subscriber":38,"../util/isArray":202,"../util/subscribeToResult":221,"./fromArray":51}],72:[function(require,module,exports){
8419 "use strict";
8420 var __extends = (this && this.__extends) || (function () {
8421     var extendStatics = function (d, b) {
8422         extendStatics = Object.setPrototypeOf ||
8423             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8424             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8425         return extendStatics(d, b);
8426     }
8427     return function (d, b) {
8428         extendStatics(d, b);
8429         function __() { this.constructor = d; }
8430         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8431     };
8432 })();
8433 Object.defineProperty(exports, "__esModule", { value: true });
8434 var tryCatch_1 = require("../util/tryCatch");
8435 var errorObject_1 = require("../util/errorObject");
8436 var OuterSubscriber_1 = require("../OuterSubscriber");
8437 var subscribeToResult_1 = require("../util/subscribeToResult");
8438 function audit(durationSelector) {
8439     return function auditOperatorFunction(source) {
8440         return source.lift(new AuditOperator(durationSelector));
8441     };
8442 }
8443 exports.audit = audit;
8444 var AuditOperator = (function () {
8445     function AuditOperator(durationSelector) {
8446         this.durationSelector = durationSelector;
8447     }
8448     AuditOperator.prototype.call = function (subscriber, source) {
8449         return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));
8450     };
8451     return AuditOperator;
8452 }());
8453 var AuditSubscriber = (function (_super) {
8454     __extends(AuditSubscriber, _super);
8455     function AuditSubscriber(destination, durationSelector) {
8456         var _this = _super.call(this, destination) || this;
8457         _this.durationSelector = durationSelector;
8458         _this.hasValue = false;
8459         return _this;
8460     }
8461     AuditSubscriber.prototype._next = function (value) {
8462         this.value = value;
8463         this.hasValue = true;
8464         if (!this.throttled) {
8465             var duration = tryCatch_1.tryCatch(this.durationSelector)(value);
8466             if (duration === errorObject_1.errorObject) {
8467                 this.destination.error(errorObject_1.errorObject.e);
8468             }
8469             else {
8470                 var innerSubscription = subscribeToResult_1.subscribeToResult(this, duration);
8471                 if (!innerSubscription || innerSubscription.closed) {
8472                     this.clearThrottle();
8473                 }
8474                 else {
8475                     this.add(this.throttled = innerSubscription);
8476                 }
8477             }
8478         }
8479     };
8480     AuditSubscriber.prototype.clearThrottle = function () {
8481         var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled;
8482         if (throttled) {
8483             this.remove(throttled);
8484             this.throttled = null;
8485             throttled.unsubscribe();
8486         }
8487         if (hasValue) {
8488             this.value = null;
8489             this.hasValue = false;
8490             this.destination.next(value);
8491         }
8492     };
8493     AuditSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
8494         this.clearThrottle();
8495     };
8496     AuditSubscriber.prototype.notifyComplete = function () {
8497         this.clearThrottle();
8498     };
8499     return AuditSubscriber;
8500 }(OuterSubscriber_1.OuterSubscriber));
8501
8502 },{"../OuterSubscriber":33,"../util/errorObject":199,"../util/subscribeToResult":221,"../util/tryCatch":223}],73:[function(require,module,exports){
8503 "use strict";
8504 Object.defineProperty(exports, "__esModule", { value: true });
8505 var async_1 = require("../scheduler/async");
8506 var audit_1 = require("./audit");
8507 var timer_1 = require("../observable/timer");
8508 function auditTime(duration, scheduler) {
8509     if (scheduler === void 0) { scheduler = async_1.async; }
8510     return audit_1.audit(function () { return timer_1.timer(duration, scheduler); });
8511 }
8512 exports.auditTime = auditTime;
8513
8514 },{"../observable/timer":69,"../scheduler/async":187,"./audit":72}],74:[function(require,module,exports){
8515 "use strict";
8516 var __extends = (this && this.__extends) || (function () {
8517     var extendStatics = function (d, b) {
8518         extendStatics = Object.setPrototypeOf ||
8519             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8520             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8521         return extendStatics(d, b);
8522     }
8523     return function (d, b) {
8524         extendStatics(d, b);
8525         function __() { this.constructor = d; }
8526         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8527     };
8528 })();
8529 Object.defineProperty(exports, "__esModule", { value: true });
8530 var OuterSubscriber_1 = require("../OuterSubscriber");
8531 var subscribeToResult_1 = require("../util/subscribeToResult");
8532 function buffer(closingNotifier) {
8533     return function bufferOperatorFunction(source) {
8534         return source.lift(new BufferOperator(closingNotifier));
8535     };
8536 }
8537 exports.buffer = buffer;
8538 var BufferOperator = (function () {
8539     function BufferOperator(closingNotifier) {
8540         this.closingNotifier = closingNotifier;
8541     }
8542     BufferOperator.prototype.call = function (subscriber, source) {
8543         return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
8544     };
8545     return BufferOperator;
8546 }());
8547 var BufferSubscriber = (function (_super) {
8548     __extends(BufferSubscriber, _super);
8549     function BufferSubscriber(destination, closingNotifier) {
8550         var _this = _super.call(this, destination) || this;
8551         _this.buffer = [];
8552         _this.add(subscribeToResult_1.subscribeToResult(_this, closingNotifier));
8553         return _this;
8554     }
8555     BufferSubscriber.prototype._next = function (value) {
8556         this.buffer.push(value);
8557     };
8558     BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8559         var buffer = this.buffer;
8560         this.buffer = [];
8561         this.destination.next(buffer);
8562     };
8563     return BufferSubscriber;
8564 }(OuterSubscriber_1.OuterSubscriber));
8565
8566 },{"../OuterSubscriber":33,"../util/subscribeToResult":221}],75:[function(require,module,exports){
8567 "use strict";
8568 var __extends = (this && this.__extends) || (function () {
8569     var extendStatics = function (d, b) {
8570         extendStatics = Object.setPrototypeOf ||
8571             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8572             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8573         return extendStatics(d, b);
8574     }
8575     return function (d, b) {
8576         extendStatics(d, b);
8577         function __() { this.constructor = d; }
8578         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8579     };
8580 })();
8581 Object.defineProperty(exports, "__esModule", { value: true });
8582 var Subscriber_1 = require("../Subscriber");
8583 function bufferCount(bufferSize, startBufferEvery) {
8584     if (startBufferEvery === void 0) { startBufferEvery = null; }
8585     return function bufferCountOperatorFunction(source) {
8586         return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));
8587     };
8588 }
8589 exports.bufferCount = bufferCount;
8590 var BufferCountOperator = (function () {
8591     function BufferCountOperator(bufferSize, startBufferEvery) {
8592         this.bufferSize = bufferSize;
8593         this.startBufferEvery = startBufferEvery;
8594         if (!startBufferEvery || bufferSize === startBufferEvery) {
8595             this.subscriberClass = BufferCountSubscriber;
8596         }
8597         else {
8598             this.subscriberClass = BufferSkipCountSubscriber;
8599         }
8600     }
8601     BufferCountOperator.prototype.call = function (subscriber, source) {
8602         return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
8603     };
8604     return BufferCountOperator;
8605 }());
8606 var BufferCountSubscriber = (function (_super) {
8607     __extends(BufferCountSubscriber, _super);
8608     function BufferCountSubscriber(destination, bufferSize) {
8609         var _this = _super.call(this, destination) || this;
8610         _this.bufferSize = bufferSize;
8611         _this.buffer = [];
8612         return _this;
8613     }
8614     BufferCountSubscriber.prototype._next = function (value) {
8615         var buffer = this.buffer;
8616         buffer.push(value);
8617         if (buffer.length == this.bufferSize) {
8618             this.destination.next(buffer);
8619             this.buffer = [];
8620         }
8621     };
8622     BufferCountSubscriber.prototype._complete = function () {
8623         var buffer = this.buffer;
8624         if (buffer.length > 0) {
8625             this.destination.next(buffer);
8626         }
8627         _super.prototype._complete.call(this);
8628     };
8629     return BufferCountSubscriber;
8630 }(Subscriber_1.Subscriber));
8631 var BufferSkipCountSubscriber = (function (_super) {
8632     __extends(BufferSkipCountSubscriber, _super);
8633     function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
8634         var _this = _super.call(this, destination) || this;
8635         _this.bufferSize = bufferSize;
8636         _this.startBufferEvery = startBufferEvery;
8637         _this.buffers = [];
8638         _this.count = 0;
8639         return _this;
8640     }
8641     BufferSkipCountSubscriber.prototype._next = function (value) {
8642         var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
8643         this.count++;
8644         if (count % startBufferEvery === 0) {
8645             buffers.push([]);
8646         }
8647         for (var i = buffers.length; i--;) {
8648             var buffer = buffers[i];
8649             buffer.push(value);
8650             if (buffer.length === bufferSize) {
8651                 buffers.splice(i, 1);
8652                 this.destination.next(buffer);
8653             }
8654         }
8655     };
8656     BufferSkipCountSubscriber.prototype._complete = function () {
8657         var _a = this, buffers = _a.buffers, destination = _a.destination;
8658         while (buffers.length > 0) {
8659             var buffer = buffers.shift();
8660             if (buffer.length > 0) {
8661                 destination.next(buffer);
8662             }
8663         }
8664         _super.prototype._complete.call(this);
8665     };
8666     return BufferSkipCountSubscriber;
8667 }(Subscriber_1.Subscriber));
8668
8669 },{"../Subscriber":38}],76:[function(require,module,exports){
8670 "use strict";
8671 var __extends = (this && this.__extends) || (function () {
8672     var extendStatics = function (d, b) {
8673         extendStatics = Object.setPrototypeOf ||
8674             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8675             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8676         return extendStatics(d, b);
8677     }
8678     return function (d, b) {
8679         extendStatics(d, b);
8680         function __() { this.constructor = d; }
8681         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8682     };
8683 })();
8684 Object.defineProperty(exports, "__esModule", { value: true });
8685 var async_1 = require("../scheduler/async");
8686 var Subscriber_1 = require("../Subscriber");
8687 var isScheduler_1 = require("../util/isScheduler");
8688 function bufferTime(bufferTimeSpan) {
8689     var length = arguments.length;
8690     var scheduler = async_1.async;
8691     if (isScheduler_1.isScheduler(arguments[arguments.length - 1])) {
8692         scheduler = arguments[arguments.length - 1];
8693         length--;
8694     }
8695     var bufferCreationInterval = null;
8696     if (length >= 2) {
8697         bufferCreationInterval = arguments[1];
8698     }
8699     var maxBufferSize = Number.POSITIVE_INFINITY;
8700     if (length >= 3) {
8701         maxBufferSize = arguments[2];
8702     }
8703     return function bufferTimeOperatorFunction(source) {
8704         return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));
8705     };
8706 }
8707 exports.bufferTime = bufferTime;
8708 var BufferTimeOperator = (function () {
8709     function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
8710         this.bufferTimeSpan = bufferTimeSpan;
8711         this.bufferCreationInterval = bufferCreationInterval;
8712         this.maxBufferSize = maxBufferSize;
8713         this.scheduler = scheduler;
8714     }
8715     BufferTimeOperator.prototype.call = function (subscriber, source) {
8716         return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler));
8717     };
8718     return BufferTimeOperator;
8719 }());
8720 var Context = (function () {
8721     function Context() {
8722         this.buffer = [];
8723     }
8724     return Context;
8725 }());
8726 var BufferTimeSubscriber = (function (_super) {
8727     __extends(BufferTimeSubscriber, _super);
8728     function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
8729         var _this = _super.call(this, destination) || this;
8730         _this.bufferTimeSpan = bufferTimeSpan;
8731         _this.bufferCreationInterval = bufferCreationInterval;
8732         _this.maxBufferSize = maxBufferSize;
8733         _this.scheduler = scheduler;
8734         _this.contexts = [];
8735         var context = _this.openContext();
8736         _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;
8737         if (_this.timespanOnly) {
8738             var timeSpanOnlyState = { subscriber: _this, context: context, bufferTimeSpan: bufferTimeSpan };
8739             _this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
8740         }
8741         else {
8742             var closeState = { subscriber: _this, context: context };
8743             var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: _this, scheduler: scheduler };
8744             _this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState));
8745             _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState));
8746         }
8747         return _this;
8748     }
8749     BufferTimeSubscriber.prototype._next = function (value) {
8750         var contexts = this.contexts;
8751         var len = contexts.length;
8752         var filledBufferContext;
8753         for (var i = 0; i < len; i++) {
8754             var context_1 = contexts[i];
8755             var buffer = context_1.buffer;
8756             buffer.push(value);
8757             if (buffer.length == this.maxBufferSize) {
8758                 filledBufferContext = context_1;
8759             }
8760         }
8761         if (filledBufferContext) {
8762             this.onBufferFull(filledBufferContext);
8763         }
8764     };
8765     BufferTimeSubscriber.prototype._error = function (err) {
8766         this.contexts.length = 0;
8767         _super.prototype._error.call(this, err);
8768     };
8769     BufferTimeSubscriber.prototype._complete = function () {
8770         var _a = this, contexts = _a.contexts, destination = _a.destination;
8771         while (contexts.length > 0) {
8772             var context_2 = contexts.shift();
8773             destination.next(context_2.buffer);
8774         }
8775         _super.prototype._complete.call(this);
8776     };
8777     BufferTimeSubscriber.prototype._unsubscribe = function () {
8778         this.contexts = null;
8779     };
8780     BufferTimeSubscriber.prototype.onBufferFull = function (context) {
8781         this.closeContext(context);
8782         var closeAction = context.closeAction;
8783         closeAction.unsubscribe();
8784         this.remove(closeAction);
8785         if (!this.closed && this.timespanOnly) {
8786             context = this.openContext();
8787             var bufferTimeSpan = this.bufferTimeSpan;
8788             var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan };
8789             this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
8790         }
8791     };
8792     BufferTimeSubscriber.prototype.openContext = function () {
8793         var context = new Context();
8794         this.contexts.push(context);
8795         return context;
8796     };
8797     BufferTimeSubscriber.prototype.closeContext = function (context) {
8798         this.destination.next(context.buffer);
8799         var contexts = this.contexts;
8800         var spliceIndex = contexts ? contexts.indexOf(context) : -1;
8801         if (spliceIndex >= 0) {
8802             contexts.splice(contexts.indexOf(context), 1);
8803         }
8804     };
8805     return BufferTimeSubscriber;
8806 }(Subscriber_1.Subscriber));
8807 function dispatchBufferTimeSpanOnly(state) {
8808     var subscriber = state.subscriber;
8809     var prevContext = state.context;
8810     if (prevContext) {
8811         subscriber.closeContext(prevContext);
8812     }
8813     if (!subscriber.closed) {
8814         state.context = subscriber.openContext();
8815         state.context.closeAction = this.schedule(state, state.bufferTimeSpan);
8816     }
8817 }
8818 function dispatchBufferCreation(state) {
8819     var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler;
8820     var context = subscriber.openContext();
8821     var action = this;
8822     if (!subscriber.closed) {
8823         subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context }));
8824         action.schedule(state, bufferCreationInterval);
8825     }
8826 }
8827 function dispatchBufferClose(arg) {
8828     var subscriber = arg.subscriber, context = arg.context;
8829     subscriber.closeContext(context);
8830 }
8831
8832 },{"../Subscriber":38,"../scheduler/async":187,"../util/isScheduler":212}],77:[function(require,module,exports){
8833 "use strict";
8834 var __extends = (this && this.__extends) || (function () {
8835     var extendStatics = function (d, b) {
8836         extendStatics = Object.setPrototypeOf ||
8837             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8838             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8839         return extendStatics(d, b);
8840     }
8841     return function (d, b) {
8842         extendStatics(d, b);
8843         function __() { this.constructor = d; }
8844         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8845     };
8846 })();
8847 Object.defineProperty(exports, "__esModule", { value: true });
8848 var Subscription_1 = require("../Subscription");
8849 var subscribeToResult_1 = require("../util/subscribeToResult");
8850 var OuterSubscriber_1 = require("../OuterSubscriber");
8851 function bufferToggle(openings, closingSelector) {
8852     return function bufferToggleOperatorFunction(source) {
8853         return source.lift(new BufferToggleOperator(openings, closingSelector));
8854     };
8855 }
8856 exports.bufferToggle = bufferToggle;
8857 var BufferToggleOperator = (function () {
8858     function BufferToggleOperator(openings, closingSelector) {
8859         this.openings = openings;
8860         this.closingSelector = closingSelector;
8861     }
8862     BufferToggleOperator.prototype.call = function (subscriber, source) {
8863         return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector));
8864     };
8865     return BufferToggleOperator;
8866 }());
8867 var BufferToggleSubscriber = (function (_super) {
8868     __extends(BufferToggleSubscriber, _super);
8869     function BufferToggleSubscriber(destination, openings, closingSelector) {
8870         var _this = _super.call(this, destination) || this;
8871         _this.openings = openings;
8872         _this.closingSelector = closingSelector;
8873         _this.contexts = [];
8874         _this.add(subscribeToResult_1.subscribeToResult(_this, openings));
8875         return _this;
8876     }
8877     BufferToggleSubscriber.prototype._next = function (value) {
8878         var contexts = this.contexts;
8879         var len = contexts.length;
8880         for (var i = 0; i < len; i++) {
8881             contexts[i].buffer.push(value);
8882         }
8883     };
8884     BufferToggleSubscriber.prototype._error = function (err) {
8885         var contexts = this.contexts;
8886         while (contexts.length > 0) {
8887             var context_1 = contexts.shift();
8888             context_1.subscription.unsubscribe();
8889             context_1.buffer = null;
8890             context_1.subscription = null;
8891         }
8892         this.contexts = null;
8893         _super.prototype._error.call(this, err);
8894     };
8895     BufferToggleSubscriber.prototype._complete = function () {
8896         var contexts = this.contexts;
8897         while (contexts.length > 0) {
8898             var context_2 = contexts.shift();
8899             this.destination.next(context_2.buffer);
8900             context_2.subscription.unsubscribe();
8901             context_2.buffer = null;
8902             context_2.subscription = null;
8903         }
8904         this.contexts = null;
8905         _super.prototype._complete.call(this);
8906     };
8907     BufferToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8908         outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue);
8909     };
8910     BufferToggleSubscriber.prototype.notifyComplete = function (innerSub) {
8911         this.closeBuffer(innerSub.context);
8912     };
8913     BufferToggleSubscriber.prototype.openBuffer = function (value) {
8914         try {
8915             var closingSelector = this.closingSelector;
8916             var closingNotifier = closingSelector.call(this, value);
8917             if (closingNotifier) {
8918                 this.trySubscribe(closingNotifier);
8919             }
8920         }
8921         catch (err) {
8922             this._error(err);
8923         }
8924     };
8925     BufferToggleSubscriber.prototype.closeBuffer = function (context) {
8926         var contexts = this.contexts;
8927         if (contexts && context) {
8928             var buffer = context.buffer, subscription = context.subscription;
8929             this.destination.next(buffer);
8930             contexts.splice(contexts.indexOf(context), 1);
8931             this.remove(subscription);
8932             subscription.unsubscribe();
8933         }
8934     };
8935     BufferToggleSubscriber.prototype.trySubscribe = function (closingNotifier) {
8936         var contexts = this.contexts;
8937         var buffer = [];
8938         var subscription = new Subscription_1.Subscription();
8939         var context = { buffer: buffer, subscription: subscription };
8940         contexts.push(context);
8941         var innerSubscription = subscribeToResult_1.subscribeToResult(this, closingNotifier, context);
8942         if (!innerSubscription || innerSubscription.closed) {
8943             this.closeBuffer(context);
8944         }
8945         else {
8946             innerSubscription.context = context;
8947             this.add(innerSubscription);
8948             subscription.add(innerSubscription);
8949         }
8950     };
8951     return BufferToggleSubscriber;
8952 }(OuterSubscriber_1.OuterSubscriber));
8953
8954 },{"../OuterSubscriber":33,"../Subscription":39,"../util/subscribeToResult":221}],78:[function(require,module,exports){
8955 "use strict";
8956 var __extends = (this && this.__extends) || (function () {
8957     var extendStatics = function (d, b) {
8958         extendStatics = Object.setPrototypeOf ||
8959             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
8960             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
8961         return extendStatics(d, b);
8962     }
8963     return function (d, b) {
8964         extendStatics(d, b);
8965         function __() { this.constructor = d; }
8966         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8967     };
8968 })();
8969 Object.defineProperty(exports, "__esModule", { value: true });
8970 var Subscription_1 = require("../Subscription");
8971 var tryCatch_1 = require("../util/tryCatch");
8972 var errorObject_1 = require("../util/errorObject");
8973 var OuterSubscriber_1 = require("../OuterSubscriber");
8974 var subscribeToResult_1 = require("../util/subscribeToResult");
8975 function bufferWhen(closingSelector) {
8976     return function (source) {
8977         return source.lift(new BufferWhenOperator(closingSelector));
8978     };
8979 }
8980 exports.bufferWhen = bufferWhen;
8981 var BufferWhenOperator = (function () {
8982     function BufferWhenOperator(closingSelector) {
8983         this.closingSelector = closingSelector;
8984     }
8985     BufferWhenOperator.prototype.call = function (subscriber, source) {
8986         return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
8987     };
8988     return BufferWhenOperator;
8989 }());
8990 var BufferWhenSubscriber = (function (_super) {
8991     __extends(BufferWhenSubscriber, _super);
8992     function BufferWhenSubscriber(destination, closingSelector) {
8993         var _this = _super.call(this, destination) || this;
8994         _this.closingSelector = closingSelector;
8995         _this.subscribing = false;
8996         _this.openBuffer();
8997         return _this;
8998     }
8999     BufferWhenSubscriber.prototype._next = function (value) {
9000         this.buffer.push(value);
9001     };
9002     BufferWhenSubscriber.prototype._complete = function () {
9003         var buffer = this.buffer;
9004         if (buffer) {
9005             this.destination.next(buffer);
9006         }
9007         _super.prototype._complete.call(this);
9008     };
9009     BufferWhenSubscriber.prototype._unsubscribe = function () {
9010         this.buffer = null;
9011         this.subscribing = false;
9012     };
9013     BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9014         this.openBuffer();
9015     };
9016     BufferWhenSubscriber.prototype.notifyComplete = function () {
9017         if (this.subscribing) {
9018             this.complete();
9019         }
9020         else {
9021             this.openBuffer();
9022         }
9023     };
9024     BufferWhenSubscriber.prototype.openBuffer = function () {
9025         var closingSubscription = this.closingSubscription;
9026         if (closingSubscription) {
9027             this.remove(closingSubscription);
9028             closingSubscription.unsubscribe();
9029         }
9030         var buffer = this.buffer;
9031         if (this.buffer) {
9032             this.destination.next(buffer);
9033         }
9034         this.buffer = [];
9035         var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
9036         if (closingNotifier === errorObject_1.errorObject) {
9037             this.error(errorObject_1.errorObject.e);
9038         }
9039         else {
9040             closingSubscription = new Subscription_1.Subscription();
9041             this.closingSubscription = closingSubscription;
9042             this.add(closingSubscription);
9043             this.subscribing = true;
9044             closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
9045             this.subscribing = false;
9046         }
9047     };
9048     return BufferWhenSubscriber;
9049 }(OuterSubscriber_1.OuterSubscriber));
9050
9051 },{"../OuterSubscriber":33,"../Subscription":39,"../util/errorObject":199,"../util/subscribeToResult":221,"../util/tryCatch":223}],79:[function(require,module,exports){
9052 "use strict";
9053 var __extends = (this && this.__extends) || (function () {
9054     var extendStatics = function (d, b) {
9055         extendStatics = Object.setPrototypeOf ||
9056             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9057             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9058         return extendStatics(d, b);
9059     }
9060     return function (d, b) {
9061         extendStatics(d, b);
9062         function __() { this.constructor = d; }
9063         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9064     };
9065 })();
9066 Object.defineProperty(exports, "__esModule", { value: true });
9067 var OuterSubscriber_1 = require("../OuterSubscriber");
9068 var InnerSubscriber_1 = require("../InnerSubscriber");
9069 var subscribeToResult_1 = require("../util/subscribeToResult");
9070 function catchError(selector) {
9071     return function catchErrorOperatorFunction(source) {
9072         var operator = new CatchOperator(selector);
9073         var caught = source.lift(operator);
9074         return (operator.caught = caught);
9075     };
9076 }
9077 exports.catchError = catchError;
9078 var CatchOperator = (function () {
9079     function CatchOperator(selector) {
9080         this.selector = selector;
9081     }
9082     CatchOperator.prototype.call = function (subscriber, source) {
9083         return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
9084     };
9085     return CatchOperator;
9086 }());
9087 var CatchSubscriber = (function (_super) {
9088     __extends(CatchSubscriber, _super);
9089     function CatchSubscriber(destination, selector, caught) {
9090         var _this = _super.call(this, destination) || this;
9091         _this.selector = selector;
9092         _this.caught = caught;
9093         return _this;
9094     }
9095     CatchSubscriber.prototype.error = function (err) {
9096         if (!this.isStopped) {
9097             var result = void 0;
9098             try {
9099                 result = this.selector(err, this.caught);
9100             }
9101             catch (err2) {
9102                 _super.prototype.error.call(this, err2);
9103                 return;
9104             }
9105             this._unsubscribeAndRecycle();
9106             var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
9107             this.add(innerSubscriber);
9108             subscribeToResult_1.subscribeToResult(this, result, undefined, undefined, innerSubscriber);
9109         }
9110     };
9111     return CatchSubscriber;
9112 }(OuterSubscriber_1.OuterSubscriber));
9113
9114 },{"../InnerSubscriber":29,"../OuterSubscriber":33,"../util/subscribeToResult":221}],80:[function(require,module,exports){
9115 "use strict";
9116 Object.defineProperty(exports, "__esModule", { value: true });
9117 var combineLatest_1 = require("../observable/combineLatest");
9118 function combineAll(project) {
9119     return function (source) { return source.lift(new combineLatest_1.CombineLatestOperator(project)); };
9120 }
9121 exports.combineAll = combineAll;
9122
9123 },{"../observable/combineLatest":45}],81:[function(require,module,exports){
9124 "use strict";
9125 Object.defineProperty(exports, "__esModule", { value: true });
9126 var isArray_1 = require("../util/isArray");
9127 var combineLatest_1 = require("../observable/combineLatest");
9128 var from_1 = require("../observable/from");
9129 var none = {};
9130 function combineLatest() {
9131     var observables = [];
9132     for (var _i = 0; _i < arguments.length; _i++) {
9133         observables[_i] = arguments[_i];
9134     }
9135     var project = null;
9136     if (typeof observables[observables.length - 1] === 'function') {
9137         project = observables.pop();
9138     }
9139     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
9140         observables = observables[0].slice();
9141     }
9142     return function (source) { return source.lift.call(from_1.from([source].concat(observables)), new combineLatest_1.CombineLatestOperator(project)); };
9143 }
9144 exports.combineLatest = combineLatest;
9145
9146 },{"../observable/combineLatest":45,"../observable/from":50,"../util/isArray":202}],82:[function(require,module,exports){
9147 "use strict";
9148 Object.defineProperty(exports, "__esModule", { value: true });
9149 var concat_1 = require("../observable/concat");
9150 function concat() {
9151     var observables = [];
9152     for (var _i = 0; _i < arguments.length; _i++) {
9153         observables[_i] = arguments[_i];
9154     }
9155     return function (source) { return source.lift.call(concat_1.concat.apply(void 0, [source].concat(observables))); };
9156 }
9157 exports.concat = concat;
9158
9159 },{"../observable/concat":46}],83:[function(require,module,exports){
9160 "use strict";
9161 Object.defineProperty(exports, "__esModule", { value: true });
9162 var mergeAll_1 = require("./mergeAll");
9163 function concatAll() {
9164     return mergeAll_1.mergeAll(1);
9165 }
9166 exports.concatAll = concatAll;
9167
9168 },{"./mergeAll":116}],84:[function(require,module,exports){
9169 "use strict";
9170 Object.defineProperty(exports, "__esModule", { value: true });
9171 var mergeMap_1 = require("./mergeMap");
9172 function concatMap(project, resultSelector) {
9173     return mergeMap_1.mergeMap(project, resultSelector, 1);
9174 }
9175 exports.concatMap = concatMap;
9176
9177 },{"./mergeMap":117}],85:[function(require,module,exports){
9178 "use strict";
9179 Object.defineProperty(exports, "__esModule", { value: true });
9180 var concatMap_1 = require("./concatMap");
9181 function concatMapTo(innerObservable, resultSelector) {
9182     return concatMap_1.concatMap(function () { return innerObservable; }, resultSelector);
9183 }
9184 exports.concatMapTo = concatMapTo;
9185
9186 },{"./concatMap":84}],86:[function(require,module,exports){
9187 "use strict";
9188 var __extends = (this && this.__extends) || (function () {
9189     var extendStatics = function (d, b) {
9190         extendStatics = Object.setPrototypeOf ||
9191             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9192             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9193         return extendStatics(d, b);
9194     }
9195     return function (d, b) {
9196         extendStatics(d, b);
9197         function __() { this.constructor = d; }
9198         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9199     };
9200 })();
9201 Object.defineProperty(exports, "__esModule", { value: true });
9202 var Subscriber_1 = require("../Subscriber");
9203 function count(predicate) {
9204     return function (source) { return source.lift(new CountOperator(predicate, source)); };
9205 }
9206 exports.count = count;
9207 var CountOperator = (function () {
9208     function CountOperator(predicate, source) {
9209         this.predicate = predicate;
9210         this.source = source;
9211     }
9212     CountOperator.prototype.call = function (subscriber, source) {
9213         return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source));
9214     };
9215     return CountOperator;
9216 }());
9217 var CountSubscriber = (function (_super) {
9218     __extends(CountSubscriber, _super);
9219     function CountSubscriber(destination, predicate, source) {
9220         var _this = _super.call(this, destination) || this;
9221         _this.predicate = predicate;
9222         _this.source = source;
9223         _this.count = 0;
9224         _this.index = 0;
9225         return _this;
9226     }
9227     CountSubscriber.prototype._next = function (value) {
9228         if (this.predicate) {
9229             this._tryPredicate(value);
9230         }
9231         else {
9232             this.count++;
9233         }
9234     };
9235     CountSubscriber.prototype._tryPredicate = function (value) {
9236         var result;
9237         try {
9238             result = this.predicate(value, this.index++, this.source);
9239         }
9240         catch (err) {
9241             this.destination.error(err);
9242             return;
9243         }
9244         if (result) {
9245             this.count++;
9246         }
9247     };
9248     CountSubscriber.prototype._complete = function () {
9249         this.destination.next(this.count);
9250         this.destination.complete();
9251     };
9252     return CountSubscriber;
9253 }(Subscriber_1.Subscriber));
9254
9255 },{"../Subscriber":38}],87:[function(require,module,exports){
9256 "use strict";
9257 var __extends = (this && this.__extends) || (function () {
9258     var extendStatics = function (d, b) {
9259         extendStatics = Object.setPrototypeOf ||
9260             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9261             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9262         return extendStatics(d, b);
9263     }
9264     return function (d, b) {
9265         extendStatics(d, b);
9266         function __() { this.constructor = d; }
9267         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9268     };
9269 })();
9270 Object.defineProperty(exports, "__esModule", { value: true });
9271 var OuterSubscriber_1 = require("../OuterSubscriber");
9272 var subscribeToResult_1 = require("../util/subscribeToResult");
9273 function debounce(durationSelector) {
9274     return function (source) { return source.lift(new DebounceOperator(durationSelector)); };
9275 }
9276 exports.debounce = debounce;
9277 var DebounceOperator = (function () {
9278     function DebounceOperator(durationSelector) {
9279         this.durationSelector = durationSelector;
9280     }
9281     DebounceOperator.prototype.call = function (subscriber, source) {
9282         return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector));
9283     };
9284     return DebounceOperator;
9285 }());
9286 var DebounceSubscriber = (function (_super) {
9287     __extends(DebounceSubscriber, _super);
9288     function DebounceSubscriber(destination, durationSelector) {
9289         var _this = _super.call(this, destination) || this;
9290         _this.durationSelector = durationSelector;
9291         _this.hasValue = false;
9292         _this.durationSubscription = null;
9293         return _this;
9294     }
9295     DebounceSubscriber.prototype._next = function (value) {
9296         try {
9297             var result = this.durationSelector.call(this, value);
9298             if (result) {
9299                 this._tryNext(value, result);
9300             }
9301         }
9302         catch (err) {
9303             this.destination.error(err);
9304         }
9305     };
9306     DebounceSubscriber.prototype._complete = function () {
9307         this.emitValue();
9308         this.destination.complete();
9309     };
9310     DebounceSubscriber.prototype._tryNext = function (value, duration) {
9311         var subscription = this.durationSubscription;
9312         this.value = value;
9313         this.hasValue = true;
9314         if (subscription) {
9315             subscription.unsubscribe();
9316             this.remove(subscription);
9317         }
9318         subscription = subscribeToResult_1.subscribeToResult(this, duration);
9319         if (subscription && !subscription.closed) {
9320             this.add(this.durationSubscription = subscription);
9321         }
9322     };
9323     DebounceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9324         this.emitValue();
9325     };
9326     DebounceSubscriber.prototype.notifyComplete = function () {
9327         this.emitValue();
9328     };
9329     DebounceSubscriber.prototype.emitValue = function () {
9330         if (this.hasValue) {
9331             var value = this.value;
9332             var subscription = this.durationSubscription;
9333             if (subscription) {
9334                 this.durationSubscription = null;
9335                 subscription.unsubscribe();
9336                 this.remove(subscription);
9337             }
9338             this.value = null;
9339             this.hasValue = false;
9340             _super.prototype._next.call(this, value);
9341         }
9342     };
9343     return DebounceSubscriber;
9344 }(OuterSubscriber_1.OuterSubscriber));
9345
9346 },{"../OuterSubscriber":33,"../util/subscribeToResult":221}],88:[function(require,module,exports){
9347 "use strict";
9348 var __extends = (this && this.__extends) || (function () {
9349     var extendStatics = function (d, b) {
9350         extendStatics = Object.setPrototypeOf ||
9351             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9352             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9353         return extendStatics(d, b);
9354     }
9355     return function (d, b) {
9356         extendStatics(d, b);
9357         function __() { this.constructor = d; }
9358         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9359     };
9360 })();
9361 Object.defineProperty(exports, "__esModule", { value: true });
9362 var Subscriber_1 = require("../Subscriber");
9363 var async_1 = require("../scheduler/async");
9364 function debounceTime(dueTime, scheduler) {
9365     if (scheduler === void 0) { scheduler = async_1.async; }
9366     return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); };
9367 }
9368 exports.debounceTime = debounceTime;
9369 var DebounceTimeOperator = (function () {
9370     function DebounceTimeOperator(dueTime, scheduler) {
9371         this.dueTime = dueTime;
9372         this.scheduler = scheduler;
9373     }
9374     DebounceTimeOperator.prototype.call = function (subscriber, source) {
9375         return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
9376     };
9377     return DebounceTimeOperator;
9378 }());
9379 var DebounceTimeSubscriber = (function (_super) {
9380     __extends(DebounceTimeSubscriber, _super);
9381     function DebounceTimeSubscriber(destination, dueTime, scheduler) {
9382         var _this = _super.call(this, destination) || this;
9383         _this.dueTime = dueTime;
9384         _this.scheduler = scheduler;
9385         _this.debouncedSubscription = null;
9386         _this.lastValue = null;
9387         _this.hasValue = false;
9388         return _this;
9389     }
9390     DebounceTimeSubscriber.prototype._next = function (value) {
9391         this.clearDebounce();
9392         this.lastValue = value;
9393         this.hasValue = true;
9394         this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
9395     };
9396     DebounceTimeSubscriber.prototype._complete = function () {
9397         this.debouncedNext();
9398         this.destination.complete();
9399     };
9400     DebounceTimeSubscriber.prototype.debouncedNext = function () {
9401         this.clearDebounce();
9402         if (this.hasValue) {
9403             var lastValue = this.lastValue;
9404             this.lastValue = null;
9405             this.hasValue = false;
9406             this.destination.next(lastValue);
9407         }
9408     };
9409     DebounceTimeSubscriber.prototype.clearDebounce = function () {
9410         var debouncedSubscription = this.debouncedSubscription;
9411         if (debouncedSubscription !== null) {
9412             this.remove(debouncedSubscription);
9413             debouncedSubscription.unsubscribe();
9414             this.debouncedSubscription = null;
9415         }
9416     };
9417     return DebounceTimeSubscriber;
9418 }(Subscriber_1.Subscriber));
9419 function dispatchNext(subscriber) {
9420     subscriber.debouncedNext();
9421 }
9422
9423 },{"../Subscriber":38,"../scheduler/async":187}],89:[function(require,module,exports){
9424 "use strict";
9425 var __extends = (this && this.__extends) || (function () {
9426     var extendStatics = function (d, b) {
9427         extendStatics = Object.setPrototypeOf ||
9428             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9429             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9430         return extendStatics(d, b);
9431     }
9432     return function (d, b) {
9433         extendStatics(d, b);
9434         function __() { this.constructor = d; }
9435         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9436     };
9437 })();
9438 Object.defineProperty(exports, "__esModule", { value: true });
9439 var Subscriber_1 = require("../Subscriber");
9440 function defaultIfEmpty(defaultValue) {
9441     if (defaultValue === void 0) { defaultValue = null; }
9442     return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); };
9443 }
9444 exports.defaultIfEmpty = defaultIfEmpty;
9445 var DefaultIfEmptyOperator = (function () {
9446     function DefaultIfEmptyOperator(defaultValue) {
9447         this.defaultValue = defaultValue;
9448     }
9449     DefaultIfEmptyOperator.prototype.call = function (subscriber, source) {
9450         return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
9451     };
9452     return DefaultIfEmptyOperator;
9453 }());
9454 var DefaultIfEmptySubscriber = (function (_super) {
9455     __extends(DefaultIfEmptySubscriber, _super);
9456     function DefaultIfEmptySubscriber(destination, defaultValue) {
9457         var _this = _super.call(this, destination) || this;
9458         _this.defaultValue = defaultValue;
9459         _this.isEmpty = true;
9460         return _this;
9461     }
9462     DefaultIfEmptySubscriber.prototype._next = function (value) {
9463         this.isEmpty = false;
9464         this.destination.next(value);
9465     };
9466     DefaultIfEmptySubscriber.prototype._complete = function () {
9467         if (this.isEmpty) {
9468             this.destination.next(this.defaultValue);
9469         }
9470         this.destination.complete();
9471     };
9472     return DefaultIfEmptySubscriber;
9473 }(Subscriber_1.Subscriber));
9474
9475 },{"../Subscriber":38}],90:[function(require,module,exports){
9476 "use strict";
9477 var __extends = (this && this.__extends) || (function () {
9478     var extendStatics = function (d, b) {
9479         extendStatics = Object.setPrototypeOf ||
9480             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9481             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9482         return extendStatics(d, b);
9483     }
9484     return function (d, b) {
9485         extendStatics(d, b);
9486         function __() { this.constructor = d; }
9487         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9488     };
9489 })();
9490 Object.defineProperty(exports, "__esModule", { value: true });
9491 var async_1 = require("../scheduler/async");
9492 var isDate_1 = require("../util/isDate");
9493 var Subscriber_1 = require("../Subscriber");
9494 var Notification_1 = require("../Notification");
9495 function delay(delay, scheduler) {
9496     if (scheduler === void 0) { scheduler = async_1.async; }
9497     var absoluteDelay = isDate_1.isDate(delay);
9498     var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
9499     return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };
9500 }
9501 exports.delay = delay;
9502 var DelayOperator = (function () {
9503     function DelayOperator(delay, scheduler) {
9504         this.delay = delay;
9505         this.scheduler = scheduler;
9506     }
9507     DelayOperator.prototype.call = function (subscriber, source) {
9508         return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
9509     };
9510     return DelayOperator;
9511 }());
9512 var DelaySubscriber = (function (_super) {
9513     __extends(DelaySubscriber, _super);
9514     function DelaySubscriber(destination, delay, scheduler) {
9515         var _this = _super.call(this, destination) || this;
9516         _this.delay = delay;
9517         _this.scheduler = scheduler;
9518         _this.queue = [];
9519         _this.active = false;
9520         _this.errored = false;
9521         return _this;
9522     }
9523     DelaySubscriber.dispatch = function (state) {
9524         var source = state.source;
9525         var queue = source.queue;
9526         var scheduler = state.scheduler;
9527         var destination = state.destination;
9528         while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
9529             queue.shift().notification.observe(destination);
9530         }
9531         if (queue.length > 0) {
9532             var delay_1 = Math.max(0, queue[0].time - scheduler.now());
9533             this.schedule(state, delay_1);
9534         }
9535         else {
9536             this.unsubscribe();
9537             source.active = false;
9538         }
9539     };
9540     DelaySubscriber.prototype._schedule = function (scheduler) {
9541         this.active = true;
9542         var destination = this.destination;
9543         destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
9544             source: this, destination: this.destination, scheduler: scheduler
9545         }));
9546     };
9547     DelaySubscriber.prototype.scheduleNotification = function (notification) {
9548         if (this.errored === true) {
9549             return;
9550         }
9551         var scheduler = this.scheduler;
9552         var message = new DelayMessage(scheduler.now() + this.delay, notification);
9553         this.queue.push(message);
9554         if (this.active === false) {
9555             this._schedule(scheduler);
9556         }
9557     };
9558     DelaySubscriber.prototype._next = function (value) {
9559         this.scheduleNotification(Notification_1.Notification.createNext(value));
9560     };
9561     DelaySubscriber.prototype._error = function (err) {
9562         this.errored = true;
9563         this.queue = [];
9564         this.destination.error(err);
9565         this.unsubscribe();
9566     };
9567     DelaySubscriber.prototype._complete = function () {
9568         this.scheduleNotification(Notification_1.Notification.createComplete());
9569         this.unsubscribe();
9570     };
9571     return DelaySubscriber;
9572 }(Subscriber_1.Subscriber));
9573 var DelayMessage = (function () {
9574     function DelayMessage(time, notification) {
9575         this.time = time;
9576         this.notification = notification;
9577     }
9578     return DelayMessage;
9579 }());
9580
9581 },{"../Notification":30,"../Subscriber":38,"../scheduler/async":187,"../util/isDate":204}],91:[function(require,module,exports){
9582 "use strict";
9583 var __extends = (this && this.__extends) || (function () {
9584     var extendStatics = function (d, b) {
9585         extendStatics = Object.setPrototypeOf ||
9586             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9587             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9588         return extendStatics(d, b);
9589     }
9590     return function (d, b) {
9591         extendStatics(d, b);
9592         function __() { this.constructor = d; }
9593         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9594     };
9595 })();
9596 Object.defineProperty(exports, "__esModule", { value: true });
9597 var Subscriber_1 = require("../Subscriber");
9598 var Observable_1 = require("../Observable");
9599 var OuterSubscriber_1 = require("../OuterSubscriber");
9600 var subscribeToResult_1 = require("../util/subscribeToResult");
9601 function delayWhen(delayDurationSelector, subscriptionDelay) {
9602     if (subscriptionDelay) {
9603         return function (source) {
9604             return new SubscriptionDelayObservable(source, subscriptionDelay)
9605                 .lift(new DelayWhenOperator(delayDurationSelector));
9606         };
9607     }
9608     return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); };
9609 }
9610 exports.delayWhen = delayWhen;
9611 var DelayWhenOperator = (function () {
9612     function DelayWhenOperator(delayDurationSelector) {
9613         this.delayDurationSelector = delayDurationSelector;
9614     }
9615     DelayWhenOperator.prototype.call = function (subscriber, source) {
9616         return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector));
9617     };
9618     return DelayWhenOperator;
9619 }());
9620 var DelayWhenSubscriber = (function (_super) {
9621     __extends(DelayWhenSubscriber, _super);
9622     function DelayWhenSubscriber(destination, delayDurationSelector) {
9623         var _this = _super.call(this, destination) || this;
9624         _this.delayDurationSelector = delayDurationSelector;
9625         _this.completed = false;
9626         _this.delayNotifierSubscriptions = [];
9627         _this.index = 0;
9628         return _this;
9629     }
9630     DelayWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9631         this.destination.next(outerValue);
9632         this.removeSubscription(innerSub);
9633         this.tryComplete();
9634     };
9635     DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) {
9636         this._error(error);
9637     };
9638     DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) {
9639         var value = this.removeSubscription(innerSub);
9640         if (value) {
9641             this.destination.next(value);
9642         }
9643         this.tryComplete();
9644     };
9645     DelayWhenSubscriber.prototype._next = function (value) {
9646         var index = this.index++;
9647         try {
9648             var delayNotifier = this.delayDurationSelector(value, index);
9649             if (delayNotifier) {
9650                 this.tryDelay(delayNotifier, value);
9651             }
9652         }
9653         catch (err) {
9654             this.destination.error(err);
9655         }
9656     };
9657     DelayWhenSubscriber.prototype._complete = function () {
9658         this.completed = true;
9659         this.tryComplete();
9660         this.unsubscribe();
9661     };
9662     DelayWhenSubscriber.prototype.removeSubscription = function (subscription) {
9663         subscription.unsubscribe();
9664         var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);
9665         if (subscriptionIdx !== -1) {
9666             this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);
9667         }
9668         return subscription.outerValue;
9669     };
9670     DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) {
9671         var notifierSubscription = subscribeToResult_1.subscribeToResult(this, delayNotifier, value);
9672         if (notifierSubscription && !notifierSubscription.closed) {
9673             var destination = this.destination;
9674             destination.add(notifierSubscription);
9675             this.delayNotifierSubscriptions.push(notifierSubscription);
9676         }
9677     };
9678     DelayWhenSubscriber.prototype.tryComplete = function () {
9679         if (this.completed && this.delayNotifierSubscriptions.length === 0) {
9680             this.destination.complete();
9681         }
9682     };
9683     return DelayWhenSubscriber;
9684 }(OuterSubscriber_1.OuterSubscriber));
9685 var SubscriptionDelayObservable = (function (_super) {
9686     __extends(SubscriptionDelayObservable, _super);
9687     function SubscriptionDelayObservable(source, subscriptionDelay) {
9688         var _this = _super.call(this) || this;
9689         _this.source = source;
9690         _this.subscriptionDelay = subscriptionDelay;
9691         return _this;
9692     }
9693     SubscriptionDelayObservable.prototype._subscribe = function (subscriber) {
9694         this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source));
9695     };
9696     return SubscriptionDelayObservable;
9697 }(Observable_1.Observable));
9698 var SubscriptionDelaySubscriber = (function (_super) {
9699     __extends(SubscriptionDelaySubscriber, _super);
9700     function SubscriptionDelaySubscriber(parent, source) {
9701         var _this = _super.call(this) || this;
9702         _this.parent = parent;
9703         _this.source = source;
9704         _this.sourceSubscribed = false;
9705         return _this;
9706     }
9707     SubscriptionDelaySubscriber.prototype._next = function (unused) {
9708         this.subscribeToSource();
9709     };
9710     SubscriptionDelaySubscriber.prototype._error = function (err) {
9711         this.unsubscribe();
9712         this.parent.error(err);
9713     };
9714     SubscriptionDelaySubscriber.prototype._complete = function () {
9715         this.unsubscribe();
9716         this.subscribeToSource();
9717     };
9718     SubscriptionDelaySubscriber.prototype.subscribeToSource = function () {
9719         if (!this.sourceSubscribed) {
9720             this.sourceSubscribed = true;
9721             this.unsubscribe();
9722             this.source.subscribe(this.parent);
9723         }
9724     };
9725     return SubscriptionDelaySubscriber;
9726 }(Subscriber_1.Subscriber));
9727
9728 },{"../Observable":31,"../OuterSubscriber":33,"../Subscriber":38,"../util/subscribeToResult":221}],92:[function(require,module,exports){
9729 "use strict";
9730 var __extends = (this && this.__extends) || (function () {
9731     var extendStatics = function (d, b) {
9732         extendStatics = Object.setPrototypeOf ||
9733             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9734             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9735         return extendStatics(d, b);
9736     }
9737     return function (d, b) {
9738         extendStatics(d, b);
9739         function __() { this.constructor = d; }
9740         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9741     };
9742 })();
9743 Object.defineProperty(exports, "__esModule", { value: true });
9744 var Subscriber_1 = require("../Subscriber");
9745 function dematerialize() {
9746     return function dematerializeOperatorFunction(source) {
9747         return source.lift(new DeMaterializeOperator());
9748     };
9749 }
9750 exports.dematerialize = dematerialize;
9751 var DeMaterializeOperator = (function () {
9752     function DeMaterializeOperator() {
9753     }
9754     DeMaterializeOperator.prototype.call = function (subscriber, source) {
9755         return source.subscribe(new DeMaterializeSubscriber(subscriber));
9756     };
9757     return DeMaterializeOperator;
9758 }());
9759 var DeMaterializeSubscriber = (function (_super) {
9760     __extends(DeMaterializeSubscriber, _super);
9761     function DeMaterializeSubscriber(destination) {
9762         return _super.call(this, destination) || this;
9763     }
9764     DeMaterializeSubscriber.prototype._next = function (value) {
9765         value.observe(this.destination);
9766     };
9767     return DeMaterializeSubscriber;
9768 }(Subscriber_1.Subscriber));
9769
9770 },{"../Subscriber":38}],93:[function(require,module,exports){
9771 "use strict";
9772 var __extends = (this && this.__extends) || (function () {
9773     var extendStatics = function (d, b) {
9774         extendStatics = Object.setPrototypeOf ||
9775             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9776             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9777         return extendStatics(d, b);
9778     }
9779     return function (d, b) {
9780         extendStatics(d, b);
9781         function __() { this.constructor = d; }
9782         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9783     };
9784 })();
9785 Object.defineProperty(exports, "__esModule", { value: true });
9786 var OuterSubscriber_1 = require("../OuterSubscriber");
9787 var subscribeToResult_1 = require("../util/subscribeToResult");
9788 function distinct(keySelector, flushes) {
9789     return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); };
9790 }
9791 exports.distinct = distinct;
9792 var DistinctOperator = (function () {
9793     function DistinctOperator(keySelector, flushes) {
9794         this.keySelector = keySelector;
9795         this.flushes = flushes;
9796     }
9797     DistinctOperator.prototype.call = function (subscriber, source) {
9798         return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
9799     };
9800     return DistinctOperator;
9801 }());
9802 var DistinctSubscriber = (function (_super) {
9803     __extends(DistinctSubscriber, _super);
9804     function DistinctSubscriber(destination, keySelector, flushes) {
9805         var _this = _super.call(this, destination) || this;
9806         _this.keySelector = keySelector;
9807         _this.values = new Set();
9808         if (flushes) {
9809             _this.add(subscribeToResult_1.subscribeToResult(_this, flushes));
9810         }
9811         return _this;
9812     }
9813     DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9814         this.values.clear();
9815     };
9816     DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
9817         this._error(error);
9818     };
9819     DistinctSubscriber.prototype._next = function (value) {
9820         if (this.keySelector) {
9821             this._useKeySelector(value);
9822         }
9823         else {
9824             this._finalizeNext(value, value);
9825         }
9826     };
9827     DistinctSubscriber.prototype._useKeySelector = function (value) {
9828         var key;
9829         var destination = this.destination;
9830         try {
9831             key = this.keySelector(value);
9832         }
9833         catch (err) {
9834             destination.error(err);
9835             return;
9836         }
9837         this._finalizeNext(key, value);
9838     };
9839     DistinctSubscriber.prototype._finalizeNext = function (key, value) {
9840         var values = this.values;
9841         if (!values.has(key)) {
9842             values.add(key);
9843             this.destination.next(value);
9844         }
9845     };
9846     return DistinctSubscriber;
9847 }(OuterSubscriber_1.OuterSubscriber));
9848 exports.DistinctSubscriber = DistinctSubscriber;
9849
9850 },{"../OuterSubscriber":33,"../util/subscribeToResult":221}],94:[function(require,module,exports){
9851 "use strict";
9852 var __extends = (this && this.__extends) || (function () {
9853     var extendStatics = function (d, b) {
9854         extendStatics = Object.setPrototypeOf ||
9855             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9856             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9857         return extendStatics(d, b);
9858     }
9859     return function (d, b) {
9860         extendStatics(d, b);
9861         function __() { this.constructor = d; }
9862         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9863     };
9864 })();
9865 Object.defineProperty(exports, "__esModule", { value: true });
9866 var Subscriber_1 = require("../Subscriber");
9867 var tryCatch_1 = require("../util/tryCatch");
9868 var errorObject_1 = require("../util/errorObject");
9869 function distinctUntilChanged(compare, keySelector) {
9870     return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); };
9871 }
9872 exports.distinctUntilChanged = distinctUntilChanged;
9873 var DistinctUntilChangedOperator = (function () {
9874     function DistinctUntilChangedOperator(compare, keySelector) {
9875         this.compare = compare;
9876         this.keySelector = keySelector;
9877     }
9878     DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
9879         return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
9880     };
9881     return DistinctUntilChangedOperator;
9882 }());
9883 var DistinctUntilChangedSubscriber = (function (_super) {
9884     __extends(DistinctUntilChangedSubscriber, _super);
9885     function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
9886         var _this = _super.call(this, destination) || this;
9887         _this.keySelector = keySelector;
9888         _this.hasKey = false;
9889         if (typeof compare === 'function') {
9890             _this.compare = compare;
9891         }
9892         return _this;
9893     }
9894     DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
9895         return x === y;
9896     };
9897     DistinctUntilChangedSubscriber.prototype._next = function (value) {
9898         var keySelector = this.keySelector;
9899         var key = value;
9900         if (keySelector) {
9901             key = tryCatch_1.tryCatch(this.keySelector)(value);
9902             if (key === errorObject_1.errorObject) {
9903                 return this.destination.error(errorObject_1.errorObject.e);
9904             }
9905         }
9906         var result = false;
9907         if (this.hasKey) {
9908             result = tryCatch_1.tryCatch(this.compare)(this.key, key);
9909             if (result === errorObject_1.errorObject) {
9910                 return this.destination.error(errorObject_1.errorObject.e);
9911             }
9912         }
9913         else {
9914             this.hasKey = true;
9915         }
9916         if (Boolean(result) === false) {
9917             this.key = key;
9918             this.destination.next(value);
9919         }
9920     };
9921     return DistinctUntilChangedSubscriber;
9922 }(Subscriber_1.Subscriber));
9923
9924 },{"../Subscriber":38,"../util/errorObject":199,"../util/tryCatch":223}],95:[function(require,module,exports){
9925 "use strict";
9926 Object.defineProperty(exports, "__esModule", { value: true });
9927 var distinctUntilChanged_1 = require("./distinctUntilChanged");
9928 function distinctUntilKeyChanged(key, compare) {
9929     return distinctUntilChanged_1.distinctUntilChanged(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; });
9930 }
9931 exports.distinctUntilKeyChanged = distinctUntilKeyChanged;
9932
9933 },{"./distinctUntilChanged":94}],96:[function(require,module,exports){
9934 "use strict";
9935 Object.defineProperty(exports, "__esModule", { value: true });
9936 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
9937 var filter_1 = require("./filter");
9938 var throwIfEmpty_1 = require("./throwIfEmpty");
9939 var defaultIfEmpty_1 = require("./defaultIfEmpty");
9940 var take_1 = require("./take");
9941 function elementAt(index, defaultValue) {
9942     if (index < 0) {
9943         throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError();
9944     }
9945     var hasDefaultValue = arguments.length >= 2;
9946     return function (source) { return source.pipe(filter_1.filter(function (v, i) { return i === index; }), take_1.take(1), hasDefaultValue
9947         ? defaultIfEmpty_1.defaultIfEmpty(defaultValue)
9948         : throwIfEmpty_1.throwIfEmpty(function () { return new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError(); })); };
9949 }
9950 exports.elementAt = elementAt;
9951
9952 },{"../util/ArgumentOutOfRangeError":192,"./defaultIfEmpty":89,"./filter":102,"./take":154,"./throwIfEmpty":161}],97:[function(require,module,exports){
9953 "use strict";
9954 Object.defineProperty(exports, "__esModule", { value: true });
9955 var fromArray_1 = require("../observable/fromArray");
9956 var scalar_1 = require("../observable/scalar");
9957 var empty_1 = require("../observable/empty");
9958 var concat_1 = require("../observable/concat");
9959 var isScheduler_1 = require("../util/isScheduler");
9960 function endWith() {
9961     var array = [];
9962     for (var _i = 0; _i < arguments.length; _i++) {
9963         array[_i] = arguments[_i];
9964     }
9965     return function (source) {
9966         var scheduler = array[array.length - 1];
9967         if (isScheduler_1.isScheduler(scheduler)) {
9968             array.pop();
9969         }
9970         else {
9971             scheduler = null;
9972         }
9973         var len = array.length;
9974         if (len === 1 && !scheduler) {
9975             return concat_1.concat(source, scalar_1.scalar(array[0]));
9976         }
9977         else if (len > 0) {
9978             return concat_1.concat(source, fromArray_1.fromArray(array, scheduler));
9979         }
9980         else {
9981             return concat_1.concat(source, empty_1.empty(scheduler));
9982         }
9983     };
9984 }
9985 exports.endWith = endWith;
9986
9987 },{"../observable/concat":46,"../observable/empty":48,"../observable/fromArray":51,"../observable/scalar":67,"../util/isScheduler":212}],98:[function(require,module,exports){
9988 "use strict";
9989 var __extends = (this && this.__extends) || (function () {
9990     var extendStatics = function (d, b) {
9991         extendStatics = Object.setPrototypeOf ||
9992             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
9993             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
9994         return extendStatics(d, b);
9995     }
9996     return function (d, b) {
9997         extendStatics(d, b);
9998         function __() { this.constructor = d; }
9999         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10000     };
10001 })();
10002 Object.defineProperty(exports, "__esModule", { value: true });
10003 var Subscriber_1 = require("../Subscriber");
10004 function every(predicate, thisArg) {
10005     return function (source) { return source.lift(new EveryOperator(predicate, thisArg, source)); };
10006 }
10007 exports.every = every;
10008 var EveryOperator = (function () {
10009     function EveryOperator(predicate, thisArg, source) {
10010         this.predicate = predicate;
10011         this.thisArg = thisArg;
10012         this.source = source;
10013     }
10014     EveryOperator.prototype.call = function (observer, source) {
10015         return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));
10016     };
10017     return EveryOperator;
10018 }());
10019 var EverySubscriber = (function (_super) {
10020     __extends(EverySubscriber, _super);
10021     function EverySubscriber(destination, predicate, thisArg, source) {
10022         var _this = _super.call(this, destination) || this;
10023         _this.predicate = predicate;
10024         _this.thisArg = thisArg;
10025         _this.source = source;
10026         _this.index = 0;
10027         _this.thisArg = thisArg || _this;
10028         return _this;
10029     }
10030     EverySubscriber.prototype.notifyComplete = function (everyValueMatch) {
10031         this.destination.next(everyValueMatch);
10032         this.destination.complete();
10033     };
10034     EverySubscriber.prototype._next = function (value) {
10035         var result = false;
10036         try {
10037             result = this.predicate.call(this.thisArg, value, this.index++, this.source);
10038         }
10039         catch (err) {
10040             this.destination.error(err);
10041             return;
10042         }
10043         if (!result) {
10044             this.notifyComplete(false);
10045         }
10046     };
10047     EverySubscriber.prototype._complete = function () {
10048         this.notifyComplete(true);
10049     };
10050     return EverySubscriber;
10051 }(Subscriber_1.Subscriber));
10052
10053 },{"../Subscriber":38}],99:[function(require,module,exports){
10054 "use strict";
10055 var __extends = (this && this.__extends) || (function () {
10056     var extendStatics = function (d, b) {
10057         extendStatics = Object.setPrototypeOf ||
10058             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10059             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10060         return extendStatics(d, b);
10061     }
10062     return function (d, b) {
10063         extendStatics(d, b);
10064         function __() { this.constructor = d; }
10065         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10066     };
10067 })();
10068 Object.defineProperty(exports, "__esModule", { value: true });
10069 var OuterSubscriber_1 = require("../OuterSubscriber");
10070 var subscribeToResult_1 = require("../util/subscribeToResult");
10071 function exhaust() {
10072     return function (source) { return source.lift(new SwitchFirstOperator()); };
10073 }
10074 exports.exhaust = exhaust;
10075 var SwitchFirstOperator = (function () {
10076     function SwitchFirstOperator() {
10077     }
10078     SwitchFirstOperator.prototype.call = function (subscriber, source) {
10079         return source.subscribe(new SwitchFirstSubscriber(subscriber));
10080     };
10081     return SwitchFirstOperator;
10082 }());
10083 var SwitchFirstSubscriber = (function (_super) {
10084     __extends(SwitchFirstSubscriber, _super);
10085     function SwitchFirstSubscriber(destination) {
10086         var _this = _super.call(this, destination) || this;
10087         _this.hasCompleted = false;
10088         _this.hasSubscription = false;
10089         return _this;
10090     }
10091     SwitchFirstSubscriber.prototype._next = function (value) {
10092         if (!this.hasSubscription) {
10093             this.hasSubscription = true;
10094             this.add(subscribeToResult_1.subscribeToResult(this, value));
10095         }
10096     };
10097     SwitchFirstSubscriber.prototype._complete = function () {
10098         this.hasCompleted = true;
10099         if (!this.hasSubscription) {
10100             this.destination.complete();
10101         }
10102     };
10103     SwitchFirstSubscriber.prototype.notifyComplete = function (innerSub) {
10104         this.remove(innerSub);
10105         this.hasSubscription = false;
10106         if (this.hasCompleted) {
10107             this.destination.complete();
10108         }
10109     };
10110     return SwitchFirstSubscriber;
10111 }(OuterSubscriber_1.OuterSubscriber));
10112
10113 },{"../OuterSubscriber":33,"../util/subscribeToResult":221}],100:[function(require,module,exports){
10114 "use strict";
10115 var __extends = (this && this.__extends) || (function () {
10116     var extendStatics = function (d, b) {
10117         extendStatics = Object.setPrototypeOf ||
10118             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10119             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10120         return extendStatics(d, b);
10121     }
10122     return function (d, b) {
10123         extendStatics(d, b);
10124         function __() { this.constructor = d; }
10125         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10126     };
10127 })();
10128 Object.defineProperty(exports, "__esModule", { value: true });
10129 var OuterSubscriber_1 = require("../OuterSubscriber");
10130 var InnerSubscriber_1 = require("../InnerSubscriber");
10131 var subscribeToResult_1 = require("../util/subscribeToResult");
10132 var map_1 = require("./map");
10133 var from_1 = require("../observable/from");
10134 function exhaustMap(project, resultSelector) {
10135     if (resultSelector) {
10136         return function (source) { return source.pipe(exhaustMap(function (a, i) { return from_1.from(project(a, i)).pipe(map_1.map(function (b, ii) { return resultSelector(a, b, i, ii); })); })); };
10137     }
10138     return function (source) {
10139         return source.lift(new ExhauseMapOperator(project));
10140     };
10141 }
10142 exports.exhaustMap = exhaustMap;
10143 var ExhauseMapOperator = (function () {
10144     function ExhauseMapOperator(project) {
10145         this.project = project;
10146     }
10147     ExhauseMapOperator.prototype.call = function (subscriber, source) {
10148         return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project));
10149     };
10150     return ExhauseMapOperator;
10151 }());
10152 var ExhaustMapSubscriber = (function (_super) {
10153     __extends(ExhaustMapSubscriber, _super);
10154     function ExhaustMapSubscriber(destination, project) {
10155         var _this = _super.call(this, destination) || this;
10156         _this.project = project;
10157         _this.hasSubscription = false;
10158         _this.hasCompleted = false;
10159         _this.index = 0;
10160         return _this;
10161     }
10162     ExhaustMapSubscriber.prototype._next = function (value) {
10163         if (!this.hasSubscription) {
10164             this.tryNext(value);
10165         }
10166     };
10167     ExhaustMapSubscriber.prototype.tryNext = function (value) {
10168         var result;
10169         var index = this.index++;
10170         try {
10171             result = this.project(value, index);
10172         }
10173         catch (err) {
10174             this.destination.error(err);
10175             return;
10176         }
10177         this.hasSubscription = true;
10178         this._innerSub(result, value, index);
10179     };
10180     ExhaustMapSubscriber.prototype._innerSub = function (result, value, index) {
10181         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
10182         var destination = this.destination;
10183         destination.add(innerSubscriber);
10184         subscribeToResult_1.subscribeToResult(this, result, value, index, innerSubscriber);
10185     };
10186     ExhaustMapSubscriber.prototype._complete = function () {
10187         this.hasCompleted = true;
10188         if (!this.hasSubscription) {
10189             this.destination.complete();
10190         }
10191         this.unsubscribe();
10192     };
10193     ExhaustMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10194         this.destination.next(innerValue);
10195     };
10196     ExhaustMapSubscriber.prototype.notifyError = function (err) {
10197         this.destination.error(err);
10198     };
10199     ExhaustMapSubscriber.prototype.notifyComplete = function (innerSub) {
10200         var destination = this.destination;
10201         destination.remove(innerSub);
10202         this.hasSubscription = false;
10203         if (this.hasCompleted) {
10204             this.destination.complete();
10205         }
10206     };
10207     return ExhaustMapSubscriber;
10208 }(OuterSubscriber_1.OuterSubscriber));
10209
10210 },{"../InnerSubscriber":29,"../OuterSubscriber":33,"../observable/from":50,"../util/subscribeToResult":221,"./map":111}],101:[function(require,module,exports){
10211 "use strict";
10212 var __extends = (this && this.__extends) || (function () {
10213     var extendStatics = function (d, b) {
10214         extendStatics = Object.setPrototypeOf ||
10215             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10216             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10217         return extendStatics(d, b);
10218     }
10219     return function (d, b) {
10220         extendStatics(d, b);
10221         function __() { this.constructor = d; }
10222         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10223     };
10224 })();
10225 Object.defineProperty(exports, "__esModule", { value: true });
10226 var tryCatch_1 = require("../util/tryCatch");
10227 var errorObject_1 = require("../util/errorObject");
10228 var OuterSubscriber_1 = require("../OuterSubscriber");
10229 var subscribeToResult_1 = require("../util/subscribeToResult");
10230 function expand(project, concurrent, scheduler) {
10231     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10232     if (scheduler === void 0) { scheduler = undefined; }
10233     concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
10234     return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); };
10235 }
10236 exports.expand = expand;
10237 var ExpandOperator = (function () {
10238     function ExpandOperator(project, concurrent, scheduler) {
10239         this.project = project;
10240         this.concurrent = concurrent;
10241         this.scheduler = scheduler;
10242     }
10243     ExpandOperator.prototype.call = function (subscriber, source) {
10244         return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
10245     };
10246     return ExpandOperator;
10247 }());
10248 exports.ExpandOperator = ExpandOperator;
10249 var ExpandSubscriber = (function (_super) {
10250     __extends(ExpandSubscriber, _super);
10251     function ExpandSubscriber(destination, project, concurrent, scheduler) {
10252         var _this = _super.call(this, destination) || this;
10253         _this.project = project;
10254         _this.concurrent = concurrent;
10255         _this.scheduler = scheduler;
10256         _this.index = 0;
10257         _this.active = 0;
10258         _this.hasCompleted = false;
10259         if (concurrent < Number.POSITIVE_INFINITY) {
10260             _this.buffer = [];
10261         }
10262         return _this;
10263     }
10264     ExpandSubscriber.dispatch = function (arg) {
10265         var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
10266         subscriber.subscribeToProjection(result, value, index);
10267     };
10268     ExpandSubscriber.prototype._next = function (value) {
10269         var destination = this.destination;
10270         if (destination.closed) {
10271             this._complete();
10272             return;
10273         }
10274         var index = this.index++;
10275         if (this.active < this.concurrent) {
10276             destination.next(value);
10277             var result = tryCatch_1.tryCatch(this.project)(value, index);
10278             if (result === errorObject_1.errorObject) {
10279                 destination.error(errorObject_1.errorObject.e);
10280             }
10281             else if (!this.scheduler) {
10282                 this.subscribeToProjection(result, value, index);
10283             }
10284             else {
10285                 var state = { subscriber: this, result: result, value: value, index: index };
10286                 var destination_1 = this.destination;
10287                 destination_1.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
10288             }
10289         }
10290         else {
10291             this.buffer.push(value);
10292         }
10293     };
10294     ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
10295         this.active++;
10296         var destination = this.destination;
10297         destination.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
10298     };
10299     ExpandSubscriber.prototype._complete = function () {
10300         this.hasCompleted = true;
10301         if (this.hasCompleted && this.active === 0) {
10302             this.destination.complete();
10303         }
10304         this.unsubscribe();
10305     };
10306     ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10307         this._next(innerValue);
10308     };
10309     ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
10310         var buffer = this.buffer;
10311         var destination = this.destination;
10312         destination.remove(innerSub);
10313         this.active--;
10314         if (buffer && buffer.length > 0) {
10315             this._next(buffer.shift());
10316         }
10317         if (this.hasCompleted && this.active === 0) {
10318             this.destination.complete();
10319         }
10320     };
10321     return ExpandSubscriber;
10322 }(OuterSubscriber_1.OuterSubscriber));
10323 exports.ExpandSubscriber = ExpandSubscriber;
10324
10325 },{"../OuterSubscriber":33,"../util/errorObject":199,"../util/subscribeToResult":221,"../util/tryCatch":223}],102:[function(require,module,exports){
10326 "use strict";
10327 var __extends = (this && this.__extends) || (function () {
10328     var extendStatics = function (d, b) {
10329         extendStatics = Object.setPrototypeOf ||
10330             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10331             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10332         return extendStatics(d, b);
10333     }
10334     return function (d, b) {
10335         extendStatics(d, b);
10336         function __() { this.constructor = d; }
10337         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10338     };
10339 })();
10340 Object.defineProperty(exports, "__esModule", { value: true });
10341 var Subscriber_1 = require("../Subscriber");
10342 function filter(predicate, thisArg) {
10343     return function filterOperatorFunction(source) {
10344         return source.lift(new FilterOperator(predicate, thisArg));
10345     };
10346 }
10347 exports.filter = filter;
10348 var FilterOperator = (function () {
10349     function FilterOperator(predicate, thisArg) {
10350         this.predicate = predicate;
10351         this.thisArg = thisArg;
10352     }
10353     FilterOperator.prototype.call = function (subscriber, source) {
10354         return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
10355     };
10356     return FilterOperator;
10357 }());
10358 var FilterSubscriber = (function (_super) {
10359     __extends(FilterSubscriber, _super);
10360     function FilterSubscriber(destination, predicate, thisArg) {
10361         var _this = _super.call(this, destination) || this;
10362         _this.predicate = predicate;
10363         _this.thisArg = thisArg;
10364         _this.count = 0;
10365         return _this;
10366     }
10367     FilterSubscriber.prototype._next = function (value) {
10368         var result;
10369         try {
10370             result = this.predicate.call(this.thisArg, value, this.count++);
10371         }
10372         catch (err) {
10373             this.destination.error(err);
10374             return;
10375         }
10376         if (result) {
10377             this.destination.next(value);
10378         }
10379     };
10380     return FilterSubscriber;
10381 }(Subscriber_1.Subscriber));
10382
10383 },{"../Subscriber":38}],103:[function(require,module,exports){
10384 "use strict";
10385 var __extends = (this && this.__extends) || (function () {
10386     var extendStatics = function (d, b) {
10387         extendStatics = Object.setPrototypeOf ||
10388             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10389             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10390         return extendStatics(d, b);
10391     }
10392     return function (d, b) {
10393         extendStatics(d, b);
10394         function __() { this.constructor = d; }
10395         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10396     };
10397 })();
10398 Object.defineProperty(exports, "__esModule", { value: true });
10399 var Subscriber_1 = require("../Subscriber");
10400 var Subscription_1 = require("../Subscription");
10401 function finalize(callback) {
10402     return function (source) { return source.lift(new FinallyOperator(callback)); };
10403 }
10404 exports.finalize = finalize;
10405 var FinallyOperator = (function () {
10406     function FinallyOperator(callback) {
10407         this.callback = callback;
10408     }
10409     FinallyOperator.prototype.call = function (subscriber, source) {
10410         return source.subscribe(new FinallySubscriber(subscriber, this.callback));
10411     };
10412     return FinallyOperator;
10413 }());
10414 var FinallySubscriber = (function (_super) {
10415     __extends(FinallySubscriber, _super);
10416     function FinallySubscriber(destination, callback) {
10417         var _this = _super.call(this, destination) || this;
10418         _this.add(new Subscription_1.Subscription(callback));
10419         return _this;
10420     }
10421     return FinallySubscriber;
10422 }(Subscriber_1.Subscriber));
10423
10424 },{"../Subscriber":38,"../Subscription":39}],104:[function(require,module,exports){
10425 "use strict";
10426 var __extends = (this && this.__extends) || (function () {
10427     var extendStatics = function (d, b) {
10428         extendStatics = Object.setPrototypeOf ||
10429             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10430             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10431         return extendStatics(d, b);
10432     }
10433     return function (d, b) {
10434         extendStatics(d, b);
10435         function __() { this.constructor = d; }
10436         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10437     };
10438 })();
10439 Object.defineProperty(exports, "__esModule", { value: true });
10440 var Subscriber_1 = require("../Subscriber");
10441 function find(predicate, thisArg) {
10442     if (typeof predicate !== 'function') {
10443         throw new TypeError('predicate is not a function');
10444     }
10445     return function (source) { return source.lift(new FindValueOperator(predicate, source, false, thisArg)); };
10446 }
10447 exports.find = find;
10448 var FindValueOperator = (function () {
10449     function FindValueOperator(predicate, source, yieldIndex, thisArg) {
10450         this.predicate = predicate;
10451         this.source = source;
10452         this.yieldIndex = yieldIndex;
10453         this.thisArg = thisArg;
10454     }
10455     FindValueOperator.prototype.call = function (observer, source) {
10456         return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));
10457     };
10458     return FindValueOperator;
10459 }());
10460 exports.FindValueOperator = FindValueOperator;
10461 var FindValueSubscriber = (function (_super) {
10462     __extends(FindValueSubscriber, _super);
10463     function FindValueSubscriber(destination, predicate, source, yieldIndex, thisArg) {
10464         var _this = _super.call(this, destination) || this;
10465         _this.predicate = predicate;
10466         _this.source = source;
10467         _this.yieldIndex = yieldIndex;
10468         _this.thisArg = thisArg;
10469         _this.index = 0;
10470         return _this;
10471     }
10472     FindValueSubscriber.prototype.notifyComplete = function (value) {
10473         var destination = this.destination;
10474         destination.next(value);
10475         destination.complete();
10476         this.unsubscribe();
10477     };
10478     FindValueSubscriber.prototype._next = function (value) {
10479         var _a = this, predicate = _a.predicate, thisArg = _a.thisArg;
10480         var index = this.index++;
10481         try {
10482             var result = predicate.call(thisArg || this, value, index, this.source);
10483             if (result) {
10484                 this.notifyComplete(this.yieldIndex ? index : value);
10485             }
10486         }
10487         catch (err) {
10488             this.destination.error(err);
10489         }
10490     };
10491     FindValueSubscriber.prototype._complete = function () {
10492         this.notifyComplete(this.yieldIndex ? -1 : undefined);
10493     };
10494     return FindValueSubscriber;
10495 }(Subscriber_1.Subscriber));
10496 exports.FindValueSubscriber = FindValueSubscriber;
10497
10498 },{"../Subscriber":38}],105:[function(require,module,exports){
10499 "use strict";
10500 Object.defineProperty(exports, "__esModule", { value: true });
10501 var find_1 = require("../operators/find");
10502 function findIndex(predicate, thisArg) {
10503     return function (source) { return source.lift(new find_1.FindValueOperator(predicate, source, true, thisArg)); };
10504 }
10505 exports.findIndex = findIndex;
10506
10507 },{"../operators/find":104}],106:[function(require,module,exports){
10508 "use strict";
10509 Object.defineProperty(exports, "__esModule", { value: true });
10510 var EmptyError_1 = require("../util/EmptyError");
10511 var filter_1 = require("./filter");
10512 var take_1 = require("./take");
10513 var defaultIfEmpty_1 = require("./defaultIfEmpty");
10514 var throwIfEmpty_1 = require("./throwIfEmpty");
10515 var identity_1 = require("../util/identity");
10516 function first(predicate, defaultValue) {
10517     var hasDefaultValue = arguments.length >= 2;
10518     return function (source) { return source.pipe(predicate ? filter_1.filter(function (v, i) { return predicate(v, i, source); }) : identity_1.identity, take_1.take(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function () { return new EmptyError_1.EmptyError(); })); };
10519 }
10520 exports.first = first;
10521
10522 },{"../util/EmptyError":193,"../util/identity":201,"./defaultIfEmpty":89,"./filter":102,"./take":154,"./throwIfEmpty":161}],107:[function(require,module,exports){
10523 "use strict";
10524 var __extends = (this && this.__extends) || (function () {
10525     var extendStatics = function (d, b) {
10526         extendStatics = Object.setPrototypeOf ||
10527             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10528             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10529         return extendStatics(d, b);
10530     }
10531     return function (d, b) {
10532         extendStatics(d, b);
10533         function __() { this.constructor = d; }
10534         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10535     };
10536 })();
10537 Object.defineProperty(exports, "__esModule", { value: true });
10538 var Subscriber_1 = require("../Subscriber");
10539 var Subscription_1 = require("../Subscription");
10540 var Observable_1 = require("../Observable");
10541 var Subject_1 = require("../Subject");
10542 function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) {
10543     return function (source) {
10544         return source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));
10545     };
10546 }
10547 exports.groupBy = groupBy;
10548 var GroupByOperator = (function () {
10549     function GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector) {
10550         this.keySelector = keySelector;
10551         this.elementSelector = elementSelector;
10552         this.durationSelector = durationSelector;
10553         this.subjectSelector = subjectSelector;
10554     }
10555     GroupByOperator.prototype.call = function (subscriber, source) {
10556         return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector));
10557     };
10558     return GroupByOperator;
10559 }());
10560 var GroupBySubscriber = (function (_super) {
10561     __extends(GroupBySubscriber, _super);
10562     function GroupBySubscriber(destination, keySelector, elementSelector, durationSelector, subjectSelector) {
10563         var _this = _super.call(this, destination) || this;
10564         _this.keySelector = keySelector;
10565         _this.elementSelector = elementSelector;
10566         _this.durationSelector = durationSelector;
10567         _this.subjectSelector = subjectSelector;
10568         _this.groups = null;
10569         _this.attemptedToUnsubscribe = false;
10570         _this.count = 0;
10571         return _this;
10572     }
10573     GroupBySubscriber.prototype._next = function (value) {
10574         var key;
10575         try {
10576             key = this.keySelector(value);
10577         }
10578         catch (err) {
10579             this.error(err);
10580             return;
10581         }
10582         this._group(value, key);
10583     };
10584     GroupBySubscriber.prototype._group = function (value, key) {
10585         var groups = this.groups;
10586         if (!groups) {
10587             groups = this.groups = new Map();
10588         }
10589         var group = groups.get(key);
10590         var element;
10591         if (this.elementSelector) {
10592             try {
10593                 element = this.elementSelector(value);
10594             }
10595             catch (err) {
10596                 this.error(err);
10597             }
10598         }
10599         else {
10600             element = value;
10601         }
10602         if (!group) {
10603             group = (this.subjectSelector ? this.subjectSelector() : new Subject_1.Subject());
10604             groups.set(key, group);
10605             var groupedObservable = new GroupedObservable(key, group, this);
10606             this.destination.next(groupedObservable);
10607             if (this.durationSelector) {
10608                 var duration = void 0;
10609                 try {
10610                     duration = this.durationSelector(new GroupedObservable(key, group));
10611                 }
10612                 catch (err) {
10613                     this.error(err);
10614                     return;
10615                 }
10616                 this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));
10617             }
10618         }
10619         if (!group.closed) {
10620             group.next(element);
10621         }
10622     };
10623     GroupBySubscriber.prototype._error = function (err) {
10624         var groups = this.groups;
10625         if (groups) {
10626             groups.forEach(function (group, key) {
10627                 group.error(err);
10628             });
10629             groups.clear();
10630         }
10631         this.destination.error(err);
10632     };
10633     GroupBySubscriber.prototype._complete = function () {
10634         var groups = this.groups;
10635         if (groups) {
10636             groups.forEach(function (group, key) {
10637                 group.complete();
10638             });
10639             groups.clear();
10640         }
10641         this.destination.complete();
10642     };
10643     GroupBySubscriber.prototype.removeGroup = function (key) {
10644         this.groups.delete(key);
10645     };
10646     GroupBySubscriber.prototype.unsubscribe = function () {
10647         if (!this.closed) {
10648             this.attemptedToUnsubscribe = true;
10649             if (this.count === 0) {
10650                 _super.prototype.unsubscribe.call(this);
10651             }
10652         }
10653     };
10654     return GroupBySubscriber;
10655 }(Subscriber_1.Subscriber));
10656 var GroupDurationSubscriber = (function (_super) {
10657     __extends(GroupDurationSubscriber, _super);
10658     function GroupDurationSubscriber(key, group, parent) {
10659         var _this = _super.call(this, group) || this;
10660         _this.key = key;
10661         _this.group = group;
10662         _this.parent = parent;
10663         return _this;
10664     }
10665     GroupDurationSubscriber.prototype._next = function (value) {
10666         this.complete();
10667     };
10668     GroupDurationSubscriber.prototype._unsubscribe = function () {
10669         var _a = this, parent = _a.parent, key = _a.key;
10670         this.key = this.parent = null;
10671         if (parent) {
10672             parent.removeGroup(key);
10673         }
10674     };
10675     return GroupDurationSubscriber;
10676 }(Subscriber_1.Subscriber));
10677 var GroupedObservable = (function (_super) {
10678     __extends(GroupedObservable, _super);
10679     function GroupedObservable(key, groupSubject, refCountSubscription) {
10680         var _this = _super.call(this) || this;
10681         _this.key = key;
10682         _this.groupSubject = groupSubject;
10683         _this.refCountSubscription = refCountSubscription;
10684         return _this;
10685     }
10686     GroupedObservable.prototype._subscribe = function (subscriber) {
10687         var subscription = new Subscription_1.Subscription();
10688         var _a = this, refCountSubscription = _a.refCountSubscription, groupSubject = _a.groupSubject;
10689         if (refCountSubscription && !refCountSubscription.closed) {
10690             subscription.add(new InnerRefCountSubscription(refCountSubscription));
10691         }
10692         subscription.add(groupSubject.subscribe(subscriber));
10693         return subscription;
10694     };
10695     return GroupedObservable;
10696 }(Observable_1.Observable));
10697 exports.GroupedObservable = GroupedObservable;
10698 var InnerRefCountSubscription = (function (_super) {
10699     __extends(InnerRefCountSubscription, _super);
10700     function InnerRefCountSubscription(parent) {
10701         var _this = _super.call(this) || this;
10702         _this.parent = parent;
10703         parent.count++;
10704         return _this;
10705     }
10706     InnerRefCountSubscription.prototype.unsubscribe = function () {
10707         var parent = this.parent;
10708         if (!parent.closed && !this.closed) {
10709             _super.prototype.unsubscribe.call(this);
10710             parent.count -= 1;
10711             if (parent.count === 0 && parent.attemptedToUnsubscribe) {
10712                 parent.unsubscribe();
10713             }
10714         }
10715     };
10716     return InnerRefCountSubscription;
10717 }(Subscription_1.Subscription));
10718
10719 },{"../Observable":31,"../Subject":36,"../Subscriber":38,"../Subscription":39}],108:[function(require,module,exports){
10720 "use strict";
10721 var __extends = (this && this.__extends) || (function () {
10722     var extendStatics = function (d, b) {
10723         extendStatics = Object.setPrototypeOf ||
10724             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10725             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10726         return extendStatics(d, b);
10727     }
10728     return function (d, b) {
10729         extendStatics(d, b);
10730         function __() { this.constructor = d; }
10731         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10732     };
10733 })();
10734 Object.defineProperty(exports, "__esModule", { value: true });
10735 var Subscriber_1 = require("../Subscriber");
10736 function ignoreElements() {
10737     return function ignoreElementsOperatorFunction(source) {
10738         return source.lift(new IgnoreElementsOperator());
10739     };
10740 }
10741 exports.ignoreElements = ignoreElements;
10742 var IgnoreElementsOperator = (function () {
10743     function IgnoreElementsOperator() {
10744     }
10745     IgnoreElementsOperator.prototype.call = function (subscriber, source) {
10746         return source.subscribe(new IgnoreElementsSubscriber(subscriber));
10747     };
10748     return IgnoreElementsOperator;
10749 }());
10750 var IgnoreElementsSubscriber = (function (_super) {
10751     __extends(IgnoreElementsSubscriber, _super);
10752     function IgnoreElementsSubscriber() {
10753         return _super !== null && _super.apply(this, arguments) || this;
10754     }
10755     IgnoreElementsSubscriber.prototype._next = function (unused) {
10756     };
10757     return IgnoreElementsSubscriber;
10758 }(Subscriber_1.Subscriber));
10759
10760 },{"../Subscriber":38}],109:[function(require,module,exports){
10761 "use strict";
10762 var __extends = (this && this.__extends) || (function () {
10763     var extendStatics = function (d, b) {
10764         extendStatics = Object.setPrototypeOf ||
10765             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10766             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10767         return extendStatics(d, b);
10768     }
10769     return function (d, b) {
10770         extendStatics(d, b);
10771         function __() { this.constructor = d; }
10772         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10773     };
10774 })();
10775 Object.defineProperty(exports, "__esModule", { value: true });
10776 var Subscriber_1 = require("../Subscriber");
10777 function isEmpty() {
10778     return function (source) { return source.lift(new IsEmptyOperator()); };
10779 }
10780 exports.isEmpty = isEmpty;
10781 var IsEmptyOperator = (function () {
10782     function IsEmptyOperator() {
10783     }
10784     IsEmptyOperator.prototype.call = function (observer, source) {
10785         return source.subscribe(new IsEmptySubscriber(observer));
10786     };
10787     return IsEmptyOperator;
10788 }());
10789 var IsEmptySubscriber = (function (_super) {
10790     __extends(IsEmptySubscriber, _super);
10791     function IsEmptySubscriber(destination) {
10792         return _super.call(this, destination) || this;
10793     }
10794     IsEmptySubscriber.prototype.notifyComplete = function (isEmpty) {
10795         var destination = this.destination;
10796         destination.next(isEmpty);
10797         destination.complete();
10798     };
10799     IsEmptySubscriber.prototype._next = function (value) {
10800         this.notifyComplete(false);
10801     };
10802     IsEmptySubscriber.prototype._complete = function () {
10803         this.notifyComplete(true);
10804     };
10805     return IsEmptySubscriber;
10806 }(Subscriber_1.Subscriber));
10807
10808 },{"../Subscriber":38}],110:[function(require,module,exports){
10809 "use strict";
10810 Object.defineProperty(exports, "__esModule", { value: true });
10811 var EmptyError_1 = require("../util/EmptyError");
10812 var filter_1 = require("./filter");
10813 var takeLast_1 = require("./takeLast");
10814 var throwIfEmpty_1 = require("./throwIfEmpty");
10815 var defaultIfEmpty_1 = require("./defaultIfEmpty");
10816 var identity_1 = require("../util/identity");
10817 function last(predicate, defaultValue) {
10818     var hasDefaultValue = arguments.length >= 2;
10819     return function (source) { return source.pipe(predicate ? filter_1.filter(function (v, i) { return predicate(v, i, source); }) : identity_1.identity, takeLast_1.takeLast(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function () { return new EmptyError_1.EmptyError(); })); };
10820 }
10821 exports.last = last;
10822
10823 },{"../util/EmptyError":193,"../util/identity":201,"./defaultIfEmpty":89,"./filter":102,"./takeLast":155,"./throwIfEmpty":161}],111:[function(require,module,exports){
10824 "use strict";
10825 var __extends = (this && this.__extends) || (function () {
10826     var extendStatics = function (d, b) {
10827         extendStatics = Object.setPrototypeOf ||
10828             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10829             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10830         return extendStatics(d, b);
10831     }
10832     return function (d, b) {
10833         extendStatics(d, b);
10834         function __() { this.constructor = d; }
10835         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10836     };
10837 })();
10838 Object.defineProperty(exports, "__esModule", { value: true });
10839 var Subscriber_1 = require("../Subscriber");
10840 function map(project, thisArg) {
10841     return function mapOperation(source) {
10842         if (typeof project !== 'function') {
10843             throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
10844         }
10845         return source.lift(new MapOperator(project, thisArg));
10846     };
10847 }
10848 exports.map = map;
10849 var MapOperator = (function () {
10850     function MapOperator(project, thisArg) {
10851         this.project = project;
10852         this.thisArg = thisArg;
10853     }
10854     MapOperator.prototype.call = function (subscriber, source) {
10855         return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
10856     };
10857     return MapOperator;
10858 }());
10859 exports.MapOperator = MapOperator;
10860 var MapSubscriber = (function (_super) {
10861     __extends(MapSubscriber, _super);
10862     function MapSubscriber(destination, project, thisArg) {
10863         var _this = _super.call(this, destination) || this;
10864         _this.project = project;
10865         _this.count = 0;
10866         _this.thisArg = thisArg || _this;
10867         return _this;
10868     }
10869     MapSubscriber.prototype._next = function (value) {
10870         var result;
10871         try {
10872             result = this.project.call(this.thisArg, value, this.count++);
10873         }
10874         catch (err) {
10875             this.destination.error(err);
10876             return;
10877         }
10878         this.destination.next(result);
10879     };
10880     return MapSubscriber;
10881 }(Subscriber_1.Subscriber));
10882
10883 },{"../Subscriber":38}],112:[function(require,module,exports){
10884 "use strict";
10885 var __extends = (this && this.__extends) || (function () {
10886     var extendStatics = function (d, b) {
10887         extendStatics = Object.setPrototypeOf ||
10888             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10889             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10890         return extendStatics(d, b);
10891     }
10892     return function (d, b) {
10893         extendStatics(d, b);
10894         function __() { this.constructor = d; }
10895         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10896     };
10897 })();
10898 Object.defineProperty(exports, "__esModule", { value: true });
10899 var Subscriber_1 = require("../Subscriber");
10900 function mapTo(value) {
10901     return function (source) { return source.lift(new MapToOperator(value)); };
10902 }
10903 exports.mapTo = mapTo;
10904 var MapToOperator = (function () {
10905     function MapToOperator(value) {
10906         this.value = value;
10907     }
10908     MapToOperator.prototype.call = function (subscriber, source) {
10909         return source.subscribe(new MapToSubscriber(subscriber, this.value));
10910     };
10911     return MapToOperator;
10912 }());
10913 var MapToSubscriber = (function (_super) {
10914     __extends(MapToSubscriber, _super);
10915     function MapToSubscriber(destination, value) {
10916         var _this = _super.call(this, destination) || this;
10917         _this.value = value;
10918         return _this;
10919     }
10920     MapToSubscriber.prototype._next = function (x) {
10921         this.destination.next(this.value);
10922     };
10923     return MapToSubscriber;
10924 }(Subscriber_1.Subscriber));
10925
10926 },{"../Subscriber":38}],113:[function(require,module,exports){
10927 "use strict";
10928 var __extends = (this && this.__extends) || (function () {
10929     var extendStatics = function (d, b) {
10930         extendStatics = Object.setPrototypeOf ||
10931             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10932             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
10933         return extendStatics(d, b);
10934     }
10935     return function (d, b) {
10936         extendStatics(d, b);
10937         function __() { this.constructor = d; }
10938         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10939     };
10940 })();
10941 Object.defineProperty(exports, "__esModule", { value: true });
10942 var Subscriber_1 = require("../Subscriber");
10943 var Notification_1 = require("../Notification");
10944 function materialize() {
10945     return function materializeOperatorFunction(source) {
10946         return source.lift(new MaterializeOperator());
10947     };
10948 }
10949 exports.materialize = materialize;
10950 var MaterializeOperator = (function () {
10951     function MaterializeOperator() {
10952     }
10953     MaterializeOperator.prototype.call = function (subscriber, source) {
10954         return source.subscribe(new MaterializeSubscriber(subscriber));
10955     };
10956     return MaterializeOperator;
10957 }());
10958 var MaterializeSubscriber = (function (_super) {
10959     __extends(MaterializeSubscriber, _super);
10960     function MaterializeSubscriber(destination) {
10961         return _super.call(this, destination) || this;
10962     }
10963     MaterializeSubscriber.prototype._next = function (value) {
10964         this.destination.next(Notification_1.Notification.createNext(value));
10965     };
10966     MaterializeSubscriber.prototype._error = function (err) {
10967         var destination = this.destination;
10968         destination.next(Notification_1.Notification.createError(err));
10969         destination.complete();
10970     };
10971     MaterializeSubscriber.prototype._complete = function () {
10972         var destination = this.destination;
10973         destination.next(Notification_1.Notification.createComplete());
10974         destination.complete();
10975     };
10976     return MaterializeSubscriber;
10977 }(Subscriber_1.Subscriber));
10978
10979 },{"../Notification":30,"../Subscriber":38}],114:[function(require,module,exports){
10980 "use strict";
10981 Object.defineProperty(exports, "__esModule", { value: true });
10982 var reduce_1 = require("./reduce");
10983 function max(comparer) {
10984     var max = (typeof comparer === 'function')
10985         ? function (x, y) { return comparer(x, y) > 0 ? x : y; }
10986         : function (x, y) { return x > y ? x : y; };
10987     return reduce_1.reduce(max);
10988 }
10989 exports.max = max;
10990
10991 },{"./reduce":132}],115:[function(require,module,exports){
10992 "use strict";
10993 Object.defineProperty(exports, "__esModule", { value: true });
10994 var merge_1 = require("../observable/merge");
10995 function merge() {
10996     var observables = [];
10997     for (var _i = 0; _i < arguments.length; _i++) {
10998         observables[_i] = arguments[_i];
10999     }
11000     return function (source) { return source.lift.call(merge_1.merge.apply(void 0, [source].concat(observables))); };
11001 }
11002 exports.merge = merge;
11003
11004 },{"../observable/merge":60}],116:[function(require,module,exports){
11005 "use strict";
11006 Object.defineProperty(exports, "__esModule", { value: true });
11007 var mergeMap_1 = require("./mergeMap");
11008 var identity_1 = require("../util/identity");
11009 function mergeAll(concurrent) {
11010     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
11011     return mergeMap_1.mergeMap(identity_1.identity, concurrent);
11012 }
11013 exports.mergeAll = mergeAll;
11014
11015 },{"../util/identity":201,"./mergeMap":117}],117:[function(require,module,exports){
11016 "use strict";
11017 var __extends = (this && this.__extends) || (function () {
11018     var extendStatics = function (d, b) {
11019         extendStatics = Object.setPrototypeOf ||
11020             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11021             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11022         return extendStatics(d, b);
11023     }
11024     return function (d, b) {
11025         extendStatics(d, b);
11026         function __() { this.constructor = d; }
11027         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11028     };
11029 })();
11030 Object.defineProperty(exports, "__esModule", { value: true });
11031 var subscribeToResult_1 = require("../util/subscribeToResult");
11032 var OuterSubscriber_1 = require("../OuterSubscriber");
11033 var InnerSubscriber_1 = require("../InnerSubscriber");
11034 var map_1 = require("./map");
11035 var from_1 = require("../observable/from");
11036 function mergeMap(project, resultSelector, concurrent) {
11037     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
11038     if (typeof resultSelector === 'function') {
11039         return function (source) { return source.pipe(mergeMap(function (a, i) { return from_1.from(project(a, i)).pipe(map_1.map(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); };
11040     }
11041     else if (typeof resultSelector === 'number') {
11042         concurrent = resultSelector;
11043     }
11044     return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); };
11045 }
11046 exports.mergeMap = mergeMap;
11047 var MergeMapOperator = (function () {
11048     function MergeMapOperator(project, concurrent) {
11049         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
11050         this.project = project;
11051         this.concurrent = concurrent;
11052     }
11053     MergeMapOperator.prototype.call = function (observer, source) {
11054         return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));
11055     };
11056     return MergeMapOperator;
11057 }());
11058 exports.MergeMapOperator = MergeMapOperator;
11059 var MergeMapSubscriber = (function (_super) {
11060     __extends(MergeMapSubscriber, _super);
11061     function MergeMapSubscriber(destination, project, concurrent) {
11062         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
11063         var _this = _super.call(this, destination) || this;
11064         _this.project = project;
11065         _this.concurrent = concurrent;
11066         _this.hasCompleted = false;
11067         _this.buffer = [];
11068         _this.active = 0;
11069         _this.index = 0;
11070         return _this;
11071     }
11072     MergeMapSubscriber.prototype._next = function (value) {
11073         if (this.active < this.concurrent) {
11074             this._tryNext(value);
11075         }
11076         else {
11077             this.buffer.push(value);
11078         }
11079     };
11080     MergeMapSubscriber.prototype._tryNext = function (value) {
11081         var result;
11082         var index = this.index++;
11083         try {
11084             result = this.project(value, index);
11085         }
11086         catch (err) {
11087             this.destination.error(err);
11088             return;
11089         }
11090         this.active++;
11091         this._innerSub(result, value, index);
11092     };
11093     MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
11094         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
11095         var destination = this.destination;
11096         destination.add(innerSubscriber);
11097         subscribeToResult_1.subscribeToResult(this, ish, value, index, innerSubscriber);
11098     };
11099     MergeMapSubscriber.prototype._complete = function () {
11100         this.hasCompleted = true;
11101         if (this.active === 0 && this.buffer.length === 0) {
11102             this.destination.complete();
11103         }
11104         this.unsubscribe();
11105     };
11106     MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11107         this.destination.next(innerValue);
11108     };
11109     MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
11110         var buffer = this.buffer;
11111         this.remove(innerSub);
11112         this.active--;
11113         if (buffer.length > 0) {
11114             this._next(buffer.shift());
11115         }
11116         else if (this.active === 0 && this.hasCompleted) {
11117             this.destination.complete();
11118         }
11119     };
11120     return MergeMapSubscriber;
11121 }(OuterSubscriber_1.OuterSubscriber));
11122 exports.MergeMapSubscriber = MergeMapSubscriber;
11123
11124 },{"../InnerSubscriber":29,"../OuterSubscriber":33,"../observable/from":50,"../util/subscribeToResult":221,"./map":111}],118:[function(require,module,exports){
11125 "use strict";
11126 Object.defineProperty(exports, "__esModule", { value: true });
11127 var mergeMap_1 = require("./mergeMap");
11128 function mergeMapTo(innerObservable, resultSelector, concurrent) {
11129     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
11130     if (typeof resultSelector === 'function') {
11131         return mergeMap_1.mergeMap(function () { return innerObservable; }, resultSelector, concurrent);
11132     }
11133     if (typeof resultSelector === 'number') {
11134         concurrent = resultSelector;
11135     }
11136     return mergeMap_1.mergeMap(function () { return innerObservable; }, concurrent);
11137 }
11138 exports.mergeMapTo = mergeMapTo;
11139
11140 },{"./mergeMap":117}],119:[function(require,module,exports){
11141 "use strict";
11142 var __extends = (this && this.__extends) || (function () {
11143     var extendStatics = function (d, b) {
11144         extendStatics = Object.setPrototypeOf ||
11145             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11146             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11147         return extendStatics(d, b);
11148     }
11149     return function (d, b) {
11150         extendStatics(d, b);
11151         function __() { this.constructor = d; }
11152         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11153     };
11154 })();
11155 Object.defineProperty(exports, "__esModule", { value: true });
11156 var tryCatch_1 = require("../util/tryCatch");
11157 var errorObject_1 = require("../util/errorObject");
11158 var subscribeToResult_1 = require("../util/subscribeToResult");
11159 var OuterSubscriber_1 = require("../OuterSubscriber");
11160 var InnerSubscriber_1 = require("../InnerSubscriber");
11161 function mergeScan(accumulator, seed, concurrent) {
11162     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
11163     return function (source) { return source.lift(new MergeScanOperator(accumulator, seed, concurrent)); };
11164 }
11165 exports.mergeScan = mergeScan;
11166 var MergeScanOperator = (function () {
11167     function MergeScanOperator(accumulator, seed, concurrent) {
11168         this.accumulator = accumulator;
11169         this.seed = seed;
11170         this.concurrent = concurrent;
11171     }
11172     MergeScanOperator.prototype.call = function (subscriber, source) {
11173         return source.subscribe(new MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent));
11174     };
11175     return MergeScanOperator;
11176 }());
11177 exports.MergeScanOperator = MergeScanOperator;
11178 var MergeScanSubscriber = (function (_super) {
11179     __extends(MergeScanSubscriber, _super);
11180     function MergeScanSubscriber(destination, accumulator, acc, concurrent) {
11181         var _this = _super.call(this, destination) || this;
11182         _this.accumulator = accumulator;
11183         _this.acc = acc;
11184         _this.concurrent = concurrent;
11185         _this.hasValue = false;
11186         _this.hasCompleted = false;
11187         _this.buffer = [];
11188         _this.active = 0;
11189         _this.index = 0;
11190         return _this;
11191     }
11192     MergeScanSubscriber.prototype._next = function (value) {
11193         if (this.active < this.concurrent) {
11194             var index = this.index++;
11195             var ish = tryCatch_1.tryCatch(this.accumulator)(this.acc, value);
11196             var destination = this.destination;
11197             if (ish === errorObject_1.errorObject) {
11198                 destination.error(errorObject_1.errorObject.e);
11199             }
11200             else {
11201                 this.active++;
11202                 this._innerSub(ish, value, index);
11203             }
11204         }
11205         else {
11206             this.buffer.push(value);
11207         }
11208     };
11209     MergeScanSubscriber.prototype._innerSub = function (ish, value, index) {
11210         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
11211         var destination = this.destination;
11212         destination.add(innerSubscriber);
11213         subscribeToResult_1.subscribeToResult(this, ish, value, index, innerSubscriber);
11214     };
11215     MergeScanSubscriber.prototype._complete = function () {
11216         this.hasCompleted = true;
11217         if (this.active === 0 && this.buffer.length === 0) {
11218             if (this.hasValue === false) {
11219                 this.destination.next(this.acc);
11220             }
11221             this.destination.complete();
11222         }
11223         this.unsubscribe();
11224     };
11225     MergeScanSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11226         var destination = this.destination;
11227         this.acc = innerValue;
11228         this.hasValue = true;
11229         destination.next(innerValue);
11230     };
11231     MergeScanSubscriber.prototype.notifyComplete = function (innerSub) {
11232         var buffer = this.buffer;
11233         var destination = this.destination;
11234         destination.remove(innerSub);
11235         this.active--;
11236         if (buffer.length > 0) {
11237             this._next(buffer.shift());
11238         }
11239         else if (this.active === 0 && this.hasCompleted) {
11240             if (this.hasValue === false) {
11241                 this.destination.next(this.acc);
11242             }
11243             this.destination.complete();
11244         }
11245     };
11246     return MergeScanSubscriber;
11247 }(OuterSubscriber_1.OuterSubscriber));
11248 exports.MergeScanSubscriber = MergeScanSubscriber;
11249
11250 },{"../InnerSubscriber":29,"../OuterSubscriber":33,"../util/errorObject":199,"../util/subscribeToResult":221,"../util/tryCatch":223}],120:[function(require,module,exports){
11251 "use strict";
11252 Object.defineProperty(exports, "__esModule", { value: true });
11253 var reduce_1 = require("./reduce");
11254 function min(comparer) {
11255     var min = (typeof comparer === 'function')
11256         ? function (x, y) { return comparer(x, y) < 0 ? x : y; }
11257         : function (x, y) { return x < y ? x : y; };
11258     return reduce_1.reduce(min);
11259 }
11260 exports.min = min;
11261
11262 },{"./reduce":132}],121:[function(require,module,exports){
11263 "use strict";
11264 Object.defineProperty(exports, "__esModule", { value: true });
11265 var ConnectableObservable_1 = require("../observable/ConnectableObservable");
11266 function multicast(subjectOrSubjectFactory, selector) {
11267     return function multicastOperatorFunction(source) {
11268         var subjectFactory;
11269         if (typeof subjectOrSubjectFactory === 'function') {
11270             subjectFactory = subjectOrSubjectFactory;
11271         }
11272         else {
11273             subjectFactory = function subjectFactory() {
11274                 return subjectOrSubjectFactory;
11275             };
11276         }
11277         if (typeof selector === 'function') {
11278             return source.lift(new MulticastOperator(subjectFactory, selector));
11279         }
11280         var connectable = Object.create(source, ConnectableObservable_1.connectableObservableDescriptor);
11281         connectable.source = source;
11282         connectable.subjectFactory = subjectFactory;
11283         return connectable;
11284     };
11285 }
11286 exports.multicast = multicast;
11287 var MulticastOperator = (function () {
11288     function MulticastOperator(subjectFactory, selector) {
11289         this.subjectFactory = subjectFactory;
11290         this.selector = selector;
11291     }
11292     MulticastOperator.prototype.call = function (subscriber, source) {
11293         var selector = this.selector;
11294         var subject = this.subjectFactory();
11295         var subscription = selector(subject).subscribe(subscriber);
11296         subscription.add(source.subscribe(subject));
11297         return subscription;
11298     };
11299     return MulticastOperator;
11300 }());
11301 exports.MulticastOperator = MulticastOperator;
11302
11303 },{"../observable/ConnectableObservable":41}],122:[function(require,module,exports){
11304 "use strict";
11305 var __extends = (this && this.__extends) || (function () {
11306     var extendStatics = function (d, b) {
11307         extendStatics = Object.setPrototypeOf ||
11308             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11309             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11310         return extendStatics(d, b);
11311     }
11312     return function (d, b) {
11313         extendStatics(d, b);
11314         function __() { this.constructor = d; }
11315         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11316     };
11317 })();
11318 Object.defineProperty(exports, "__esModule", { value: true });
11319 var Subscriber_1 = require("../Subscriber");
11320 var Notification_1 = require("../Notification");
11321 function observeOn(scheduler, delay) {
11322     if (delay === void 0) { delay = 0; }
11323     return function observeOnOperatorFunction(source) {
11324         return source.lift(new ObserveOnOperator(scheduler, delay));
11325     };
11326 }
11327 exports.observeOn = observeOn;
11328 var ObserveOnOperator = (function () {
11329     function ObserveOnOperator(scheduler, delay) {
11330         if (delay === void 0) { delay = 0; }
11331         this.scheduler = scheduler;
11332         this.delay = delay;
11333     }
11334     ObserveOnOperator.prototype.call = function (subscriber, source) {
11335         return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
11336     };
11337     return ObserveOnOperator;
11338 }());
11339 exports.ObserveOnOperator = ObserveOnOperator;
11340 var ObserveOnSubscriber = (function (_super) {
11341     __extends(ObserveOnSubscriber, _super);
11342     function ObserveOnSubscriber(destination, scheduler, delay) {
11343         if (delay === void 0) { delay = 0; }
11344         var _this = _super.call(this, destination) || this;
11345         _this.scheduler = scheduler;
11346         _this.delay = delay;
11347         return _this;
11348     }
11349     ObserveOnSubscriber.dispatch = function (arg) {
11350         var notification = arg.notification, destination = arg.destination;
11351         notification.observe(destination);
11352         this.unsubscribe();
11353     };
11354     ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
11355         var destination = this.destination;
11356         destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
11357     };
11358     ObserveOnSubscriber.prototype._next = function (value) {
11359         this.scheduleMessage(Notification_1.Notification.createNext(value));
11360     };
11361     ObserveOnSubscriber.prototype._error = function (err) {
11362         this.scheduleMessage(Notification_1.Notification.createError(err));
11363         this.unsubscribe();
11364     };
11365     ObserveOnSubscriber.prototype._complete = function () {
11366         this.scheduleMessage(Notification_1.Notification.createComplete());
11367         this.unsubscribe();
11368     };
11369     return ObserveOnSubscriber;
11370 }(Subscriber_1.Subscriber));
11371 exports.ObserveOnSubscriber = ObserveOnSubscriber;
11372 var ObserveOnMessage = (function () {
11373     function ObserveOnMessage(notification, destination) {
11374         this.notification = notification;
11375         this.destination = destination;
11376     }
11377     return ObserveOnMessage;
11378 }());
11379 exports.ObserveOnMessage = ObserveOnMessage;
11380
11381 },{"../Notification":30,"../Subscriber":38}],123:[function(require,module,exports){
11382 "use strict";
11383 var __extends = (this && this.__extends) || (function () {
11384     var extendStatics = function (d, b) {
11385         extendStatics = Object.setPrototypeOf ||
11386             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11387             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11388         return extendStatics(d, b);
11389     }
11390     return function (d, b) {
11391         extendStatics(d, b);
11392         function __() { this.constructor = d; }
11393         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11394     };
11395 })();
11396 Object.defineProperty(exports, "__esModule", { value: true });
11397 var from_1 = require("../observable/from");
11398 var isArray_1 = require("../util/isArray");
11399 var OuterSubscriber_1 = require("../OuterSubscriber");
11400 var InnerSubscriber_1 = require("../InnerSubscriber");
11401 var subscribeToResult_1 = require("../util/subscribeToResult");
11402 function onErrorResumeNext() {
11403     var nextSources = [];
11404     for (var _i = 0; _i < arguments.length; _i++) {
11405         nextSources[_i] = arguments[_i];
11406     }
11407     if (nextSources.length === 1 && isArray_1.isArray(nextSources[0])) {
11408         nextSources = nextSources[0];
11409     }
11410     return function (source) { return source.lift(new OnErrorResumeNextOperator(nextSources)); };
11411 }
11412 exports.onErrorResumeNext = onErrorResumeNext;
11413 function onErrorResumeNextStatic() {
11414     var nextSources = [];
11415     for (var _i = 0; _i < arguments.length; _i++) {
11416         nextSources[_i] = arguments[_i];
11417     }
11418     var source = null;
11419     if (nextSources.length === 1 && isArray_1.isArray(nextSources[0])) {
11420         nextSources = nextSources[0];
11421     }
11422     source = nextSources.shift();
11423     return from_1.from(source, null).lift(new OnErrorResumeNextOperator(nextSources));
11424 }
11425 exports.onErrorResumeNextStatic = onErrorResumeNextStatic;
11426 var OnErrorResumeNextOperator = (function () {
11427     function OnErrorResumeNextOperator(nextSources) {
11428         this.nextSources = nextSources;
11429     }
11430     OnErrorResumeNextOperator.prototype.call = function (subscriber, source) {
11431         return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources));
11432     };
11433     return OnErrorResumeNextOperator;
11434 }());
11435 var OnErrorResumeNextSubscriber = (function (_super) {
11436     __extends(OnErrorResumeNextSubscriber, _super);
11437     function OnErrorResumeNextSubscriber(destination, nextSources) {
11438         var _this = _super.call(this, destination) || this;
11439         _this.destination = destination;
11440         _this.nextSources = nextSources;
11441         return _this;
11442     }
11443     OnErrorResumeNextSubscriber.prototype.notifyError = function (error, innerSub) {
11444         this.subscribeToNextSource();
11445     };
11446     OnErrorResumeNextSubscriber.prototype.notifyComplete = function (innerSub) {
11447         this.subscribeToNextSource();
11448     };
11449     OnErrorResumeNextSubscriber.prototype._error = function (err) {
11450         this.subscribeToNextSource();
11451         this.unsubscribe();
11452     };
11453     OnErrorResumeNextSubscriber.prototype._complete = function () {
11454         this.subscribeToNextSource();
11455         this.unsubscribe();
11456     };
11457     OnErrorResumeNextSubscriber.prototype.subscribeToNextSource = function () {
11458         var next = this.nextSources.shift();
11459         if (next) {
11460             var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
11461             var destination = this.destination;
11462             destination.add(innerSubscriber);
11463             subscribeToResult_1.subscribeToResult(this, next, undefined, undefined, innerSubscriber);
11464         }
11465         else {
11466             this.destination.complete();
11467         }
11468     };
11469     return OnErrorResumeNextSubscriber;
11470 }(OuterSubscriber_1.OuterSubscriber));
11471
11472 },{"../InnerSubscriber":29,"../OuterSubscriber":33,"../observable/from":50,"../util/isArray":202,"../util/subscribeToResult":221}],124:[function(require,module,exports){
11473 "use strict";
11474 var __extends = (this && this.__extends) || (function () {
11475     var extendStatics = function (d, b) {
11476         extendStatics = Object.setPrototypeOf ||
11477             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11478             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11479         return extendStatics(d, b);
11480     }
11481     return function (d, b) {
11482         extendStatics(d, b);
11483         function __() { this.constructor = d; }
11484         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11485     };
11486 })();
11487 Object.defineProperty(exports, "__esModule", { value: true });
11488 var Subscriber_1 = require("../Subscriber");
11489 function pairwise() {
11490     return function (source) { return source.lift(new PairwiseOperator()); };
11491 }
11492 exports.pairwise = pairwise;
11493 var PairwiseOperator = (function () {
11494     function PairwiseOperator() {
11495     }
11496     PairwiseOperator.prototype.call = function (subscriber, source) {
11497         return source.subscribe(new PairwiseSubscriber(subscriber));
11498     };
11499     return PairwiseOperator;
11500 }());
11501 var PairwiseSubscriber = (function (_super) {
11502     __extends(PairwiseSubscriber, _super);
11503     function PairwiseSubscriber(destination) {
11504         var _this = _super.call(this, destination) || this;
11505         _this.hasPrev = false;
11506         return _this;
11507     }
11508     PairwiseSubscriber.prototype._next = function (value) {
11509         if (this.hasPrev) {
11510             this.destination.next([this.prev, value]);
11511         }
11512         else {
11513             this.hasPrev = true;
11514         }
11515         this.prev = value;
11516     };
11517     return PairwiseSubscriber;
11518 }(Subscriber_1.Subscriber));
11519
11520 },{"../Subscriber":38}],125:[function(require,module,exports){
11521 "use strict";
11522 Object.defineProperty(exports, "__esModule", { value: true });
11523 var not_1 = require("../util/not");
11524 var filter_1 = require("./filter");
11525 function partition(predicate, thisArg) {
11526     return function (source) { return [
11527         filter_1.filter(predicate, thisArg)(source),
11528         filter_1.filter(not_1.not(predicate, thisArg))(source)
11529     ]; };
11530 }
11531 exports.partition = partition;
11532
11533 },{"../util/not":214,"./filter":102}],126:[function(require,module,exports){
11534 "use strict";
11535 Object.defineProperty(exports, "__esModule", { value: true });
11536 var map_1 = require("./map");
11537 function pluck() {
11538     var properties = [];
11539     for (var _i = 0; _i < arguments.length; _i++) {
11540         properties[_i] = arguments[_i];
11541     }
11542     var length = properties.length;
11543     if (length === 0) {
11544         throw new Error('list of properties cannot be empty.');
11545     }
11546     return function (source) { return map_1.map(plucker(properties, length))(source); };
11547 }
11548 exports.pluck = pluck;
11549 function plucker(props, length) {
11550     var mapper = function (x) {
11551         var currentProp = x;
11552         for (var i = 0; i < length; i++) {
11553             var p = currentProp[props[i]];
11554             if (typeof p !== 'undefined') {
11555                 currentProp = p;
11556             }
11557             else {
11558                 return undefined;
11559             }
11560         }
11561         return currentProp;
11562     };
11563     return mapper;
11564 }
11565
11566 },{"./map":111}],127:[function(require,module,exports){
11567 "use strict";
11568 Object.defineProperty(exports, "__esModule", { value: true });
11569 var Subject_1 = require("../Subject");
11570 var multicast_1 = require("./multicast");
11571 function publish(selector) {
11572     return selector ?
11573         multicast_1.multicast(function () { return new Subject_1.Subject(); }, selector) :
11574         multicast_1.multicast(new Subject_1.Subject());
11575 }
11576 exports.publish = publish;
11577
11578 },{"../Subject":36,"./multicast":121}],128:[function(require,module,exports){
11579 "use strict";
11580 Object.defineProperty(exports, "__esModule", { value: true });
11581 var BehaviorSubject_1 = require("../BehaviorSubject");
11582 var multicast_1 = require("./multicast");
11583 function publishBehavior(value) {
11584     return function (source) { return multicast_1.multicast(new BehaviorSubject_1.BehaviorSubject(value))(source); };
11585 }
11586 exports.publishBehavior = publishBehavior;
11587
11588 },{"../BehaviorSubject":28,"./multicast":121}],129:[function(require,module,exports){
11589 "use strict";
11590 Object.defineProperty(exports, "__esModule", { value: true });
11591 var AsyncSubject_1 = require("../AsyncSubject");
11592 var multicast_1 = require("./multicast");
11593 function publishLast() {
11594     return function (source) { return multicast_1.multicast(new AsyncSubject_1.AsyncSubject())(source); };
11595 }
11596 exports.publishLast = publishLast;
11597
11598 },{"../AsyncSubject":27,"./multicast":121}],130:[function(require,module,exports){
11599 "use strict";
11600 Object.defineProperty(exports, "__esModule", { value: true });
11601 var ReplaySubject_1 = require("../ReplaySubject");
11602 var multicast_1 = require("./multicast");
11603 function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
11604     if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {
11605         scheduler = selectorOrScheduler;
11606     }
11607     var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;
11608     var subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler);
11609     return function (source) { return multicast_1.multicast(function () { return subject; }, selector)(source); };
11610 }
11611 exports.publishReplay = publishReplay;
11612
11613 },{"../ReplaySubject":34,"./multicast":121}],131:[function(require,module,exports){
11614 "use strict";
11615 Object.defineProperty(exports, "__esModule", { value: true });
11616 var isArray_1 = require("../util/isArray");
11617 var race_1 = require("../observable/race");
11618 function race() {
11619     var observables = [];
11620     for (var _i = 0; _i < arguments.length; _i++) {
11621         observables[_i] = arguments[_i];
11622     }
11623     return function raceOperatorFunction(source) {
11624         if (observables.length === 1 && isArray_1.isArray(observables[0])) {
11625             observables = observables[0];
11626         }
11627         return source.lift.call(race_1.race.apply(void 0, [source].concat(observables)));
11628     };
11629 }
11630 exports.race = race;
11631
11632 },{"../observable/race":65,"../util/isArray":202}],132:[function(require,module,exports){
11633 "use strict";
11634 Object.defineProperty(exports, "__esModule", { value: true });
11635 var scan_1 = require("./scan");
11636 var takeLast_1 = require("./takeLast");
11637 var defaultIfEmpty_1 = require("./defaultIfEmpty");
11638 var pipe_1 = require("../util/pipe");
11639 function reduce(accumulator, seed) {
11640     if (arguments.length >= 2) {
11641         return function reduceOperatorFunctionWithSeed(source) {
11642             return pipe_1.pipe(scan_1.scan(accumulator, seed), takeLast_1.takeLast(1), defaultIfEmpty_1.defaultIfEmpty(seed))(source);
11643         };
11644     }
11645     return function reduceOperatorFunction(source) {
11646         return pipe_1.pipe(scan_1.scan(function (acc, value, index) { return accumulator(acc, value, index + 1); }), takeLast_1.takeLast(1))(source);
11647     };
11648 }
11649 exports.reduce = reduce;
11650
11651 },{"../util/pipe":215,"./defaultIfEmpty":89,"./scan":140,"./takeLast":155}],133:[function(require,module,exports){
11652 "use strict";
11653 var __extends = (this && this.__extends) || (function () {
11654     var extendStatics = function (d, b) {
11655         extendStatics = Object.setPrototypeOf ||
11656             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11657             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11658         return extendStatics(d, b);
11659     }
11660     return function (d, b) {
11661         extendStatics(d, b);
11662         function __() { this.constructor = d; }
11663         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11664     };
11665 })();
11666 Object.defineProperty(exports, "__esModule", { value: true });
11667 var Subscriber_1 = require("../Subscriber");
11668 function refCount() {
11669     return function refCountOperatorFunction(source) {
11670         return source.lift(new RefCountOperator(source));
11671     };
11672 }
11673 exports.refCount = refCount;
11674 var RefCountOperator = (function () {
11675     function RefCountOperator(connectable) {
11676         this.connectable = connectable;
11677     }
11678     RefCountOperator.prototype.call = function (subscriber, source) {
11679         var connectable = this.connectable;
11680         connectable._refCount++;
11681         var refCounter = new RefCountSubscriber(subscriber, connectable);
11682         var subscription = source.subscribe(refCounter);
11683         if (!refCounter.closed) {
11684             refCounter.connection = connectable.connect();
11685         }
11686         return subscription;
11687     };
11688     return RefCountOperator;
11689 }());
11690 var RefCountSubscriber = (function (_super) {
11691     __extends(RefCountSubscriber, _super);
11692     function RefCountSubscriber(destination, connectable) {
11693         var _this = _super.call(this, destination) || this;
11694         _this.connectable = connectable;
11695         return _this;
11696     }
11697     RefCountSubscriber.prototype._unsubscribe = function () {
11698         var connectable = this.connectable;
11699         if (!connectable) {
11700             this.connection = null;
11701             return;
11702         }
11703         this.connectable = null;
11704         var refCount = connectable._refCount;
11705         if (refCount <= 0) {
11706             this.connection = null;
11707             return;
11708         }
11709         connectable._refCount = refCount - 1;
11710         if (refCount > 1) {
11711             this.connection = null;
11712             return;
11713         }
11714         var connection = this.connection;
11715         var sharedConnection = connectable._connection;
11716         this.connection = null;
11717         if (sharedConnection && (!connection || sharedConnection === connection)) {
11718             sharedConnection.unsubscribe();
11719         }
11720     };
11721     return RefCountSubscriber;
11722 }(Subscriber_1.Subscriber));
11723
11724 },{"../Subscriber":38}],134:[function(require,module,exports){
11725 "use strict";
11726 var __extends = (this && this.__extends) || (function () {
11727     var extendStatics = function (d, b) {
11728         extendStatics = Object.setPrototypeOf ||
11729             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11730             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11731         return extendStatics(d, b);
11732     }
11733     return function (d, b) {
11734         extendStatics(d, b);
11735         function __() { this.constructor = d; }
11736         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11737     };
11738 })();
11739 Object.defineProperty(exports, "__esModule", { value: true });
11740 var Subscriber_1 = require("../Subscriber");
11741 var empty_1 = require("../observable/empty");
11742 function repeat(count) {
11743     if (count === void 0) { count = -1; }
11744     return function (source) {
11745         if (count === 0) {
11746             return empty_1.empty();
11747         }
11748         else if (count < 0) {
11749             return source.lift(new RepeatOperator(-1, source));
11750         }
11751         else {
11752             return source.lift(new RepeatOperator(count - 1, source));
11753         }
11754     };
11755 }
11756 exports.repeat = repeat;
11757 var RepeatOperator = (function () {
11758     function RepeatOperator(count, source) {
11759         this.count = count;
11760         this.source = source;
11761     }
11762     RepeatOperator.prototype.call = function (subscriber, source) {
11763         return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source));
11764     };
11765     return RepeatOperator;
11766 }());
11767 var RepeatSubscriber = (function (_super) {
11768     __extends(RepeatSubscriber, _super);
11769     function RepeatSubscriber(destination, count, source) {
11770         var _this = _super.call(this, destination) || this;
11771         _this.count = count;
11772         _this.source = source;
11773         return _this;
11774     }
11775     RepeatSubscriber.prototype.complete = function () {
11776         if (!this.isStopped) {
11777             var _a = this, source = _a.source, count = _a.count;
11778             if (count === 0) {
11779                 return _super.prototype.complete.call(this);
11780             }
11781             else if (count > -1) {
11782                 this.count = count - 1;
11783             }
11784             source.subscribe(this._unsubscribeAndRecycle());
11785         }
11786     };
11787     return RepeatSubscriber;
11788 }(Subscriber_1.Subscriber));
11789
11790 },{"../Subscriber":38,"../observable/empty":48}],135:[function(require,module,exports){
11791 "use strict";
11792 var __extends = (this && this.__extends) || (function () {
11793     var extendStatics = function (d, b) {
11794         extendStatics = Object.setPrototypeOf ||
11795             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11796             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11797         return extendStatics(d, b);
11798     }
11799     return function (d, b) {
11800         extendStatics(d, b);
11801         function __() { this.constructor = d; }
11802         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11803     };
11804 })();
11805 Object.defineProperty(exports, "__esModule", { value: true });
11806 var Subject_1 = require("../Subject");
11807 var tryCatch_1 = require("../util/tryCatch");
11808 var errorObject_1 = require("../util/errorObject");
11809 var OuterSubscriber_1 = require("../OuterSubscriber");
11810 var subscribeToResult_1 = require("../util/subscribeToResult");
11811 function repeatWhen(notifier) {
11812     return function (source) { return source.lift(new RepeatWhenOperator(notifier)); };
11813 }
11814 exports.repeatWhen = repeatWhen;
11815 var RepeatWhenOperator = (function () {
11816     function RepeatWhenOperator(notifier) {
11817         this.notifier = notifier;
11818     }
11819     RepeatWhenOperator.prototype.call = function (subscriber, source) {
11820         return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source));
11821     };
11822     return RepeatWhenOperator;
11823 }());
11824 var RepeatWhenSubscriber = (function (_super) {
11825     __extends(RepeatWhenSubscriber, _super);
11826     function RepeatWhenSubscriber(destination, notifier, source) {
11827         var _this = _super.call(this, destination) || this;
11828         _this.notifier = notifier;
11829         _this.source = source;
11830         _this.sourceIsBeingSubscribedTo = true;
11831         return _this;
11832     }
11833     RepeatWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11834         this.sourceIsBeingSubscribedTo = true;
11835         this.source.subscribe(this);
11836     };
11837     RepeatWhenSubscriber.prototype.notifyComplete = function (innerSub) {
11838         if (this.sourceIsBeingSubscribedTo === false) {
11839             return _super.prototype.complete.call(this);
11840         }
11841     };
11842     RepeatWhenSubscriber.prototype.complete = function () {
11843         this.sourceIsBeingSubscribedTo = false;
11844         if (!this.isStopped) {
11845             if (!this.retries) {
11846                 this.subscribeToRetries();
11847             }
11848             if (!this.retriesSubscription || this.retriesSubscription.closed) {
11849                 return _super.prototype.complete.call(this);
11850             }
11851             this._unsubscribeAndRecycle();
11852             this.notifications.next();
11853         }
11854     };
11855     RepeatWhenSubscriber.prototype._unsubscribe = function () {
11856         var _a = this, notifications = _a.notifications, retriesSubscription = _a.retriesSubscription;
11857         if (notifications) {
11858             notifications.unsubscribe();
11859             this.notifications = null;
11860         }
11861         if (retriesSubscription) {
11862             retriesSubscription.unsubscribe();
11863             this.retriesSubscription = null;
11864         }
11865         this.retries = null;
11866     };
11867     RepeatWhenSubscriber.prototype._unsubscribeAndRecycle = function () {
11868         var _unsubscribe = this._unsubscribe;
11869         this._unsubscribe = null;
11870         _super.prototype._unsubscribeAndRecycle.call(this);
11871         this._unsubscribe = _unsubscribe;
11872         return this;
11873     };
11874     RepeatWhenSubscriber.prototype.subscribeToRetries = function () {
11875         this.notifications = new Subject_1.Subject();
11876         var retries = tryCatch_1.tryCatch(this.notifier)(this.notifications);
11877         if (retries === errorObject_1.errorObject) {
11878             return _super.prototype.complete.call(this);
11879         }
11880         this.retries = retries;
11881         this.retriesSubscription = subscribeToResult_1.subscribeToResult(this, retries);
11882     };
11883     return RepeatWhenSubscriber;
11884 }(OuterSubscriber_1.OuterSubscriber));
11885
11886 },{"../OuterSubscriber":33,"../Subject":36,"../util/errorObject":199,"../util/subscribeToResult":221,"../util/tryCatch":223}],136:[function(require,module,exports){
11887 "use strict";
11888 var __extends = (this && this.__extends) || (function () {
11889     var extendStatics = function (d, b) {
11890         extendStatics = Object.setPrototypeOf ||
11891             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11892             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11893         return extendStatics(d, b);
11894     }
11895     return function (d, b) {
11896         extendStatics(d, b);
11897         function __() { this.constructor = d; }
11898         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11899     };
11900 })();
11901 Object.defineProperty(exports, "__esModule", { value: true });
11902 var Subscriber_1 = require("../Subscriber");
11903 function retry(count) {
11904     if (count === void 0) { count = -1; }
11905     return function (source) { return source.lift(new RetryOperator(count, source)); };
11906 }
11907 exports.retry = retry;
11908 var RetryOperator = (function () {
11909     function RetryOperator(count, source) {
11910         this.count = count;
11911         this.source = source;
11912     }
11913     RetryOperator.prototype.call = function (subscriber, source) {
11914         return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
11915     };
11916     return RetryOperator;
11917 }());
11918 var RetrySubscriber = (function (_super) {
11919     __extends(RetrySubscriber, _super);
11920     function RetrySubscriber(destination, count, source) {
11921         var _this = _super.call(this, destination) || this;
11922         _this.count = count;
11923         _this.source = source;
11924         return _this;
11925     }
11926     RetrySubscriber.prototype.error = function (err) {
11927         if (!this.isStopped) {
11928             var _a = this, source = _a.source, count = _a.count;
11929             if (count === 0) {
11930                 return _super.prototype.error.call(this, err);
11931             }
11932             else if (count > -1) {
11933                 this.count = count - 1;
11934             }
11935             source.subscribe(this._unsubscribeAndRecycle());
11936         }
11937     };
11938     return RetrySubscriber;
11939 }(Subscriber_1.Subscriber));
11940
11941 },{"../Subscriber":38}],137:[function(require,module,exports){
11942 "use strict";
11943 var __extends = (this && this.__extends) || (function () {
11944     var extendStatics = function (d, b) {
11945         extendStatics = Object.setPrototypeOf ||
11946             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11947             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11948         return extendStatics(d, b);
11949     }
11950     return function (d, b) {
11951         extendStatics(d, b);
11952         function __() { this.constructor = d; }
11953         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11954     };
11955 })();
11956 Object.defineProperty(exports, "__esModule", { value: true });
11957 var Subject_1 = require("../Subject");
11958 var tryCatch_1 = require("../util/tryCatch");
11959 var errorObject_1 = require("../util/errorObject");
11960 var OuterSubscriber_1 = require("../OuterSubscriber");
11961 var subscribeToResult_1 = require("../util/subscribeToResult");
11962 function retryWhen(notifier) {
11963     return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); };
11964 }
11965 exports.retryWhen = retryWhen;
11966 var RetryWhenOperator = (function () {
11967     function RetryWhenOperator(notifier, source) {
11968         this.notifier = notifier;
11969         this.source = source;
11970     }
11971     RetryWhenOperator.prototype.call = function (subscriber, source) {
11972         return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));
11973     };
11974     return RetryWhenOperator;
11975 }());
11976 var RetryWhenSubscriber = (function (_super) {
11977     __extends(RetryWhenSubscriber, _super);
11978     function RetryWhenSubscriber(destination, notifier, source) {
11979         var _this = _super.call(this, destination) || this;
11980         _this.notifier = notifier;
11981         _this.source = source;
11982         return _this;
11983     }
11984     RetryWhenSubscriber.prototype.error = function (err) {
11985         if (!this.isStopped) {
11986             var errors = this.errors;
11987             var retries = this.retries;
11988             var retriesSubscription = this.retriesSubscription;
11989             if (!retries) {
11990                 errors = new Subject_1.Subject();
11991                 retries = tryCatch_1.tryCatch(this.notifier)(errors);
11992                 if (retries === errorObject_1.errorObject) {
11993                     return _super.prototype.error.call(this, errorObject_1.errorObject.e);
11994                 }
11995                 retriesSubscription = subscribeToResult_1.subscribeToResult(this, retries);
11996             }
11997             else {
11998                 this.errors = null;
11999                 this.retriesSubscription = null;
12000             }
12001             this._unsubscribeAndRecycle();
12002             this.errors = errors;
12003             this.retries = retries;
12004             this.retriesSubscription = retriesSubscription;
12005             errors.next(err);
12006         }
12007     };
12008     RetryWhenSubscriber.prototype._unsubscribe = function () {
12009         var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription;
12010         if (errors) {
12011             errors.unsubscribe();
12012             this.errors = null;
12013         }
12014         if (retriesSubscription) {
12015             retriesSubscription.unsubscribe();
12016             this.retriesSubscription = null;
12017         }
12018         this.retries = null;
12019     };
12020     RetryWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12021         var _unsubscribe = this._unsubscribe;
12022         this._unsubscribe = null;
12023         this._unsubscribeAndRecycle();
12024         this._unsubscribe = _unsubscribe;
12025         this.source.subscribe(this);
12026     };
12027     return RetryWhenSubscriber;
12028 }(OuterSubscriber_1.OuterSubscriber));
12029
12030 },{"../OuterSubscriber":33,"../Subject":36,"../util/errorObject":199,"../util/subscribeToResult":221,"../util/tryCatch":223}],138:[function(require,module,exports){
12031 "use strict";
12032 var __extends = (this && this.__extends) || (function () {
12033     var extendStatics = function (d, b) {
12034         extendStatics = Object.setPrototypeOf ||
12035             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12036             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12037         return extendStatics(d, b);
12038     }
12039     return function (d, b) {
12040         extendStatics(d, b);
12041         function __() { this.constructor = d; }
12042         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12043     };
12044 })();
12045 Object.defineProperty(exports, "__esModule", { value: true });
12046 var OuterSubscriber_1 = require("../OuterSubscriber");
12047 var subscribeToResult_1 = require("../util/subscribeToResult");
12048 function sample(notifier) {
12049     return function (source) { return source.lift(new SampleOperator(notifier)); };
12050 }
12051 exports.sample = sample;
12052 var SampleOperator = (function () {
12053     function SampleOperator(notifier) {
12054         this.notifier = notifier;
12055     }
12056     SampleOperator.prototype.call = function (subscriber, source) {
12057         var sampleSubscriber = new SampleSubscriber(subscriber);
12058         var subscription = source.subscribe(sampleSubscriber);
12059         subscription.add(subscribeToResult_1.subscribeToResult(sampleSubscriber, this.notifier));
12060         return subscription;
12061     };
12062     return SampleOperator;
12063 }());
12064 var SampleSubscriber = (function (_super) {
12065     __extends(SampleSubscriber, _super);
12066     function SampleSubscriber() {
12067         var _this = _super !== null && _super.apply(this, arguments) || this;
12068         _this.hasValue = false;
12069         return _this;
12070     }
12071     SampleSubscriber.prototype._next = function (value) {
12072         this.value = value;
12073         this.hasValue = true;
12074     };
12075     SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12076         this.emitValue();
12077     };
12078     SampleSubscriber.prototype.notifyComplete = function () {
12079         this.emitValue();
12080     };
12081     SampleSubscriber.prototype.emitValue = function () {
12082         if (this.hasValue) {
12083             this.hasValue = false;
12084             this.destination.next(this.value);
12085         }
12086     };
12087     return SampleSubscriber;
12088 }(OuterSubscriber_1.OuterSubscriber));
12089
12090 },{"../OuterSubscriber":33,"../util/subscribeToResult":221}],139:[function(require,module,exports){
12091 "use strict";
12092 var __extends = (this && this.__extends) || (function () {
12093     var extendStatics = function (d, b) {
12094         extendStatics = Object.setPrototypeOf ||
12095             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12096             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12097         return extendStatics(d, b);
12098     }
12099     return function (d, b) {
12100         extendStatics(d, b);
12101         function __() { this.constructor = d; }
12102         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12103     };
12104 })();
12105 Object.defineProperty(exports, "__esModule", { value: true });
12106 var Subscriber_1 = require("../Subscriber");
12107 var async_1 = require("../scheduler/async");
12108 function sampleTime(period, scheduler) {
12109     if (scheduler === void 0) { scheduler = async_1.async; }
12110     return function (source) { return source.lift(new SampleTimeOperator(period, scheduler)); };
12111 }
12112 exports.sampleTime = sampleTime;
12113 var SampleTimeOperator = (function () {
12114     function SampleTimeOperator(period, scheduler) {
12115         this.period = period;
12116         this.scheduler = scheduler;
12117     }
12118     SampleTimeOperator.prototype.call = function (subscriber, source) {
12119         return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler));
12120     };
12121     return SampleTimeOperator;
12122 }());
12123 var SampleTimeSubscriber = (function (_super) {
12124     __extends(SampleTimeSubscriber, _super);
12125     function SampleTimeSubscriber(destination, period, scheduler) {
12126         var _this = _super.call(this, destination) || this;
12127         _this.period = period;
12128         _this.scheduler = scheduler;
12129         _this.hasValue = false;
12130         _this.add(scheduler.schedule(dispatchNotification, period, { subscriber: _this, period: period }));
12131         return _this;
12132     }
12133     SampleTimeSubscriber.prototype._next = function (value) {
12134         this.lastValue = value;
12135         this.hasValue = true;
12136     };
12137     SampleTimeSubscriber.prototype.notifyNext = function () {
12138         if (this.hasValue) {
12139             this.hasValue = false;
12140             this.destination.next(this.lastValue);
12141         }
12142     };
12143     return SampleTimeSubscriber;
12144 }(Subscriber_1.Subscriber));
12145 function dispatchNotification(state) {
12146     var subscriber = state.subscriber, period = state.period;
12147     subscriber.notifyNext();
12148     this.schedule(state, period);
12149 }
12150
12151 },{"../Subscriber":38,"../scheduler/async":187}],140:[function(require,module,exports){
12152 "use strict";
12153 var __extends = (this && this.__extends) || (function () {
12154     var extendStatics = function (d, b) {
12155         extendStatics = Object.setPrototypeOf ||
12156             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12157             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12158         return extendStatics(d, b);
12159     }
12160     return function (d, b) {
12161         extendStatics(d, b);
12162         function __() { this.constructor = d; }
12163         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12164     };
12165 })();
12166 Object.defineProperty(exports, "__esModule", { value: true });
12167 var Subscriber_1 = require("../Subscriber");
12168 function scan(accumulator, seed) {
12169     var hasSeed = false;
12170     if (arguments.length >= 2) {
12171         hasSeed = true;
12172     }
12173     return function scanOperatorFunction(source) {
12174         return source.lift(new ScanOperator(accumulator, seed, hasSeed));
12175     };
12176 }
12177 exports.scan = scan;
12178 var ScanOperator = (function () {
12179     function ScanOperator(accumulator, seed, hasSeed) {
12180         if (hasSeed === void 0) { hasSeed = false; }
12181         this.accumulator = accumulator;
12182         this.seed = seed;
12183         this.hasSeed = hasSeed;
12184     }
12185     ScanOperator.prototype.call = function (subscriber, source) {
12186         return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
12187     };
12188     return ScanOperator;
12189 }());
12190 var ScanSubscriber = (function (_super) {
12191     __extends(ScanSubscriber, _super);
12192     function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
12193         var _this = _super.call(this, destination) || this;
12194         _this.accumulator = accumulator;
12195         _this._seed = _seed;
12196         _this.hasSeed = hasSeed;
12197         _this.index = 0;
12198         return _this;
12199     }
12200     Object.defineProperty(ScanSubscriber.prototype, "seed", {
12201         get: function () {
12202             return this._seed;
12203         },
12204         set: function (value) {
12205             this.hasSeed = true;
12206             this._seed = value;
12207         },
12208         enumerable: true,
12209         configurable: true
12210     });
12211     ScanSubscriber.prototype._next = function (value) {
12212         if (!this.hasSeed) {
12213             this.seed = value;
12214             this.destination.next(value);
12215         }
12216         else {
12217             return this._tryNext(value);
12218         }
12219     };
12220     ScanSubscriber.prototype._tryNext = function (value) {
12221         var index = this.index++;
12222         var result;
12223         try {
12224             result = this.accumulator(this.seed, value, index);
12225         }
12226         catch (err) {
12227             this.destination.error(err);
12228         }
12229         this.seed = result;
12230         this.destination.next(result);
12231     };
12232     return ScanSubscriber;
12233 }(Subscriber_1.Subscriber));
12234
12235 },{"../Subscriber":38}],141:[function(require,module,exports){
12236 "use strict";
12237 var __extends = (this && this.__extends) || (function () {
12238     var extendStatics = function (d, b) {
12239         extendStatics = Object.setPrototypeOf ||
12240             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12241             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12242         return extendStatics(d, b);
12243     }
12244     return function (d, b) {
12245         extendStatics(d, b);
12246         function __() { this.constructor = d; }
12247         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12248     };
12249 })();
12250 Object.defineProperty(exports, "__esModule", { value: true });
12251 var Subscriber_1 = require("../Subscriber");
12252 var tryCatch_1 = require("../util/tryCatch");
12253 var errorObject_1 = require("../util/errorObject");
12254 function sequenceEqual(compareTo, comparor) {
12255     return function (source) { return source.lift(new SequenceEqualOperator(compareTo, comparor)); };
12256 }
12257 exports.sequenceEqual = sequenceEqual;
12258 var SequenceEqualOperator = (function () {
12259     function SequenceEqualOperator(compareTo, comparor) {
12260         this.compareTo = compareTo;
12261         this.comparor = comparor;
12262     }
12263     SequenceEqualOperator.prototype.call = function (subscriber, source) {
12264         return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparor));
12265     };
12266     return SequenceEqualOperator;
12267 }());
12268 exports.SequenceEqualOperator = SequenceEqualOperator;
12269 var SequenceEqualSubscriber = (function (_super) {
12270     __extends(SequenceEqualSubscriber, _super);
12271     function SequenceEqualSubscriber(destination, compareTo, comparor) {
12272         var _this = _super.call(this, destination) || this;
12273         _this.compareTo = compareTo;
12274         _this.comparor = comparor;
12275         _this._a = [];
12276         _this._b = [];
12277         _this._oneComplete = false;
12278         _this.destination.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, _this)));
12279         return _this;
12280     }
12281     SequenceEqualSubscriber.prototype._next = function (value) {
12282         if (this._oneComplete && this._b.length === 0) {
12283             this.emit(false);
12284         }
12285         else {
12286             this._a.push(value);
12287             this.checkValues();
12288         }
12289     };
12290     SequenceEqualSubscriber.prototype._complete = function () {
12291         if (this._oneComplete) {
12292             this.emit(this._a.length === 0 && this._b.length === 0);
12293         }
12294         else {
12295             this._oneComplete = true;
12296         }
12297         this.unsubscribe();
12298     };
12299     SequenceEqualSubscriber.prototype.checkValues = function () {
12300         var _c = this, _a = _c._a, _b = _c._b, comparor = _c.comparor;
12301         while (_a.length > 0 && _b.length > 0) {
12302             var a = _a.shift();
12303             var b = _b.shift();
12304             var areEqual = false;
12305             if (comparor) {
12306                 areEqual = tryCatch_1.tryCatch(comparor)(a, b);
12307                 if (areEqual === errorObject_1.errorObject) {
12308                     this.destination.error(errorObject_1.errorObject.e);
12309                 }
12310             }
12311             else {
12312                 areEqual = a === b;
12313             }
12314             if (!areEqual) {
12315                 this.emit(false);
12316             }
12317         }
12318     };
12319     SequenceEqualSubscriber.prototype.emit = function (value) {
12320         var destination = this.destination;
12321         destination.next(value);
12322         destination.complete();
12323     };
12324     SequenceEqualSubscriber.prototype.nextB = function (value) {
12325         if (this._oneComplete && this._a.length === 0) {
12326             this.emit(false);
12327         }
12328         else {
12329             this._b.push(value);
12330             this.checkValues();
12331         }
12332     };
12333     SequenceEqualSubscriber.prototype.completeB = function () {
12334         if (this._oneComplete) {
12335             this.emit(this._a.length === 0 && this._b.length === 0);
12336         }
12337         else {
12338             this._oneComplete = true;
12339         }
12340     };
12341     return SequenceEqualSubscriber;
12342 }(Subscriber_1.Subscriber));
12343 exports.SequenceEqualSubscriber = SequenceEqualSubscriber;
12344 var SequenceEqualCompareToSubscriber = (function (_super) {
12345     __extends(SequenceEqualCompareToSubscriber, _super);
12346     function SequenceEqualCompareToSubscriber(destination, parent) {
12347         var _this = _super.call(this, destination) || this;
12348         _this.parent = parent;
12349         return _this;
12350     }
12351     SequenceEqualCompareToSubscriber.prototype._next = function (value) {
12352         this.parent.nextB(value);
12353     };
12354     SequenceEqualCompareToSubscriber.prototype._error = function (err) {
12355         this.parent.error(err);
12356         this.unsubscribe();
12357     };
12358     SequenceEqualCompareToSubscriber.prototype._complete = function () {
12359         this.parent.completeB();
12360         this.unsubscribe();
12361     };
12362     return SequenceEqualCompareToSubscriber;
12363 }(Subscriber_1.Subscriber));
12364
12365 },{"../Subscriber":38,"../util/errorObject":199,"../util/tryCatch":223}],142:[function(require,module,exports){
12366 "use strict";
12367 Object.defineProperty(exports, "__esModule", { value: true });
12368 var multicast_1 = require("./multicast");
12369 var refCount_1 = require("./refCount");
12370 var Subject_1 = require("../Subject");
12371 function shareSubjectFactory() {
12372     return new Subject_1.Subject();
12373 }
12374 function share() {
12375     return function (source) { return refCount_1.refCount()(multicast_1.multicast(shareSubjectFactory)(source)); };
12376 }
12377 exports.share = share;
12378
12379 },{"../Subject":36,"./multicast":121,"./refCount":133}],143:[function(require,module,exports){
12380 "use strict";
12381 Object.defineProperty(exports, "__esModule", { value: true });
12382 var ReplaySubject_1 = require("../ReplaySubject");
12383 function shareReplay(bufferSize, windowTime, scheduler) {
12384     if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
12385     if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
12386     return function (source) { return source.lift(shareReplayOperator(bufferSize, windowTime, scheduler)); };
12387 }
12388 exports.shareReplay = shareReplay;
12389 function shareReplayOperator(bufferSize, windowTime, scheduler) {
12390     var subject;
12391     var refCount = 0;
12392     var subscription;
12393     var hasError = false;
12394     var isComplete = false;
12395     return function shareReplayOperation(source) {
12396         refCount++;
12397         if (!subject || hasError) {
12398             hasError = false;
12399             subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler);
12400             subscription = source.subscribe({
12401                 next: function (value) { subject.next(value); },
12402                 error: function (err) {
12403                     hasError = true;
12404                     subject.error(err);
12405                 },
12406                 complete: function () {
12407                     isComplete = true;
12408                     subject.complete();
12409                 },
12410             });
12411         }
12412         var innerSub = subject.subscribe(this);
12413         return function () {
12414             refCount--;
12415             innerSub.unsubscribe();
12416             if (subscription && refCount === 0 && isComplete) {
12417                 subscription.unsubscribe();
12418             }
12419         };
12420     };
12421 }
12422
12423 },{"../ReplaySubject":34}],144:[function(require,module,exports){
12424 "use strict";
12425 var __extends = (this && this.__extends) || (function () {
12426     var extendStatics = function (d, b) {
12427         extendStatics = Object.setPrototypeOf ||
12428             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12429             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12430         return extendStatics(d, b);
12431     }
12432     return function (d, b) {
12433         extendStatics(d, b);
12434         function __() { this.constructor = d; }
12435         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12436     };
12437 })();
12438 Object.defineProperty(exports, "__esModule", { value: true });
12439 var Subscriber_1 = require("../Subscriber");
12440 var EmptyError_1 = require("../util/EmptyError");
12441 function single(predicate) {
12442     return function (source) { return source.lift(new SingleOperator(predicate, source)); };
12443 }
12444 exports.single = single;
12445 var SingleOperator = (function () {
12446     function SingleOperator(predicate, source) {
12447         this.predicate = predicate;
12448         this.source = source;
12449     }
12450     SingleOperator.prototype.call = function (subscriber, source) {
12451         return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source));
12452     };
12453     return SingleOperator;
12454 }());
12455 var SingleSubscriber = (function (_super) {
12456     __extends(SingleSubscriber, _super);
12457     function SingleSubscriber(destination, predicate, source) {
12458         var _this = _super.call(this, destination) || this;
12459         _this.predicate = predicate;
12460         _this.source = source;
12461         _this.seenValue = false;
12462         _this.index = 0;
12463         return _this;
12464     }
12465     SingleSubscriber.prototype.applySingleValue = function (value) {
12466         if (this.seenValue) {
12467             this.destination.error('Sequence contains more than one element');
12468         }
12469         else {
12470             this.seenValue = true;
12471             this.singleValue = value;
12472         }
12473     };
12474     SingleSubscriber.prototype._next = function (value) {
12475         var index = this.index++;
12476         if (this.predicate) {
12477             this.tryNext(value, index);
12478         }
12479         else {
12480             this.applySingleValue(value);
12481         }
12482     };
12483     SingleSubscriber.prototype.tryNext = function (value, index) {
12484         try {
12485             if (this.predicate(value, index, this.source)) {
12486                 this.applySingleValue(value);
12487             }
12488         }
12489         catch (err) {
12490             this.destination.error(err);
12491         }
12492     };
12493     SingleSubscriber.prototype._complete = function () {
12494         var destination = this.destination;
12495         if (this.index > 0) {
12496             destination.next(this.seenValue ? this.singleValue : undefined);
12497             destination.complete();
12498         }
12499         else {
12500             destination.error(new EmptyError_1.EmptyError);
12501         }
12502     };
12503     return SingleSubscriber;
12504 }(Subscriber_1.Subscriber));
12505
12506 },{"../Subscriber":38,"../util/EmptyError":193}],145:[function(require,module,exports){
12507 "use strict";
12508 var __extends = (this && this.__extends) || (function () {
12509     var extendStatics = function (d, b) {
12510         extendStatics = Object.setPrototypeOf ||
12511             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12512             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12513         return extendStatics(d, b);
12514     }
12515     return function (d, b) {
12516         extendStatics(d, b);
12517         function __() { this.constructor = d; }
12518         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12519     };
12520 })();
12521 Object.defineProperty(exports, "__esModule", { value: true });
12522 var Subscriber_1 = require("../Subscriber");
12523 function skip(count) {
12524     return function (source) { return source.lift(new SkipOperator(count)); };
12525 }
12526 exports.skip = skip;
12527 var SkipOperator = (function () {
12528     function SkipOperator(total) {
12529         this.total = total;
12530     }
12531     SkipOperator.prototype.call = function (subscriber, source) {
12532         return source.subscribe(new SkipSubscriber(subscriber, this.total));
12533     };
12534     return SkipOperator;
12535 }());
12536 var SkipSubscriber = (function (_super) {
12537     __extends(SkipSubscriber, _super);
12538     function SkipSubscriber(destination, total) {
12539         var _this = _super.call(this, destination) || this;
12540         _this.total = total;
12541         _this.count = 0;
12542         return _this;
12543     }
12544     SkipSubscriber.prototype._next = function (x) {
12545         if (++this.count > this.total) {
12546             this.destination.next(x);
12547         }
12548     };
12549     return SkipSubscriber;
12550 }(Subscriber_1.Subscriber));
12551
12552 },{"../Subscriber":38}],146:[function(require,module,exports){
12553 "use strict";
12554 var __extends = (this && this.__extends) || (function () {
12555     var extendStatics = function (d, b) {
12556         extendStatics = Object.setPrototypeOf ||
12557             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12558             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12559         return extendStatics(d, b);
12560     }
12561     return function (d, b) {
12562         extendStatics(d, b);
12563         function __() { this.constructor = d; }
12564         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12565     };
12566 })();
12567 Object.defineProperty(exports, "__esModule", { value: true });
12568 var Subscriber_1 = require("../Subscriber");
12569 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
12570 function skipLast(count) {
12571     return function (source) { return source.lift(new SkipLastOperator(count)); };
12572 }
12573 exports.skipLast = skipLast;
12574 var SkipLastOperator = (function () {
12575     function SkipLastOperator(_skipCount) {
12576         this._skipCount = _skipCount;
12577         if (this._skipCount < 0) {
12578             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
12579         }
12580     }
12581     SkipLastOperator.prototype.call = function (subscriber, source) {
12582         if (this._skipCount === 0) {
12583             return source.subscribe(new Subscriber_1.Subscriber(subscriber));
12584         }
12585         else {
12586             return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount));
12587         }
12588     };
12589     return SkipLastOperator;
12590 }());
12591 var SkipLastSubscriber = (function (_super) {
12592     __extends(SkipLastSubscriber, _super);
12593     function SkipLastSubscriber(destination, _skipCount) {
12594         var _this = _super.call(this, destination) || this;
12595         _this._skipCount = _skipCount;
12596         _this._count = 0;
12597         _this._ring = new Array(_skipCount);
12598         return _this;
12599     }
12600     SkipLastSubscriber.prototype._next = function (value) {
12601         var skipCount = this._skipCount;
12602         var count = this._count++;
12603         if (count < skipCount) {
12604             this._ring[count] = value;
12605         }
12606         else {
12607             var currentIndex = count % skipCount;
12608             var ring = this._ring;
12609             var oldValue = ring[currentIndex];
12610             ring[currentIndex] = value;
12611             this.destination.next(oldValue);
12612         }
12613     };
12614     return SkipLastSubscriber;
12615 }(Subscriber_1.Subscriber));
12616
12617 },{"../Subscriber":38,"../util/ArgumentOutOfRangeError":192}],147:[function(require,module,exports){
12618 "use strict";
12619 var __extends = (this && this.__extends) || (function () {
12620     var extendStatics = function (d, b) {
12621         extendStatics = Object.setPrototypeOf ||
12622             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12623             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12624         return extendStatics(d, b);
12625     }
12626     return function (d, b) {
12627         extendStatics(d, b);
12628         function __() { this.constructor = d; }
12629         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12630     };
12631 })();
12632 Object.defineProperty(exports, "__esModule", { value: true });
12633 var OuterSubscriber_1 = require("../OuterSubscriber");
12634 var InnerSubscriber_1 = require("../InnerSubscriber");
12635 var subscribeToResult_1 = require("../util/subscribeToResult");
12636 function skipUntil(notifier) {
12637     return function (source) { return source.lift(new SkipUntilOperator(notifier)); };
12638 }
12639 exports.skipUntil = skipUntil;
12640 var SkipUntilOperator = (function () {
12641     function SkipUntilOperator(notifier) {
12642         this.notifier = notifier;
12643     }
12644     SkipUntilOperator.prototype.call = function (destination, source) {
12645         return source.subscribe(new SkipUntilSubscriber(destination, this.notifier));
12646     };
12647     return SkipUntilOperator;
12648 }());
12649 var SkipUntilSubscriber = (function (_super) {
12650     __extends(SkipUntilSubscriber, _super);
12651     function SkipUntilSubscriber(destination, notifier) {
12652         var _this = _super.call(this, destination) || this;
12653         _this.hasValue = false;
12654         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(_this, undefined, undefined);
12655         _this.add(innerSubscriber);
12656         _this.innerSubscription = innerSubscriber;
12657         subscribeToResult_1.subscribeToResult(_this, notifier, undefined, undefined, innerSubscriber);
12658         return _this;
12659     }
12660     SkipUntilSubscriber.prototype._next = function (value) {
12661         if (this.hasValue) {
12662             _super.prototype._next.call(this, value);
12663         }
12664     };
12665     SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12666         this.hasValue = true;
12667         if (this.innerSubscription) {
12668             this.innerSubscription.unsubscribe();
12669         }
12670     };
12671     SkipUntilSubscriber.prototype.notifyComplete = function () {
12672     };
12673     return SkipUntilSubscriber;
12674 }(OuterSubscriber_1.OuterSubscriber));
12675
12676 },{"../InnerSubscriber":29,"../OuterSubscriber":33,"../util/subscribeToResult":221}],148:[function(require,module,exports){
12677 "use strict";
12678 var __extends = (this && this.__extends) || (function () {
12679     var extendStatics = function (d, b) {
12680         extendStatics = Object.setPrototypeOf ||
12681             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12682             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12683         return extendStatics(d, b);
12684     }
12685     return function (d, b) {
12686         extendStatics(d, b);
12687         function __() { this.constructor = d; }
12688         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12689     };
12690 })();
12691 Object.defineProperty(exports, "__esModule", { value: true });
12692 var Subscriber_1 = require("../Subscriber");
12693 function skipWhile(predicate) {
12694     return function (source) { return source.lift(new SkipWhileOperator(predicate)); };
12695 }
12696 exports.skipWhile = skipWhile;
12697 var SkipWhileOperator = (function () {
12698     function SkipWhileOperator(predicate) {
12699         this.predicate = predicate;
12700     }
12701     SkipWhileOperator.prototype.call = function (subscriber, source) {
12702         return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
12703     };
12704     return SkipWhileOperator;
12705 }());
12706 var SkipWhileSubscriber = (function (_super) {
12707     __extends(SkipWhileSubscriber, _super);
12708     function SkipWhileSubscriber(destination, predicate) {
12709         var _this = _super.call(this, destination) || this;
12710         _this.predicate = predicate;
12711         _this.skipping = true;
12712         _this.index = 0;
12713         return _this;
12714     }
12715     SkipWhileSubscriber.prototype._next = function (value) {
12716         var destination = this.destination;
12717         if (this.skipping) {
12718             this.tryCallPredicate(value);
12719         }
12720         if (!this.skipping) {
12721             destination.next(value);
12722         }
12723     };
12724     SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
12725         try {
12726             var result = this.predicate(value, this.index++);
12727             this.skipping = Boolean(result);
12728         }
12729         catch (err) {
12730             this.destination.error(err);
12731         }
12732     };
12733     return SkipWhileSubscriber;
12734 }(Subscriber_1.Subscriber));
12735
12736 },{"../Subscriber":38}],149:[function(require,module,exports){
12737 "use strict";
12738 Object.defineProperty(exports, "__esModule", { value: true });
12739 var fromArray_1 = require("../observable/fromArray");
12740 var scalar_1 = require("../observable/scalar");
12741 var empty_1 = require("../observable/empty");
12742 var concat_1 = require("../observable/concat");
12743 var isScheduler_1 = require("../util/isScheduler");
12744 function startWith() {
12745     var array = [];
12746     for (var _i = 0; _i < arguments.length; _i++) {
12747         array[_i] = arguments[_i];
12748     }
12749     return function (source) {
12750         var scheduler = array[array.length - 1];
12751         if (isScheduler_1.isScheduler(scheduler)) {
12752             array.pop();
12753         }
12754         else {
12755             scheduler = null;
12756         }
12757         var len = array.length;
12758         if (len === 1 && !scheduler) {
12759             return concat_1.concat(scalar_1.scalar(array[0]), source);
12760         }
12761         else if (len > 0) {
12762             return concat_1.concat(fromArray_1.fromArray(array, scheduler), source);
12763         }
12764         else {
12765             return concat_1.concat(empty_1.empty(scheduler), source);
12766         }
12767     };
12768 }
12769 exports.startWith = startWith;
12770
12771 },{"../observable/concat":46,"../observable/empty":48,"../observable/fromArray":51,"../observable/scalar":67,"../util/isScheduler":212}],150:[function(require,module,exports){
12772 "use strict";
12773 Object.defineProperty(exports, "__esModule", { value: true });
12774 var SubscribeOnObservable_1 = require("../observable/SubscribeOnObservable");
12775 function subscribeOn(scheduler, delay) {
12776     if (delay === void 0) { delay = 0; }
12777     return function subscribeOnOperatorFunction(source) {
12778         return source.lift(new SubscribeOnOperator(scheduler, delay));
12779     };
12780 }
12781 exports.subscribeOn = subscribeOn;
12782 var SubscribeOnOperator = (function () {
12783     function SubscribeOnOperator(scheduler, delay) {
12784         this.scheduler = scheduler;
12785         this.delay = delay;
12786     }
12787     SubscribeOnOperator.prototype.call = function (subscriber, source) {
12788         return new SubscribeOnObservable_1.SubscribeOnObservable(source, this.delay, this.scheduler).subscribe(subscriber);
12789     };
12790     return SubscribeOnOperator;
12791 }());
12792
12793 },{"../observable/SubscribeOnObservable":42}],151:[function(require,module,exports){
12794 "use strict";
12795 Object.defineProperty(exports, "__esModule", { value: true });
12796 var switchMap_1 = require("./switchMap");
12797 var identity_1 = require("../util/identity");
12798 function switchAll() {
12799     return switchMap_1.switchMap(identity_1.identity);
12800 }
12801 exports.switchAll = switchAll;
12802
12803 },{"../util/identity":201,"./switchMap":152}],152:[function(require,module,exports){
12804 "use strict";
12805 var __extends = (this && this.__extends) || (function () {
12806     var extendStatics = function (d, b) {
12807         extendStatics = Object.setPrototypeOf ||
12808             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12809             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12810         return extendStatics(d, b);
12811     }
12812     return function (d, b) {
12813         extendStatics(d, b);
12814         function __() { this.constructor = d; }
12815         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12816     };
12817 })();
12818 Object.defineProperty(exports, "__esModule", { value: true });
12819 var OuterSubscriber_1 = require("../OuterSubscriber");
12820 var InnerSubscriber_1 = require("../InnerSubscriber");
12821 var subscribeToResult_1 = require("../util/subscribeToResult");
12822 var map_1 = require("./map");
12823 var from_1 = require("../observable/from");
12824 function switchMap(project, resultSelector) {
12825     if (typeof resultSelector === 'function') {
12826         return function (source) { return source.pipe(switchMap(function (a, i) { return from_1.from(project(a, i)).pipe(map_1.map(function (b, ii) { return resultSelector(a, b, i, ii); })); })); };
12827     }
12828     return function (source) { return source.lift(new SwitchMapOperator(project)); };
12829 }
12830 exports.switchMap = switchMap;
12831 var SwitchMapOperator = (function () {
12832     function SwitchMapOperator(project) {
12833         this.project = project;
12834     }
12835     SwitchMapOperator.prototype.call = function (subscriber, source) {
12836         return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));
12837     };
12838     return SwitchMapOperator;
12839 }());
12840 var SwitchMapSubscriber = (function (_super) {
12841     __extends(SwitchMapSubscriber, _super);
12842     function SwitchMapSubscriber(destination, project) {
12843         var _this = _super.call(this, destination) || this;
12844         _this.project = project;
12845         _this.index = 0;
12846         return _this;
12847     }
12848     SwitchMapSubscriber.prototype._next = function (value) {
12849         var result;
12850         var index = this.index++;
12851         try {
12852             result = this.project(value, index);
12853         }
12854         catch (error) {
12855             this.destination.error(error);
12856             return;
12857         }
12858         this._innerSub(result, value, index);
12859     };
12860     SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
12861         var innerSubscription = this.innerSubscription;
12862         if (innerSubscription) {
12863             innerSubscription.unsubscribe();
12864         }
12865         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
12866         var destination = this.destination;
12867         destination.add(innerSubscriber);
12868         this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index, innerSubscriber);
12869     };
12870     SwitchMapSubscriber.prototype._complete = function () {
12871         var innerSubscription = this.innerSubscription;
12872         if (!innerSubscription || innerSubscription.closed) {
12873             _super.prototype._complete.call(this);
12874         }
12875         this.unsubscribe();
12876     };
12877     SwitchMapSubscriber.prototype._unsubscribe = function () {
12878         this.innerSubscription = null;
12879     };
12880     SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
12881         var destination = this.destination;
12882         destination.remove(innerSub);
12883         this.innerSubscription = null;
12884         if (this.isStopped) {
12885             _super.prototype._complete.call(this);
12886         }
12887     };
12888     SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12889         this.destination.next(innerValue);
12890     };
12891     return SwitchMapSubscriber;
12892 }(OuterSubscriber_1.OuterSubscriber));
12893
12894 },{"../InnerSubscriber":29,"../OuterSubscriber":33,"../observable/from":50,"../util/subscribeToResult":221,"./map":111}],153:[function(require,module,exports){
12895 "use strict";
12896 Object.defineProperty(exports, "__esModule", { value: true });
12897 var switchMap_1 = require("./switchMap");
12898 function switchMapTo(innerObservable, resultSelector) {
12899     return resultSelector ? switchMap_1.switchMap(function () { return innerObservable; }, resultSelector) : switchMap_1.switchMap(function () { return innerObservable; });
12900 }
12901 exports.switchMapTo = switchMapTo;
12902
12903 },{"./switchMap":152}],154:[function(require,module,exports){
12904 "use strict";
12905 var __extends = (this && this.__extends) || (function () {
12906     var extendStatics = function (d, b) {
12907         extendStatics = Object.setPrototypeOf ||
12908             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12909             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12910         return extendStatics(d, b);
12911     }
12912     return function (d, b) {
12913         extendStatics(d, b);
12914         function __() { this.constructor = d; }
12915         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12916     };
12917 })();
12918 Object.defineProperty(exports, "__esModule", { value: true });
12919 var Subscriber_1 = require("../Subscriber");
12920 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
12921 var empty_1 = require("../observable/empty");
12922 function take(count) {
12923     return function (source) {
12924         if (count === 0) {
12925             return empty_1.empty();
12926         }
12927         else {
12928             return source.lift(new TakeOperator(count));
12929         }
12930     };
12931 }
12932 exports.take = take;
12933 var TakeOperator = (function () {
12934     function TakeOperator(total) {
12935         this.total = total;
12936         if (this.total < 0) {
12937             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
12938         }
12939     }
12940     TakeOperator.prototype.call = function (subscriber, source) {
12941         return source.subscribe(new TakeSubscriber(subscriber, this.total));
12942     };
12943     return TakeOperator;
12944 }());
12945 var TakeSubscriber = (function (_super) {
12946     __extends(TakeSubscriber, _super);
12947     function TakeSubscriber(destination, total) {
12948         var _this = _super.call(this, destination) || this;
12949         _this.total = total;
12950         _this.count = 0;
12951         return _this;
12952     }
12953     TakeSubscriber.prototype._next = function (value) {
12954         var total = this.total;
12955         var count = ++this.count;
12956         if (count <= total) {
12957             this.destination.next(value);
12958             if (count === total) {
12959                 this.destination.complete();
12960                 this.unsubscribe();
12961             }
12962         }
12963     };
12964     return TakeSubscriber;
12965 }(Subscriber_1.Subscriber));
12966
12967 },{"../Subscriber":38,"../observable/empty":48,"../util/ArgumentOutOfRangeError":192}],155:[function(require,module,exports){
12968 "use strict";
12969 var __extends = (this && this.__extends) || (function () {
12970     var extendStatics = function (d, b) {
12971         extendStatics = Object.setPrototypeOf ||
12972             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12973             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12974         return extendStatics(d, b);
12975     }
12976     return function (d, b) {
12977         extendStatics(d, b);
12978         function __() { this.constructor = d; }
12979         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12980     };
12981 })();
12982 Object.defineProperty(exports, "__esModule", { value: true });
12983 var Subscriber_1 = require("../Subscriber");
12984 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
12985 var empty_1 = require("../observable/empty");
12986 function takeLast(count) {
12987     return function takeLastOperatorFunction(source) {
12988         if (count === 0) {
12989             return empty_1.empty();
12990         }
12991         else {
12992             return source.lift(new TakeLastOperator(count));
12993         }
12994     };
12995 }
12996 exports.takeLast = takeLast;
12997 var TakeLastOperator = (function () {
12998     function TakeLastOperator(total) {
12999         this.total = total;
13000         if (this.total < 0) {
13001             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
13002         }
13003     }
13004     TakeLastOperator.prototype.call = function (subscriber, source) {
13005         return source.subscribe(new TakeLastSubscriber(subscriber, this.total));
13006     };
13007     return TakeLastOperator;
13008 }());
13009 var TakeLastSubscriber = (function (_super) {
13010     __extends(TakeLastSubscriber, _super);
13011     function TakeLastSubscriber(destination, total) {
13012         var _this = _super.call(this, destination) || this;
13013         _this.total = total;
13014         _this.ring = new Array();
13015         _this.count = 0;
13016         return _this;
13017     }
13018     TakeLastSubscriber.prototype._next = function (value) {
13019         var ring = this.ring;
13020         var total = this.total;
13021         var count = this.count++;
13022         if (ring.length < total) {
13023             ring.push(value);
13024         }
13025         else {
13026             var index = count % total;
13027             ring[index] = value;
13028         }
13029     };
13030     TakeLastSubscriber.prototype._complete = function () {
13031         var destination = this.destination;
13032         var count = this.count;
13033         if (count > 0) {
13034             var total = this.count >= this.total ? this.total : this.count;
13035             var ring = this.ring;
13036             for (var i = 0; i < total; i++) {
13037                 var idx = (count++) % total;
13038                 destination.next(ring[idx]);
13039             }
13040         }
13041         destination.complete();
13042     };
13043     return TakeLastSubscriber;
13044 }(Subscriber_1.Subscriber));
13045
13046 },{"../Subscriber":38,"../observable/empty":48,"../util/ArgumentOutOfRangeError":192}],156:[function(require,module,exports){
13047 "use strict";
13048 var __extends = (this && this.__extends) || (function () {
13049     var extendStatics = function (d, b) {
13050         extendStatics = Object.setPrototypeOf ||
13051             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13052             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13053         return extendStatics(d, b);
13054     }
13055     return function (d, b) {
13056         extendStatics(d, b);
13057         function __() { this.constructor = d; }
13058         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13059     };
13060 })();
13061 Object.defineProperty(exports, "__esModule", { value: true });
13062 var OuterSubscriber_1 = require("../OuterSubscriber");
13063 var subscribeToResult_1 = require("../util/subscribeToResult");
13064 function takeUntil(notifier) {
13065     return function (source) { return source.lift(new TakeUntilOperator(notifier)); };
13066 }
13067 exports.takeUntil = takeUntil;
13068 var TakeUntilOperator = (function () {
13069     function TakeUntilOperator(notifier) {
13070         this.notifier = notifier;
13071     }
13072     TakeUntilOperator.prototype.call = function (subscriber, source) {
13073         var takeUntilSubscriber = new TakeUntilSubscriber(subscriber);
13074         var notifierSubscription = subscribeToResult_1.subscribeToResult(takeUntilSubscriber, this.notifier);
13075         if (notifierSubscription && !takeUntilSubscriber.seenValue) {
13076             takeUntilSubscriber.add(notifierSubscription);
13077             return source.subscribe(takeUntilSubscriber);
13078         }
13079         return takeUntilSubscriber;
13080     };
13081     return TakeUntilOperator;
13082 }());
13083 var TakeUntilSubscriber = (function (_super) {
13084     __extends(TakeUntilSubscriber, _super);
13085     function TakeUntilSubscriber(destination) {
13086         var _this = _super.call(this, destination) || this;
13087         _this.seenValue = false;
13088         return _this;
13089     }
13090     TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13091         this.seenValue = true;
13092         this.complete();
13093     };
13094     TakeUntilSubscriber.prototype.notifyComplete = function () {
13095     };
13096     return TakeUntilSubscriber;
13097 }(OuterSubscriber_1.OuterSubscriber));
13098
13099 },{"../OuterSubscriber":33,"../util/subscribeToResult":221}],157:[function(require,module,exports){
13100 "use strict";
13101 var __extends = (this && this.__extends) || (function () {
13102     var extendStatics = function (d, b) {
13103         extendStatics = Object.setPrototypeOf ||
13104             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13105             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13106         return extendStatics(d, b);
13107     }
13108     return function (d, b) {
13109         extendStatics(d, b);
13110         function __() { this.constructor = d; }
13111         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13112     };
13113 })();
13114 Object.defineProperty(exports, "__esModule", { value: true });
13115 var Subscriber_1 = require("../Subscriber");
13116 function takeWhile(predicate) {
13117     return function (source) { return source.lift(new TakeWhileOperator(predicate)); };
13118 }
13119 exports.takeWhile = takeWhile;
13120 var TakeWhileOperator = (function () {
13121     function TakeWhileOperator(predicate) {
13122         this.predicate = predicate;
13123     }
13124     TakeWhileOperator.prototype.call = function (subscriber, source) {
13125         return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate));
13126     };
13127     return TakeWhileOperator;
13128 }());
13129 var TakeWhileSubscriber = (function (_super) {
13130     __extends(TakeWhileSubscriber, _super);
13131     function TakeWhileSubscriber(destination, predicate) {
13132         var _this = _super.call(this, destination) || this;
13133         _this.predicate = predicate;
13134         _this.index = 0;
13135         return _this;
13136     }
13137     TakeWhileSubscriber.prototype._next = function (value) {
13138         var destination = this.destination;
13139         var result;
13140         try {
13141             result = this.predicate(value, this.index++);
13142         }
13143         catch (err) {
13144             destination.error(err);
13145             return;
13146         }
13147         this.nextOrComplete(value, result);
13148     };
13149     TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) {
13150         var destination = this.destination;
13151         if (Boolean(predicateResult)) {
13152             destination.next(value);
13153         }
13154         else {
13155             destination.complete();
13156         }
13157     };
13158     return TakeWhileSubscriber;
13159 }(Subscriber_1.Subscriber));
13160
13161 },{"../Subscriber":38}],158:[function(require,module,exports){
13162 "use strict";
13163 var __extends = (this && this.__extends) || (function () {
13164     var extendStatics = function (d, b) {
13165         extendStatics = Object.setPrototypeOf ||
13166             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13167             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13168         return extendStatics(d, b);
13169     }
13170     return function (d, b) {
13171         extendStatics(d, b);
13172         function __() { this.constructor = d; }
13173         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13174     };
13175 })();
13176 Object.defineProperty(exports, "__esModule", { value: true });
13177 var Subscriber_1 = require("../Subscriber");
13178 var noop_1 = require("../util/noop");
13179 var isFunction_1 = require("../util/isFunction");
13180 function tap(nextOrObserver, error, complete) {
13181     return function tapOperatorFunction(source) {
13182         return source.lift(new DoOperator(nextOrObserver, error, complete));
13183     };
13184 }
13185 exports.tap = tap;
13186 var DoOperator = (function () {
13187     function DoOperator(nextOrObserver, error, complete) {
13188         this.nextOrObserver = nextOrObserver;
13189         this.error = error;
13190         this.complete = complete;
13191     }
13192     DoOperator.prototype.call = function (subscriber, source) {
13193         return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
13194     };
13195     return DoOperator;
13196 }());
13197 var TapSubscriber = (function (_super) {
13198     __extends(TapSubscriber, _super);
13199     function TapSubscriber(destination, observerOrNext, error, complete) {
13200         var _this = _super.call(this, destination) || this;
13201         _this._tapNext = noop_1.noop;
13202         _this._tapError = noop_1.noop;
13203         _this._tapComplete = noop_1.noop;
13204         _this._tapError = error || noop_1.noop;
13205         _this._tapComplete = complete || noop_1.noop;
13206         if (isFunction_1.isFunction(observerOrNext)) {
13207             _this._context = _this;
13208             _this._tapNext = observerOrNext;
13209         }
13210         else if (observerOrNext) {
13211             _this._context = observerOrNext;
13212             _this._tapNext = observerOrNext.next || noop_1.noop;
13213             _this._tapError = observerOrNext.error || noop_1.noop;
13214             _this._tapComplete = observerOrNext.complete || noop_1.noop;
13215         }
13216         return _this;
13217     }
13218     TapSubscriber.prototype._next = function (value) {
13219         try {
13220             this._tapNext.call(this._context, value);
13221         }
13222         catch (err) {
13223             this.destination.error(err);
13224             return;
13225         }
13226         this.destination.next(value);
13227     };
13228     TapSubscriber.prototype._error = function (err) {
13229         try {
13230             this._tapError.call(this._context, err);
13231         }
13232         catch (err) {
13233             this.destination.error(err);
13234             return;
13235         }
13236         this.destination.error(err);
13237     };
13238     TapSubscriber.prototype._complete = function () {
13239         try {
13240             this._tapComplete.call(this._context);
13241         }
13242         catch (err) {
13243             this.destination.error(err);
13244             return;
13245         }
13246         return this.destination.complete();
13247     };
13248     return TapSubscriber;
13249 }(Subscriber_1.Subscriber));
13250
13251 },{"../Subscriber":38,"../util/isFunction":205,"../util/noop":213}],159:[function(require,module,exports){
13252 "use strict";
13253 var __extends = (this && this.__extends) || (function () {
13254     var extendStatics = function (d, b) {
13255         extendStatics = Object.setPrototypeOf ||
13256             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13257             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13258         return extendStatics(d, b);
13259     }
13260     return function (d, b) {
13261         extendStatics(d, b);
13262         function __() { this.constructor = d; }
13263         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13264     };
13265 })();
13266 Object.defineProperty(exports, "__esModule", { value: true });
13267 var OuterSubscriber_1 = require("../OuterSubscriber");
13268 var subscribeToResult_1 = require("../util/subscribeToResult");
13269 exports.defaultThrottleConfig = {
13270     leading: true,
13271     trailing: false
13272 };
13273 function throttle(durationSelector, config) {
13274     if (config === void 0) { config = exports.defaultThrottleConfig; }
13275     return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); };
13276 }
13277 exports.throttle = throttle;
13278 var ThrottleOperator = (function () {
13279     function ThrottleOperator(durationSelector, leading, trailing) {
13280         this.durationSelector = durationSelector;
13281         this.leading = leading;
13282         this.trailing = trailing;
13283     }
13284     ThrottleOperator.prototype.call = function (subscriber, source) {
13285         return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
13286     };
13287     return ThrottleOperator;
13288 }());
13289 var ThrottleSubscriber = (function (_super) {
13290     __extends(ThrottleSubscriber, _super);
13291     function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
13292         var _this = _super.call(this, destination) || this;
13293         _this.destination = destination;
13294         _this.durationSelector = durationSelector;
13295         _this._leading = _leading;
13296         _this._trailing = _trailing;
13297         _this._hasValue = false;
13298         return _this;
13299     }
13300     ThrottleSubscriber.prototype._next = function (value) {
13301         this._hasValue = true;
13302         this._sendValue = value;
13303         if (!this._throttled) {
13304             if (this._leading) {
13305                 this.send();
13306             }
13307             else {
13308                 this.throttle(value);
13309             }
13310         }
13311     };
13312     ThrottleSubscriber.prototype.send = function () {
13313         var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue;
13314         if (_hasValue) {
13315             this.destination.next(_sendValue);
13316             this.throttle(_sendValue);
13317         }
13318         this._hasValue = false;
13319         this._sendValue = null;
13320     };
13321     ThrottleSubscriber.prototype.throttle = function (value) {
13322         var duration = this.tryDurationSelector(value);
13323         if (duration) {
13324             this.add(this._throttled = subscribeToResult_1.subscribeToResult(this, duration));
13325         }
13326     };
13327     ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
13328         try {
13329             return this.durationSelector(value);
13330         }
13331         catch (err) {
13332             this.destination.error(err);
13333             return null;
13334         }
13335     };
13336     ThrottleSubscriber.prototype.throttlingDone = function () {
13337         var _a = this, _throttled = _a._throttled, _trailing = _a._trailing;
13338         if (_throttled) {
13339             _throttled.unsubscribe();
13340         }
13341         this._throttled = null;
13342         if (_trailing) {
13343             this.send();
13344         }
13345     };
13346     ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13347         this.throttlingDone();
13348     };
13349     ThrottleSubscriber.prototype.notifyComplete = function () {
13350         this.throttlingDone();
13351     };
13352     return ThrottleSubscriber;
13353 }(OuterSubscriber_1.OuterSubscriber));
13354
13355 },{"../OuterSubscriber":33,"../util/subscribeToResult":221}],160:[function(require,module,exports){
13356 "use strict";
13357 var __extends = (this && this.__extends) || (function () {
13358     var extendStatics = function (d, b) {
13359         extendStatics = Object.setPrototypeOf ||
13360             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13361             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13362         return extendStatics(d, b);
13363     }
13364     return function (d, b) {
13365         extendStatics(d, b);
13366         function __() { this.constructor = d; }
13367         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13368     };
13369 })();
13370 Object.defineProperty(exports, "__esModule", { value: true });
13371 var Subscriber_1 = require("../Subscriber");
13372 var async_1 = require("../scheduler/async");
13373 var throttle_1 = require("./throttle");
13374 function throttleTime(duration, scheduler, config) {
13375     if (scheduler === void 0) { scheduler = async_1.async; }
13376     if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
13377     return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); };
13378 }
13379 exports.throttleTime = throttleTime;
13380 var ThrottleTimeOperator = (function () {
13381     function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
13382         this.duration = duration;
13383         this.scheduler = scheduler;
13384         this.leading = leading;
13385         this.trailing = trailing;
13386     }
13387     ThrottleTimeOperator.prototype.call = function (subscriber, source) {
13388         return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
13389     };
13390     return ThrottleTimeOperator;
13391 }());
13392 var ThrottleTimeSubscriber = (function (_super) {
13393     __extends(ThrottleTimeSubscriber, _super);
13394     function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
13395         var _this = _super.call(this, destination) || this;
13396         _this.duration = duration;
13397         _this.scheduler = scheduler;
13398         _this.leading = leading;
13399         _this.trailing = trailing;
13400         _this._hasTrailingValue = false;
13401         _this._trailingValue = null;
13402         return _this;
13403     }
13404     ThrottleTimeSubscriber.prototype._next = function (value) {
13405         if (this.throttled) {
13406             if (this.trailing) {
13407                 this._trailingValue = value;
13408                 this._hasTrailingValue = true;
13409             }
13410         }
13411         else {
13412             this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
13413             if (this.leading) {
13414                 this.destination.next(value);
13415             }
13416         }
13417     };
13418     ThrottleTimeSubscriber.prototype._complete = function () {
13419         if (this._hasTrailingValue) {
13420             this.destination.next(this._trailingValue);
13421             this.destination.complete();
13422         }
13423         else {
13424             this.destination.complete();
13425         }
13426     };
13427     ThrottleTimeSubscriber.prototype.clearThrottle = function () {
13428         var throttled = this.throttled;
13429         if (throttled) {
13430             if (this.trailing && this._hasTrailingValue) {
13431                 this.destination.next(this._trailingValue);
13432                 this._trailingValue = null;
13433                 this._hasTrailingValue = false;
13434             }
13435             throttled.unsubscribe();
13436             this.remove(throttled);
13437             this.throttled = null;
13438         }
13439     };
13440     return ThrottleTimeSubscriber;
13441 }(Subscriber_1.Subscriber));
13442 function dispatchNext(arg) {
13443     var subscriber = arg.subscriber;
13444     subscriber.clearThrottle();
13445 }
13446
13447 },{"../Subscriber":38,"../scheduler/async":187,"./throttle":159}],161:[function(require,module,exports){
13448 "use strict";
13449 Object.defineProperty(exports, "__esModule", { value: true });
13450 var tap_1 = require("./tap");
13451 var EmptyError_1 = require("../util/EmptyError");
13452 exports.throwIfEmpty = function (errorFactory) {
13453     if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
13454     return tap_1.tap({
13455         hasValue: false,
13456         next: function () { this.hasValue = true; },
13457         complete: function () {
13458             if (!this.hasValue) {
13459                 throw errorFactory();
13460             }
13461         }
13462     });
13463 };
13464 function defaultErrorFactory() {
13465     return new EmptyError_1.EmptyError();
13466 }
13467
13468 },{"../util/EmptyError":193,"./tap":158}],162:[function(require,module,exports){
13469 "use strict";
13470 Object.defineProperty(exports, "__esModule", { value: true });
13471 var async_1 = require("../scheduler/async");
13472 var scan_1 = require("./scan");
13473 var defer_1 = require("../observable/defer");
13474 var map_1 = require("./map");
13475 function timeInterval(scheduler) {
13476     if (scheduler === void 0) { scheduler = async_1.async; }
13477     return function (source) { return defer_1.defer(function () {
13478         return source.pipe(scan_1.scan(function (_a, value) {
13479             var current = _a.current;
13480             return ({ value: value, current: scheduler.now(), last: current });
13481         }, { current: scheduler.now(), value: undefined, last: undefined }), map_1.map(function (_a) {
13482             var current = _a.current, last = _a.last, value = _a.value;
13483             return new TimeInterval(value, current - last);
13484         }));
13485     }); };
13486 }
13487 exports.timeInterval = timeInterval;
13488 var TimeInterval = (function () {
13489     function TimeInterval(value, interval) {
13490         this.value = value;
13491         this.interval = interval;
13492     }
13493     return TimeInterval;
13494 }());
13495 exports.TimeInterval = TimeInterval;
13496
13497 },{"../observable/defer":47,"../scheduler/async":187,"./map":111,"./scan":140}],163:[function(require,module,exports){
13498 "use strict";
13499 Object.defineProperty(exports, "__esModule", { value: true });
13500 var async_1 = require("../scheduler/async");
13501 var TimeoutError_1 = require("../util/TimeoutError");
13502 var timeoutWith_1 = require("./timeoutWith");
13503 var throwError_1 = require("../observable/throwError");
13504 function timeout(due, scheduler) {
13505     if (scheduler === void 0) { scheduler = async_1.async; }
13506     return timeoutWith_1.timeoutWith(due, throwError_1.throwError(new TimeoutError_1.TimeoutError()), scheduler);
13507 }
13508 exports.timeout = timeout;
13509
13510 },{"../observable/throwError":68,"../scheduler/async":187,"../util/TimeoutError":196,"./timeoutWith":164}],164:[function(require,module,exports){
13511 "use strict";
13512 var __extends = (this && this.__extends) || (function () {
13513     var extendStatics = function (d, b) {
13514         extendStatics = Object.setPrototypeOf ||
13515             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13516             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13517         return extendStatics(d, b);
13518     }
13519     return function (d, b) {
13520         extendStatics(d, b);
13521         function __() { this.constructor = d; }
13522         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13523     };
13524 })();
13525 Object.defineProperty(exports, "__esModule", { value: true });
13526 var async_1 = require("../scheduler/async");
13527 var isDate_1 = require("../util/isDate");
13528 var OuterSubscriber_1 = require("../OuterSubscriber");
13529 var subscribeToResult_1 = require("../util/subscribeToResult");
13530 function timeoutWith(due, withObservable, scheduler) {
13531     if (scheduler === void 0) { scheduler = async_1.async; }
13532     return function (source) {
13533         var absoluteTimeout = isDate_1.isDate(due);
13534         var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
13535         return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));
13536     };
13537 }
13538 exports.timeoutWith = timeoutWith;
13539 var TimeoutWithOperator = (function () {
13540     function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) {
13541         this.waitFor = waitFor;
13542         this.absoluteTimeout = absoluteTimeout;
13543         this.withObservable = withObservable;
13544         this.scheduler = scheduler;
13545     }
13546     TimeoutWithOperator.prototype.call = function (subscriber, source) {
13547         return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler));
13548     };
13549     return TimeoutWithOperator;
13550 }());
13551 var TimeoutWithSubscriber = (function (_super) {
13552     __extends(TimeoutWithSubscriber, _super);
13553     function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) {
13554         var _this = _super.call(this, destination) || this;
13555         _this.absoluteTimeout = absoluteTimeout;
13556         _this.waitFor = waitFor;
13557         _this.withObservable = withObservable;
13558         _this.scheduler = scheduler;
13559         _this.action = null;
13560         _this.scheduleTimeout();
13561         return _this;
13562     }
13563     TimeoutWithSubscriber.dispatchTimeout = function (subscriber) {
13564         var withObservable = subscriber.withObservable;
13565         subscriber._unsubscribeAndRecycle();
13566         subscriber.add(subscribeToResult_1.subscribeToResult(subscriber, withObservable));
13567     };
13568     TimeoutWithSubscriber.prototype.scheduleTimeout = function () {
13569         var action = this.action;
13570         if (action) {
13571             this.action = action.schedule(this, this.waitFor);
13572         }
13573         else {
13574             this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this));
13575         }
13576     };
13577     TimeoutWithSubscriber.prototype._next = function (value) {
13578         if (!this.absoluteTimeout) {
13579             this.scheduleTimeout();
13580         }
13581         _super.prototype._next.call(this, value);
13582     };
13583     TimeoutWithSubscriber.prototype._unsubscribe = function () {
13584         this.action = null;
13585         this.scheduler = null;
13586         this.withObservable = null;
13587     };
13588     return TimeoutWithSubscriber;
13589 }(OuterSubscriber_1.OuterSubscriber));
13590
13591 },{"../OuterSubscriber":33,"../scheduler/async":187,"../util/isDate":204,"../util/subscribeToResult":221}],165:[function(require,module,exports){
13592 "use strict";
13593 Object.defineProperty(exports, "__esModule", { value: true });
13594 var async_1 = require("../scheduler/async");
13595 var map_1 = require("./map");
13596 function timestamp(scheduler) {
13597     if (scheduler === void 0) { scheduler = async_1.async; }
13598     return map_1.map(function (value) { return new Timestamp(value, scheduler.now()); });
13599 }
13600 exports.timestamp = timestamp;
13601 var Timestamp = (function () {
13602     function Timestamp(value, timestamp) {
13603         this.value = value;
13604         this.timestamp = timestamp;
13605     }
13606     return Timestamp;
13607 }());
13608 exports.Timestamp = Timestamp;
13609
13610 },{"../scheduler/async":187,"./map":111}],166:[function(require,module,exports){
13611 "use strict";
13612 Object.defineProperty(exports, "__esModule", { value: true });
13613 var reduce_1 = require("./reduce");
13614 function toArrayReducer(arr, item, index) {
13615     if (index === 0) {
13616         return [item];
13617     }
13618     arr.push(item);
13619     return arr;
13620 }
13621 function toArray() {
13622     return reduce_1.reduce(toArrayReducer, []);
13623 }
13624 exports.toArray = toArray;
13625
13626 },{"./reduce":132}],167:[function(require,module,exports){
13627 "use strict";
13628 var __extends = (this && this.__extends) || (function () {
13629     var extendStatics = function (d, b) {
13630         extendStatics = Object.setPrototypeOf ||
13631             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13632             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13633         return extendStatics(d, b);
13634     }
13635     return function (d, b) {
13636         extendStatics(d, b);
13637         function __() { this.constructor = d; }
13638         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13639     };
13640 })();
13641 Object.defineProperty(exports, "__esModule", { value: true });
13642 var Subject_1 = require("../Subject");
13643 var OuterSubscriber_1 = require("../OuterSubscriber");
13644 var subscribeToResult_1 = require("../util/subscribeToResult");
13645 function window(windowBoundaries) {
13646     return function windowOperatorFunction(source) {
13647         return source.lift(new WindowOperator(windowBoundaries));
13648     };
13649 }
13650 exports.window = window;
13651 var WindowOperator = (function () {
13652     function WindowOperator(windowBoundaries) {
13653         this.windowBoundaries = windowBoundaries;
13654     }
13655     WindowOperator.prototype.call = function (subscriber, source) {
13656         var windowSubscriber = new WindowSubscriber(subscriber);
13657         var sourceSubscription = source.subscribe(windowSubscriber);
13658         if (!sourceSubscription.closed) {
13659             windowSubscriber.add(subscribeToResult_1.subscribeToResult(windowSubscriber, this.windowBoundaries));
13660         }
13661         return sourceSubscription;
13662     };
13663     return WindowOperator;
13664 }());
13665 var WindowSubscriber = (function (_super) {
13666     __extends(WindowSubscriber, _super);
13667     function WindowSubscriber(destination) {
13668         var _this = _super.call(this, destination) || this;
13669         _this.window = new Subject_1.Subject();
13670         destination.next(_this.window);
13671         return _this;
13672     }
13673     WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13674         this.openWindow();
13675     };
13676     WindowSubscriber.prototype.notifyError = function (error, innerSub) {
13677         this._error(error);
13678     };
13679     WindowSubscriber.prototype.notifyComplete = function (innerSub) {
13680         this._complete();
13681     };
13682     WindowSubscriber.prototype._next = function (value) {
13683         this.window.next(value);
13684     };
13685     WindowSubscriber.prototype._error = function (err) {
13686         this.window.error(err);
13687         this.destination.error(err);
13688     };
13689     WindowSubscriber.prototype._complete = function () {
13690         this.window.complete();
13691         this.destination.complete();
13692     };
13693     WindowSubscriber.prototype._unsubscribe = function () {
13694         this.window = null;
13695     };
13696     WindowSubscriber.prototype.openWindow = function () {
13697         var prevWindow = this.window;
13698         if (prevWindow) {
13699             prevWindow.complete();
13700         }
13701         var destination = this.destination;
13702         var newWindow = this.window = new Subject_1.Subject();
13703         destination.next(newWindow);
13704     };
13705     return WindowSubscriber;
13706 }(OuterSubscriber_1.OuterSubscriber));
13707
13708 },{"../OuterSubscriber":33,"../Subject":36,"../util/subscribeToResult":221}],168:[function(require,module,exports){
13709 "use strict";
13710 var __extends = (this && this.__extends) || (function () {
13711     var extendStatics = function (d, b) {
13712         extendStatics = Object.setPrototypeOf ||
13713             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13714             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13715         return extendStatics(d, b);
13716     }
13717     return function (d, b) {
13718         extendStatics(d, b);
13719         function __() { this.constructor = d; }
13720         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13721     };
13722 })();
13723 Object.defineProperty(exports, "__esModule", { value: true });
13724 var Subscriber_1 = require("../Subscriber");
13725 var Subject_1 = require("../Subject");
13726 function windowCount(windowSize, startWindowEvery) {
13727     if (startWindowEvery === void 0) { startWindowEvery = 0; }
13728     return function windowCountOperatorFunction(source) {
13729         return source.lift(new WindowCountOperator(windowSize, startWindowEvery));
13730     };
13731 }
13732 exports.windowCount = windowCount;
13733 var WindowCountOperator = (function () {
13734     function WindowCountOperator(windowSize, startWindowEvery) {
13735         this.windowSize = windowSize;
13736         this.startWindowEvery = startWindowEvery;
13737     }
13738     WindowCountOperator.prototype.call = function (subscriber, source) {
13739         return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery));
13740     };
13741     return WindowCountOperator;
13742 }());
13743 var WindowCountSubscriber = (function (_super) {
13744     __extends(WindowCountSubscriber, _super);
13745     function WindowCountSubscriber(destination, windowSize, startWindowEvery) {
13746         var _this = _super.call(this, destination) || this;
13747         _this.destination = destination;
13748         _this.windowSize = windowSize;
13749         _this.startWindowEvery = startWindowEvery;
13750         _this.windows = [new Subject_1.Subject()];
13751         _this.count = 0;
13752         destination.next(_this.windows[0]);
13753         return _this;
13754     }
13755     WindowCountSubscriber.prototype._next = function (value) {
13756         var startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize;
13757         var destination = this.destination;
13758         var windowSize = this.windowSize;
13759         var windows = this.windows;
13760         var len = windows.length;
13761         for (var i = 0; i < len && !this.closed; i++) {
13762             windows[i].next(value);
13763         }
13764         var c = this.count - windowSize + 1;
13765         if (c >= 0 && c % startWindowEvery === 0 && !this.closed) {
13766             windows.shift().complete();
13767         }
13768         if (++this.count % startWindowEvery === 0 && !this.closed) {
13769             var window_1 = new Subject_1.Subject();
13770             windows.push(window_1);
13771             destination.next(window_1);
13772         }
13773     };
13774     WindowCountSubscriber.prototype._error = function (err) {
13775         var windows = this.windows;
13776         if (windows) {
13777             while (windows.length > 0 && !this.closed) {
13778                 windows.shift().error(err);
13779             }
13780         }
13781         this.destination.error(err);
13782     };
13783     WindowCountSubscriber.prototype._complete = function () {
13784         var windows = this.windows;
13785         if (windows) {
13786             while (windows.length > 0 && !this.closed) {
13787                 windows.shift().complete();
13788             }
13789         }
13790         this.destination.complete();
13791     };
13792     WindowCountSubscriber.prototype._unsubscribe = function () {
13793         this.count = 0;
13794         this.windows = null;
13795     };
13796     return WindowCountSubscriber;
13797 }(Subscriber_1.Subscriber));
13798
13799 },{"../Subject":36,"../Subscriber":38}],169:[function(require,module,exports){
13800 "use strict";
13801 var __extends = (this && this.__extends) || (function () {
13802     var extendStatics = function (d, b) {
13803         extendStatics = Object.setPrototypeOf ||
13804             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13805             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13806         return extendStatics(d, b);
13807     }
13808     return function (d, b) {
13809         extendStatics(d, b);
13810         function __() { this.constructor = d; }
13811         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13812     };
13813 })();
13814 Object.defineProperty(exports, "__esModule", { value: true });
13815 var Subject_1 = require("../Subject");
13816 var async_1 = require("../scheduler/async");
13817 var Subscriber_1 = require("../Subscriber");
13818 var isNumeric_1 = require("../util/isNumeric");
13819 var isScheduler_1 = require("../util/isScheduler");
13820 function windowTime(windowTimeSpan) {
13821     var scheduler = async_1.async;
13822     var windowCreationInterval = null;
13823     var maxWindowSize = Number.POSITIVE_INFINITY;
13824     if (isScheduler_1.isScheduler(arguments[3])) {
13825         scheduler = arguments[3];
13826     }
13827     if (isScheduler_1.isScheduler(arguments[2])) {
13828         scheduler = arguments[2];
13829     }
13830     else if (isNumeric_1.isNumeric(arguments[2])) {
13831         maxWindowSize = arguments[2];
13832     }
13833     if (isScheduler_1.isScheduler(arguments[1])) {
13834         scheduler = arguments[1];
13835     }
13836     else if (isNumeric_1.isNumeric(arguments[1])) {
13837         windowCreationInterval = arguments[1];
13838     }
13839     return function windowTimeOperatorFunction(source) {
13840         return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler));
13841     };
13842 }
13843 exports.windowTime = windowTime;
13844 var WindowTimeOperator = (function () {
13845     function WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
13846         this.windowTimeSpan = windowTimeSpan;
13847         this.windowCreationInterval = windowCreationInterval;
13848         this.maxWindowSize = maxWindowSize;
13849         this.scheduler = scheduler;
13850     }
13851     WindowTimeOperator.prototype.call = function (subscriber, source) {
13852         return source.subscribe(new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler));
13853     };
13854     return WindowTimeOperator;
13855 }());
13856 var CountedSubject = (function (_super) {
13857     __extends(CountedSubject, _super);
13858     function CountedSubject() {
13859         var _this = _super !== null && _super.apply(this, arguments) || this;
13860         _this._numberOfNextedValues = 0;
13861         return _this;
13862     }
13863     CountedSubject.prototype.next = function (value) {
13864         this._numberOfNextedValues++;
13865         _super.prototype.next.call(this, value);
13866     };
13867     Object.defineProperty(CountedSubject.prototype, "numberOfNextedValues", {
13868         get: function () {
13869             return this._numberOfNextedValues;
13870         },
13871         enumerable: true,
13872         configurable: true
13873     });
13874     return CountedSubject;
13875 }(Subject_1.Subject));
13876 var WindowTimeSubscriber = (function (_super) {
13877     __extends(WindowTimeSubscriber, _super);
13878     function WindowTimeSubscriber(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
13879         var _this = _super.call(this, destination) || this;
13880         _this.destination = destination;
13881         _this.windowTimeSpan = windowTimeSpan;
13882         _this.windowCreationInterval = windowCreationInterval;
13883         _this.maxWindowSize = maxWindowSize;
13884         _this.scheduler = scheduler;
13885         _this.windows = [];
13886         var window = _this.openWindow();
13887         if (windowCreationInterval !== null && windowCreationInterval >= 0) {
13888             var closeState = { subscriber: _this, window: window, context: null };
13889             var creationState = { windowTimeSpan: windowTimeSpan, windowCreationInterval: windowCreationInterval, subscriber: _this, scheduler: scheduler };
13890             _this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState));
13891             _this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState));
13892         }
13893         else {
13894             var timeSpanOnlyState = { subscriber: _this, window: window, windowTimeSpan: windowTimeSpan };
13895             _this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState));
13896         }
13897         return _this;
13898     }
13899     WindowTimeSubscriber.prototype._next = function (value) {
13900         var windows = this.windows;
13901         var len = windows.length;
13902         for (var i = 0; i < len; i++) {
13903             var window_1 = windows[i];
13904             if (!window_1.closed) {
13905                 window_1.next(value);
13906                 if (window_1.numberOfNextedValues >= this.maxWindowSize) {
13907                     this.closeWindow(window_1);
13908                 }
13909             }
13910         }
13911     };
13912     WindowTimeSubscriber.prototype._error = function (err) {
13913         var windows = this.windows;
13914         while (windows.length > 0) {
13915             windows.shift().error(err);
13916         }
13917         this.destination.error(err);
13918     };
13919     WindowTimeSubscriber.prototype._complete = function () {
13920         var windows = this.windows;
13921         while (windows.length > 0) {
13922             var window_2 = windows.shift();
13923             if (!window_2.closed) {
13924                 window_2.complete();
13925             }
13926         }
13927         this.destination.complete();
13928     };
13929     WindowTimeSubscriber.prototype.openWindow = function () {
13930         var window = new CountedSubject();
13931         this.windows.push(window);
13932         var destination = this.destination;
13933         destination.next(window);
13934         return window;
13935     };
13936     WindowTimeSubscriber.prototype.closeWindow = function (window) {
13937         window.complete();
13938         var windows = this.windows;
13939         windows.splice(windows.indexOf(window), 1);
13940     };
13941     return WindowTimeSubscriber;
13942 }(Subscriber_1.Subscriber));
13943 function dispatchWindowTimeSpanOnly(state) {
13944     var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, window = state.window;
13945     if (window) {
13946         subscriber.closeWindow(window);
13947     }
13948     state.window = subscriber.openWindow();
13949     this.schedule(state, windowTimeSpan);
13950 }
13951 function dispatchWindowCreation(state) {
13952     var windowTimeSpan = state.windowTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler, windowCreationInterval = state.windowCreationInterval;
13953     var window = subscriber.openWindow();
13954     var action = this;
13955     var context = { action: action, subscription: null };
13956     var timeSpanState = { subscriber: subscriber, window: window, context: context };
13957     context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState);
13958     action.add(context.subscription);
13959     action.schedule(state, windowCreationInterval);
13960 }
13961 function dispatchWindowClose(state) {
13962     var subscriber = state.subscriber, window = state.window, context = state.context;
13963     if (context && context.action && context.subscription) {
13964         context.action.remove(context.subscription);
13965     }
13966     subscriber.closeWindow(window);
13967 }
13968
13969 },{"../Subject":36,"../Subscriber":38,"../scheduler/async":187,"../util/isNumeric":208,"../util/isScheduler":212}],170:[function(require,module,exports){
13970 "use strict";
13971 var __extends = (this && this.__extends) || (function () {
13972     var extendStatics = function (d, b) {
13973         extendStatics = Object.setPrototypeOf ||
13974             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13975             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13976         return extendStatics(d, b);
13977     }
13978     return function (d, b) {
13979         extendStatics(d, b);
13980         function __() { this.constructor = d; }
13981         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13982     };
13983 })();
13984 Object.defineProperty(exports, "__esModule", { value: true });
13985 var Subject_1 = require("../Subject");
13986 var Subscription_1 = require("../Subscription");
13987 var tryCatch_1 = require("../util/tryCatch");
13988 var errorObject_1 = require("../util/errorObject");
13989 var OuterSubscriber_1 = require("../OuterSubscriber");
13990 var subscribeToResult_1 = require("../util/subscribeToResult");
13991 function windowToggle(openings, closingSelector) {
13992     return function (source) { return source.lift(new WindowToggleOperator(openings, closingSelector)); };
13993 }
13994 exports.windowToggle = windowToggle;
13995 var WindowToggleOperator = (function () {
13996     function WindowToggleOperator(openings, closingSelector) {
13997         this.openings = openings;
13998         this.closingSelector = closingSelector;
13999     }
14000     WindowToggleOperator.prototype.call = function (subscriber, source) {
14001         return source.subscribe(new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector));
14002     };
14003     return WindowToggleOperator;
14004 }());
14005 var WindowToggleSubscriber = (function (_super) {
14006     __extends(WindowToggleSubscriber, _super);
14007     function WindowToggleSubscriber(destination, openings, closingSelector) {
14008         var _this = _super.call(this, destination) || this;
14009         _this.openings = openings;
14010         _this.closingSelector = closingSelector;
14011         _this.contexts = [];
14012         _this.add(_this.openSubscription = subscribeToResult_1.subscribeToResult(_this, openings, openings));
14013         return _this;
14014     }
14015     WindowToggleSubscriber.prototype._next = function (value) {
14016         var contexts = this.contexts;
14017         if (contexts) {
14018             var len = contexts.length;
14019             for (var i = 0; i < len; i++) {
14020                 contexts[i].window.next(value);
14021             }
14022         }
14023     };
14024     WindowToggleSubscriber.prototype._error = function (err) {
14025         var contexts = this.contexts;
14026         this.contexts = null;
14027         if (contexts) {
14028             var len = contexts.length;
14029             var index = -1;
14030             while (++index < len) {
14031                 var context_1 = contexts[index];
14032                 context_1.window.error(err);
14033                 context_1.subscription.unsubscribe();
14034             }
14035         }
14036         _super.prototype._error.call(this, err);
14037     };
14038     WindowToggleSubscriber.prototype._complete = function () {
14039         var contexts = this.contexts;
14040         this.contexts = null;
14041         if (contexts) {
14042             var len = contexts.length;
14043             var index = -1;
14044             while (++index < len) {
14045                 var context_2 = contexts[index];
14046                 context_2.window.complete();
14047                 context_2.subscription.unsubscribe();
14048             }
14049         }
14050         _super.prototype._complete.call(this);
14051     };
14052     WindowToggleSubscriber.prototype._unsubscribe = function () {
14053         var contexts = this.contexts;
14054         this.contexts = null;
14055         if (contexts) {
14056             var len = contexts.length;
14057             var index = -1;
14058             while (++index < len) {
14059                 var context_3 = contexts[index];
14060                 context_3.window.unsubscribe();
14061                 context_3.subscription.unsubscribe();
14062             }
14063         }
14064     };
14065     WindowToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14066         if (outerValue === this.openings) {
14067             var closingSelector = this.closingSelector;
14068             var closingNotifier = tryCatch_1.tryCatch(closingSelector)(innerValue);
14069             if (closingNotifier === errorObject_1.errorObject) {
14070                 return this.error(errorObject_1.errorObject.e);
14071             }
14072             else {
14073                 var window_1 = new Subject_1.Subject();
14074                 var subscription = new Subscription_1.Subscription();
14075                 var context_4 = { window: window_1, subscription: subscription };
14076                 this.contexts.push(context_4);
14077                 var innerSubscription = subscribeToResult_1.subscribeToResult(this, closingNotifier, context_4);
14078                 if (innerSubscription.closed) {
14079                     this.closeWindow(this.contexts.length - 1);
14080                 }
14081                 else {
14082                     innerSubscription.context = context_4;
14083                     subscription.add(innerSubscription);
14084                 }
14085                 this.destination.next(window_1);
14086             }
14087         }
14088         else {
14089             this.closeWindow(this.contexts.indexOf(outerValue));
14090         }
14091     };
14092     WindowToggleSubscriber.prototype.notifyError = function (err) {
14093         this.error(err);
14094     };
14095     WindowToggleSubscriber.prototype.notifyComplete = function (inner) {
14096         if (inner !== this.openSubscription) {
14097             this.closeWindow(this.contexts.indexOf(inner.context));
14098         }
14099     };
14100     WindowToggleSubscriber.prototype.closeWindow = function (index) {
14101         if (index === -1) {
14102             return;
14103         }
14104         var contexts = this.contexts;
14105         var context = contexts[index];
14106         var window = context.window, subscription = context.subscription;
14107         contexts.splice(index, 1);
14108         window.complete();
14109         subscription.unsubscribe();
14110     };
14111     return WindowToggleSubscriber;
14112 }(OuterSubscriber_1.OuterSubscriber));
14113
14114 },{"../OuterSubscriber":33,"../Subject":36,"../Subscription":39,"../util/errorObject":199,"../util/subscribeToResult":221,"../util/tryCatch":223}],171:[function(require,module,exports){
14115 "use strict";
14116 var __extends = (this && this.__extends) || (function () {
14117     var extendStatics = function (d, b) {
14118         extendStatics = Object.setPrototypeOf ||
14119             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14120             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14121         return extendStatics(d, b);
14122     }
14123     return function (d, b) {
14124         extendStatics(d, b);
14125         function __() { this.constructor = d; }
14126         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14127     };
14128 })();
14129 Object.defineProperty(exports, "__esModule", { value: true });
14130 var Subject_1 = require("../Subject");
14131 var tryCatch_1 = require("../util/tryCatch");
14132 var errorObject_1 = require("../util/errorObject");
14133 var OuterSubscriber_1 = require("../OuterSubscriber");
14134 var subscribeToResult_1 = require("../util/subscribeToResult");
14135 function windowWhen(closingSelector) {
14136     return function windowWhenOperatorFunction(source) {
14137         return source.lift(new WindowOperator(closingSelector));
14138     };
14139 }
14140 exports.windowWhen = windowWhen;
14141 var WindowOperator = (function () {
14142     function WindowOperator(closingSelector) {
14143         this.closingSelector = closingSelector;
14144     }
14145     WindowOperator.prototype.call = function (subscriber, source) {
14146         return source.subscribe(new WindowSubscriber(subscriber, this.closingSelector));
14147     };
14148     return WindowOperator;
14149 }());
14150 var WindowSubscriber = (function (_super) {
14151     __extends(WindowSubscriber, _super);
14152     function WindowSubscriber(destination, closingSelector) {
14153         var _this = _super.call(this, destination) || this;
14154         _this.destination = destination;
14155         _this.closingSelector = closingSelector;
14156         _this.openWindow();
14157         return _this;
14158     }
14159     WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14160         this.openWindow(innerSub);
14161     };
14162     WindowSubscriber.prototype.notifyError = function (error, innerSub) {
14163         this._error(error);
14164     };
14165     WindowSubscriber.prototype.notifyComplete = function (innerSub) {
14166         this.openWindow(innerSub);
14167     };
14168     WindowSubscriber.prototype._next = function (value) {
14169         this.window.next(value);
14170     };
14171     WindowSubscriber.prototype._error = function (err) {
14172         this.window.error(err);
14173         this.destination.error(err);
14174         this.unsubscribeClosingNotification();
14175     };
14176     WindowSubscriber.prototype._complete = function () {
14177         this.window.complete();
14178         this.destination.complete();
14179         this.unsubscribeClosingNotification();
14180     };
14181     WindowSubscriber.prototype.unsubscribeClosingNotification = function () {
14182         if (this.closingNotification) {
14183             this.closingNotification.unsubscribe();
14184         }
14185     };
14186     WindowSubscriber.prototype.openWindow = function (innerSub) {
14187         if (innerSub === void 0) { innerSub = null; }
14188         if (innerSub) {
14189             this.remove(innerSub);
14190             innerSub.unsubscribe();
14191         }
14192         var prevWindow = this.window;
14193         if (prevWindow) {
14194             prevWindow.complete();
14195         }
14196         var window = this.window = new Subject_1.Subject();
14197         this.destination.next(window);
14198         var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
14199         if (closingNotifier === errorObject_1.errorObject) {
14200             var err = errorObject_1.errorObject.e;
14201             this.destination.error(err);
14202             this.window.error(err);
14203         }
14204         else {
14205             this.add(this.closingNotification = subscribeToResult_1.subscribeToResult(this, closingNotifier));
14206         }
14207     };
14208     return WindowSubscriber;
14209 }(OuterSubscriber_1.OuterSubscriber));
14210
14211 },{"../OuterSubscriber":33,"../Subject":36,"../util/errorObject":199,"../util/subscribeToResult":221,"../util/tryCatch":223}],172:[function(require,module,exports){
14212 "use strict";
14213 var __extends = (this && this.__extends) || (function () {
14214     var extendStatics = function (d, b) {
14215         extendStatics = Object.setPrototypeOf ||
14216             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14217             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14218         return extendStatics(d, b);
14219     }
14220     return function (d, b) {
14221         extendStatics(d, b);
14222         function __() { this.constructor = d; }
14223         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14224     };
14225 })();
14226 Object.defineProperty(exports, "__esModule", { value: true });
14227 var OuterSubscriber_1 = require("../OuterSubscriber");
14228 var subscribeToResult_1 = require("../util/subscribeToResult");
14229 function withLatestFrom() {
14230     var args = [];
14231     for (var _i = 0; _i < arguments.length; _i++) {
14232         args[_i] = arguments[_i];
14233     }
14234     return function (source) {
14235         var project;
14236         if (typeof args[args.length - 1] === 'function') {
14237             project = args.pop();
14238         }
14239         var observables = args;
14240         return source.lift(new WithLatestFromOperator(observables, project));
14241     };
14242 }
14243 exports.withLatestFrom = withLatestFrom;
14244 var WithLatestFromOperator = (function () {
14245     function WithLatestFromOperator(observables, project) {
14246         this.observables = observables;
14247         this.project = project;
14248     }
14249     WithLatestFromOperator.prototype.call = function (subscriber, source) {
14250         return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
14251     };
14252     return WithLatestFromOperator;
14253 }());
14254 var WithLatestFromSubscriber = (function (_super) {
14255     __extends(WithLatestFromSubscriber, _super);
14256     function WithLatestFromSubscriber(destination, observables, project) {
14257         var _this = _super.call(this, destination) || this;
14258         _this.observables = observables;
14259         _this.project = project;
14260         _this.toRespond = [];
14261         var len = observables.length;
14262         _this.values = new Array(len);
14263         for (var i = 0; i < len; i++) {
14264             _this.toRespond.push(i);
14265         }
14266         for (var i = 0; i < len; i++) {
14267             var observable = observables[i];
14268             _this.add(subscribeToResult_1.subscribeToResult(_this, observable, observable, i));
14269         }
14270         return _this;
14271     }
14272     WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14273         this.values[outerIndex] = innerValue;
14274         var toRespond = this.toRespond;
14275         if (toRespond.length > 0) {
14276             var found = toRespond.indexOf(outerIndex);
14277             if (found !== -1) {
14278                 toRespond.splice(found, 1);
14279             }
14280         }
14281     };
14282     WithLatestFromSubscriber.prototype.notifyComplete = function () {
14283     };
14284     WithLatestFromSubscriber.prototype._next = function (value) {
14285         if (this.toRespond.length === 0) {
14286             var args = [value].concat(this.values);
14287             if (this.project) {
14288                 this._tryProject(args);
14289             }
14290             else {
14291                 this.destination.next(args);
14292             }
14293         }
14294     };
14295     WithLatestFromSubscriber.prototype._tryProject = function (args) {
14296         var result;
14297         try {
14298             result = this.project.apply(this, args);
14299         }
14300         catch (err) {
14301             this.destination.error(err);
14302             return;
14303         }
14304         this.destination.next(result);
14305     };
14306     return WithLatestFromSubscriber;
14307 }(OuterSubscriber_1.OuterSubscriber));
14308
14309 },{"../OuterSubscriber":33,"../util/subscribeToResult":221}],173:[function(require,module,exports){
14310 "use strict";
14311 Object.defineProperty(exports, "__esModule", { value: true });
14312 var zip_1 = require("../observable/zip");
14313 function zip() {
14314     var observables = [];
14315     for (var _i = 0; _i < arguments.length; _i++) {
14316         observables[_i] = arguments[_i];
14317     }
14318     return function zipOperatorFunction(source) {
14319         return source.lift.call(zip_1.zip.apply(void 0, [source].concat(observables)));
14320     };
14321 }
14322 exports.zip = zip;
14323
14324 },{"../observable/zip":71}],174:[function(require,module,exports){
14325 "use strict";
14326 Object.defineProperty(exports, "__esModule", { value: true });
14327 var zip_1 = require("../observable/zip");
14328 function zipAll(project) {
14329     return function (source) { return source.lift(new zip_1.ZipOperator(project)); };
14330 }
14331 exports.zipAll = zipAll;
14332
14333 },{"../observable/zip":71}],175:[function(require,module,exports){
14334 "use strict";
14335 var __extends = (this && this.__extends) || (function () {
14336     var extendStatics = function (d, b) {
14337         extendStatics = Object.setPrototypeOf ||
14338             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14339             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14340         return extendStatics(d, b);
14341     }
14342     return function (d, b) {
14343         extendStatics(d, b);
14344         function __() { this.constructor = d; }
14345         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14346     };
14347 })();
14348 Object.defineProperty(exports, "__esModule", { value: true });
14349 var Subscription_1 = require("../Subscription");
14350 var Action = (function (_super) {
14351     __extends(Action, _super);
14352     function Action(scheduler, work) {
14353         return _super.call(this) || this;
14354     }
14355     Action.prototype.schedule = function (state, delay) {
14356         if (delay === void 0) { delay = 0; }
14357         return this;
14358     };
14359     return Action;
14360 }(Subscription_1.Subscription));
14361 exports.Action = Action;
14362
14363 },{"../Subscription":39}],176:[function(require,module,exports){
14364 "use strict";
14365 var __extends = (this && this.__extends) || (function () {
14366     var extendStatics = function (d, b) {
14367         extendStatics = Object.setPrototypeOf ||
14368             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14369             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14370         return extendStatics(d, b);
14371     }
14372     return function (d, b) {
14373         extendStatics(d, b);
14374         function __() { this.constructor = d; }
14375         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14376     };
14377 })();
14378 Object.defineProperty(exports, "__esModule", { value: true });
14379 var AsyncAction_1 = require("./AsyncAction");
14380 var AnimationFrameAction = (function (_super) {
14381     __extends(AnimationFrameAction, _super);
14382     function AnimationFrameAction(scheduler, work) {
14383         var _this = _super.call(this, scheduler, work) || this;
14384         _this.scheduler = scheduler;
14385         _this.work = work;
14386         return _this;
14387     }
14388     AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) {
14389         if (delay === void 0) { delay = 0; }
14390         if (delay !== null && delay > 0) {
14391             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
14392         }
14393         scheduler.actions.push(this);
14394         return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(function () { return scheduler.flush(null); }));
14395     };
14396     AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
14397         if (delay === void 0) { delay = 0; }
14398         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
14399             return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
14400         }
14401         if (scheduler.actions.length === 0) {
14402             cancelAnimationFrame(id);
14403             scheduler.scheduled = undefined;
14404         }
14405         return undefined;
14406     };
14407     return AnimationFrameAction;
14408 }(AsyncAction_1.AsyncAction));
14409 exports.AnimationFrameAction = AnimationFrameAction;
14410
14411 },{"./AsyncAction":180}],177:[function(require,module,exports){
14412 "use strict";
14413 var __extends = (this && this.__extends) || (function () {
14414     var extendStatics = function (d, b) {
14415         extendStatics = Object.setPrototypeOf ||
14416             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14417             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14418         return extendStatics(d, b);
14419     }
14420     return function (d, b) {
14421         extendStatics(d, b);
14422         function __() { this.constructor = d; }
14423         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14424     };
14425 })();
14426 Object.defineProperty(exports, "__esModule", { value: true });
14427 var AsyncScheduler_1 = require("./AsyncScheduler");
14428 var AnimationFrameScheduler = (function (_super) {
14429     __extends(AnimationFrameScheduler, _super);
14430     function AnimationFrameScheduler() {
14431         return _super !== null && _super.apply(this, arguments) || this;
14432     }
14433     AnimationFrameScheduler.prototype.flush = function (action) {
14434         this.active = true;
14435         this.scheduled = undefined;
14436         var actions = this.actions;
14437         var error;
14438         var index = -1;
14439         var count = actions.length;
14440         action = action || actions.shift();
14441         do {
14442             if (error = action.execute(action.state, action.delay)) {
14443                 break;
14444             }
14445         } while (++index < count && (action = actions.shift()));
14446         this.active = false;
14447         if (error) {
14448             while (++index < count && (action = actions.shift())) {
14449                 action.unsubscribe();
14450             }
14451             throw error;
14452         }
14453     };
14454     return AnimationFrameScheduler;
14455 }(AsyncScheduler_1.AsyncScheduler));
14456 exports.AnimationFrameScheduler = AnimationFrameScheduler;
14457
14458 },{"./AsyncScheduler":181}],178:[function(require,module,exports){
14459 "use strict";
14460 var __extends = (this && this.__extends) || (function () {
14461     var extendStatics = function (d, b) {
14462         extendStatics = Object.setPrototypeOf ||
14463             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14464             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14465         return extendStatics(d, b);
14466     }
14467     return function (d, b) {
14468         extendStatics(d, b);
14469         function __() { this.constructor = d; }
14470         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14471     };
14472 })();
14473 Object.defineProperty(exports, "__esModule", { value: true });
14474 var Immediate_1 = require("../util/Immediate");
14475 var AsyncAction_1 = require("./AsyncAction");
14476 var AsapAction = (function (_super) {
14477     __extends(AsapAction, _super);
14478     function AsapAction(scheduler, work) {
14479         var _this = _super.call(this, scheduler, work) || this;
14480         _this.scheduler = scheduler;
14481         _this.work = work;
14482         return _this;
14483     }
14484     AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) {
14485         if (delay === void 0) { delay = 0; }
14486         if (delay !== null && delay > 0) {
14487             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
14488         }
14489         scheduler.actions.push(this);
14490         return scheduler.scheduled || (scheduler.scheduled = Immediate_1.Immediate.setImmediate(scheduler.flush.bind(scheduler, null)));
14491     };
14492     AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
14493         if (delay === void 0) { delay = 0; }
14494         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
14495             return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
14496         }
14497         if (scheduler.actions.length === 0) {
14498             Immediate_1.Immediate.clearImmediate(id);
14499             scheduler.scheduled = undefined;
14500         }
14501         return undefined;
14502     };
14503     return AsapAction;
14504 }(AsyncAction_1.AsyncAction));
14505 exports.AsapAction = AsapAction;
14506
14507 },{"../util/Immediate":194,"./AsyncAction":180}],179:[function(require,module,exports){
14508 "use strict";
14509 var __extends = (this && this.__extends) || (function () {
14510     var extendStatics = function (d, b) {
14511         extendStatics = Object.setPrototypeOf ||
14512             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14513             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14514         return extendStatics(d, b);
14515     }
14516     return function (d, b) {
14517         extendStatics(d, b);
14518         function __() { this.constructor = d; }
14519         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14520     };
14521 })();
14522 Object.defineProperty(exports, "__esModule", { value: true });
14523 var AsyncScheduler_1 = require("./AsyncScheduler");
14524 var AsapScheduler = (function (_super) {
14525     __extends(AsapScheduler, _super);
14526     function AsapScheduler() {
14527         return _super !== null && _super.apply(this, arguments) || this;
14528     }
14529     AsapScheduler.prototype.flush = function (action) {
14530         this.active = true;
14531         this.scheduled = undefined;
14532         var actions = this.actions;
14533         var error;
14534         var index = -1;
14535         var count = actions.length;
14536         action = action || actions.shift();
14537         do {
14538             if (error = action.execute(action.state, action.delay)) {
14539                 break;
14540             }
14541         } while (++index < count && (action = actions.shift()));
14542         this.active = false;
14543         if (error) {
14544             while (++index < count && (action = actions.shift())) {
14545                 action.unsubscribe();
14546             }
14547             throw error;
14548         }
14549     };
14550     return AsapScheduler;
14551 }(AsyncScheduler_1.AsyncScheduler));
14552 exports.AsapScheduler = AsapScheduler;
14553
14554 },{"./AsyncScheduler":181}],180:[function(require,module,exports){
14555 "use strict";
14556 var __extends = (this && this.__extends) || (function () {
14557     var extendStatics = function (d, b) {
14558         extendStatics = Object.setPrototypeOf ||
14559             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14560             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14561         return extendStatics(d, b);
14562     }
14563     return function (d, b) {
14564         extendStatics(d, b);
14565         function __() { this.constructor = d; }
14566         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14567     };
14568 })();
14569 Object.defineProperty(exports, "__esModule", { value: true });
14570 var Action_1 = require("./Action");
14571 var AsyncAction = (function (_super) {
14572     __extends(AsyncAction, _super);
14573     function AsyncAction(scheduler, work) {
14574         var _this = _super.call(this, scheduler, work) || this;
14575         _this.scheduler = scheduler;
14576         _this.work = work;
14577         _this.pending = false;
14578         return _this;
14579     }
14580     AsyncAction.prototype.schedule = function (state, delay) {
14581         if (delay === void 0) { delay = 0; }
14582         if (this.closed) {
14583             return this;
14584         }
14585         this.state = state;
14586         var id = this.id;
14587         var scheduler = this.scheduler;
14588         if (id != null) {
14589             this.id = this.recycleAsyncId(scheduler, id, delay);
14590         }
14591         this.pending = true;
14592         this.delay = delay;
14593         this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
14594         return this;
14595     };
14596     AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
14597         if (delay === void 0) { delay = 0; }
14598         return setInterval(scheduler.flush.bind(scheduler, this), delay);
14599     };
14600     AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
14601         if (delay === void 0) { delay = 0; }
14602         if (delay !== null && this.delay === delay && this.pending === false) {
14603             return id;
14604         }
14605         clearInterval(id);
14606     };
14607     AsyncAction.prototype.execute = function (state, delay) {
14608         if (this.closed) {
14609             return new Error('executing a cancelled action');
14610         }
14611         this.pending = false;
14612         var error = this._execute(state, delay);
14613         if (error) {
14614             return error;
14615         }
14616         else if (this.pending === false && this.id != null) {
14617             this.id = this.recycleAsyncId(this.scheduler, this.id, null);
14618         }
14619     };
14620     AsyncAction.prototype._execute = function (state, delay) {
14621         var errored = false;
14622         var errorValue = undefined;
14623         try {
14624             this.work(state);
14625         }
14626         catch (e) {
14627             errored = true;
14628             errorValue = !!e && e || new Error(e);
14629         }
14630         if (errored) {
14631             this.unsubscribe();
14632             return errorValue;
14633         }
14634     };
14635     AsyncAction.prototype._unsubscribe = function () {
14636         var id = this.id;
14637         var scheduler = this.scheduler;
14638         var actions = scheduler.actions;
14639         var index = actions.indexOf(this);
14640         this.work = null;
14641         this.state = null;
14642         this.pending = false;
14643         this.scheduler = null;
14644         if (index !== -1) {
14645             actions.splice(index, 1);
14646         }
14647         if (id != null) {
14648             this.id = this.recycleAsyncId(scheduler, id, null);
14649         }
14650         this.delay = null;
14651     };
14652     return AsyncAction;
14653 }(Action_1.Action));
14654 exports.AsyncAction = AsyncAction;
14655
14656 },{"./Action":175}],181:[function(require,module,exports){
14657 "use strict";
14658 var __extends = (this && this.__extends) || (function () {
14659     var extendStatics = function (d, b) {
14660         extendStatics = Object.setPrototypeOf ||
14661             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14662             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14663         return extendStatics(d, b);
14664     }
14665     return function (d, b) {
14666         extendStatics(d, b);
14667         function __() { this.constructor = d; }
14668         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14669     };
14670 })();
14671 Object.defineProperty(exports, "__esModule", { value: true });
14672 var Scheduler_1 = require("../Scheduler");
14673 var AsyncScheduler = (function (_super) {
14674     __extends(AsyncScheduler, _super);
14675     function AsyncScheduler(SchedulerAction, now) {
14676         if (now === void 0) { now = Scheduler_1.Scheduler.now; }
14677         var _this = _super.call(this, SchedulerAction, function () {
14678             if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) {
14679                 return AsyncScheduler.delegate.now();
14680             }
14681             else {
14682                 return now();
14683             }
14684         }) || this;
14685         _this.actions = [];
14686         _this.active = false;
14687         _this.scheduled = undefined;
14688         return _this;
14689     }
14690     AsyncScheduler.prototype.schedule = function (work, delay, state) {
14691         if (delay === void 0) { delay = 0; }
14692         if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
14693             return AsyncScheduler.delegate.schedule(work, delay, state);
14694         }
14695         else {
14696             return _super.prototype.schedule.call(this, work, delay, state);
14697         }
14698     };
14699     AsyncScheduler.prototype.flush = function (action) {
14700         var actions = this.actions;
14701         if (this.active) {
14702             actions.push(action);
14703             return;
14704         }
14705         var error;
14706         this.active = true;
14707         do {
14708             if (error = action.execute(action.state, action.delay)) {
14709                 break;
14710             }
14711         } while (action = actions.shift());
14712         this.active = false;
14713         if (error) {
14714             while (action = actions.shift()) {
14715                 action.unsubscribe();
14716             }
14717             throw error;
14718         }
14719     };
14720     return AsyncScheduler;
14721 }(Scheduler_1.Scheduler));
14722 exports.AsyncScheduler = AsyncScheduler;
14723
14724 },{"../Scheduler":35}],182:[function(require,module,exports){
14725 "use strict";
14726 var __extends = (this && this.__extends) || (function () {
14727     var extendStatics = function (d, b) {
14728         extendStatics = Object.setPrototypeOf ||
14729             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14730             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14731         return extendStatics(d, b);
14732     }
14733     return function (d, b) {
14734         extendStatics(d, b);
14735         function __() { this.constructor = d; }
14736         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14737     };
14738 })();
14739 Object.defineProperty(exports, "__esModule", { value: true });
14740 var AsyncAction_1 = require("./AsyncAction");
14741 var QueueAction = (function (_super) {
14742     __extends(QueueAction, _super);
14743     function QueueAction(scheduler, work) {
14744         var _this = _super.call(this, scheduler, work) || this;
14745         _this.scheduler = scheduler;
14746         _this.work = work;
14747         return _this;
14748     }
14749     QueueAction.prototype.schedule = function (state, delay) {
14750         if (delay === void 0) { delay = 0; }
14751         if (delay > 0) {
14752             return _super.prototype.schedule.call(this, state, delay);
14753         }
14754         this.delay = delay;
14755         this.state = state;
14756         this.scheduler.flush(this);
14757         return this;
14758     };
14759     QueueAction.prototype.execute = function (state, delay) {
14760         return (delay > 0 || this.closed) ?
14761             _super.prototype.execute.call(this, state, delay) :
14762             this._execute(state, delay);
14763     };
14764     QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
14765         if (delay === void 0) { delay = 0; }
14766         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
14767             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
14768         }
14769         return scheduler.flush(this);
14770     };
14771     return QueueAction;
14772 }(AsyncAction_1.AsyncAction));
14773 exports.QueueAction = QueueAction;
14774
14775 },{"./AsyncAction":180}],183:[function(require,module,exports){
14776 "use strict";
14777 var __extends = (this && this.__extends) || (function () {
14778     var extendStatics = function (d, b) {
14779         extendStatics = Object.setPrototypeOf ||
14780             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14781             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14782         return extendStatics(d, b);
14783     }
14784     return function (d, b) {
14785         extendStatics(d, b);
14786         function __() { this.constructor = d; }
14787         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14788     };
14789 })();
14790 Object.defineProperty(exports, "__esModule", { value: true });
14791 var AsyncScheduler_1 = require("./AsyncScheduler");
14792 var QueueScheduler = (function (_super) {
14793     __extends(QueueScheduler, _super);
14794     function QueueScheduler() {
14795         return _super !== null && _super.apply(this, arguments) || this;
14796     }
14797     return QueueScheduler;
14798 }(AsyncScheduler_1.AsyncScheduler));
14799 exports.QueueScheduler = QueueScheduler;
14800
14801 },{"./AsyncScheduler":181}],184:[function(require,module,exports){
14802 "use strict";
14803 var __extends = (this && this.__extends) || (function () {
14804     var extendStatics = function (d, b) {
14805         extendStatics = Object.setPrototypeOf ||
14806             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14807             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14808         return extendStatics(d, b);
14809     }
14810     return function (d, b) {
14811         extendStatics(d, b);
14812         function __() { this.constructor = d; }
14813         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14814     };
14815 })();
14816 Object.defineProperty(exports, "__esModule", { value: true });
14817 var AsyncAction_1 = require("./AsyncAction");
14818 var AsyncScheduler_1 = require("./AsyncScheduler");
14819 var VirtualTimeScheduler = (function (_super) {
14820     __extends(VirtualTimeScheduler, _super);
14821     function VirtualTimeScheduler(SchedulerAction, maxFrames) {
14822         if (SchedulerAction === void 0) { SchedulerAction = VirtualAction; }
14823         if (maxFrames === void 0) { maxFrames = Number.POSITIVE_INFINITY; }
14824         var _this = _super.call(this, SchedulerAction, function () { return _this.frame; }) || this;
14825         _this.maxFrames = maxFrames;
14826         _this.frame = 0;
14827         _this.index = -1;
14828         return _this;
14829     }
14830     VirtualTimeScheduler.prototype.flush = function () {
14831         var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
14832         var error, action;
14833         while ((action = actions.shift()) && (this.frame = action.delay) <= maxFrames) {
14834             if (error = action.execute(action.state, action.delay)) {
14835                 break;
14836             }
14837         }
14838         if (error) {
14839             while (action = actions.shift()) {
14840                 action.unsubscribe();
14841             }
14842             throw error;
14843         }
14844     };
14845     VirtualTimeScheduler.frameTimeFactor = 10;
14846     return VirtualTimeScheduler;
14847 }(AsyncScheduler_1.AsyncScheduler));
14848 exports.VirtualTimeScheduler = VirtualTimeScheduler;
14849 var VirtualAction = (function (_super) {
14850     __extends(VirtualAction, _super);
14851     function VirtualAction(scheduler, work, index) {
14852         if (index === void 0) { index = scheduler.index += 1; }
14853         var _this = _super.call(this, scheduler, work) || this;
14854         _this.scheduler = scheduler;
14855         _this.work = work;
14856         _this.index = index;
14857         _this.active = true;
14858         _this.index = scheduler.index = index;
14859         return _this;
14860     }
14861     VirtualAction.prototype.schedule = function (state, delay) {
14862         if (delay === void 0) { delay = 0; }
14863         if (!this.id) {
14864             return _super.prototype.schedule.call(this, state, delay);
14865         }
14866         this.active = false;
14867         var action = new VirtualAction(this.scheduler, this.work);
14868         this.add(action);
14869         return action.schedule(state, delay);
14870     };
14871     VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) {
14872         if (delay === void 0) { delay = 0; }
14873         this.delay = scheduler.frame + delay;
14874         var actions = scheduler.actions;
14875         actions.push(this);
14876         actions.sort(VirtualAction.sortActions);
14877         return true;
14878     };
14879     VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
14880         if (delay === void 0) { delay = 0; }
14881         return undefined;
14882     };
14883     VirtualAction.prototype._execute = function (state, delay) {
14884         if (this.active === true) {
14885             return _super.prototype._execute.call(this, state, delay);
14886         }
14887     };
14888     VirtualAction.sortActions = function (a, b) {
14889         if (a.delay === b.delay) {
14890             if (a.index === b.index) {
14891                 return 0;
14892             }
14893             else if (a.index > b.index) {
14894                 return 1;
14895             }
14896             else {
14897                 return -1;
14898             }
14899         }
14900         else if (a.delay > b.delay) {
14901             return 1;
14902         }
14903         else {
14904             return -1;
14905         }
14906     };
14907     return VirtualAction;
14908 }(AsyncAction_1.AsyncAction));
14909 exports.VirtualAction = VirtualAction;
14910
14911 },{"./AsyncAction":180,"./AsyncScheduler":181}],185:[function(require,module,exports){
14912 "use strict";
14913 Object.defineProperty(exports, "__esModule", { value: true });
14914 var AnimationFrameAction_1 = require("./AnimationFrameAction");
14915 var AnimationFrameScheduler_1 = require("./AnimationFrameScheduler");
14916 exports.animationFrame = new AnimationFrameScheduler_1.AnimationFrameScheduler(AnimationFrameAction_1.AnimationFrameAction);
14917
14918 },{"./AnimationFrameAction":176,"./AnimationFrameScheduler":177}],186:[function(require,module,exports){
14919 "use strict";
14920 Object.defineProperty(exports, "__esModule", { value: true });
14921 var AsapAction_1 = require("./AsapAction");
14922 var AsapScheduler_1 = require("./AsapScheduler");
14923 exports.asap = new AsapScheduler_1.AsapScheduler(AsapAction_1.AsapAction);
14924
14925 },{"./AsapAction":178,"./AsapScheduler":179}],187:[function(require,module,exports){
14926 "use strict";
14927 Object.defineProperty(exports, "__esModule", { value: true });
14928 var AsyncAction_1 = require("./AsyncAction");
14929 var AsyncScheduler_1 = require("./AsyncScheduler");
14930 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
14931
14932 },{"./AsyncAction":180,"./AsyncScheduler":181}],188:[function(require,module,exports){
14933 "use strict";
14934 Object.defineProperty(exports, "__esModule", { value: true });
14935 var QueueAction_1 = require("./QueueAction");
14936 var QueueScheduler_1 = require("./QueueScheduler");
14937 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
14938
14939 },{"./QueueAction":182,"./QueueScheduler":183}],189:[function(require,module,exports){
14940 "use strict";
14941 Object.defineProperty(exports, "__esModule", { value: true });
14942 function getSymbolIterator() {
14943     if (typeof Symbol !== 'function' || !Symbol.iterator) {
14944         return '@@iterator';
14945     }
14946     return Symbol.iterator;
14947 }
14948 exports.getSymbolIterator = getSymbolIterator;
14949 exports.iterator = getSymbolIterator();
14950 exports.$$iterator = exports.iterator;
14951
14952 },{}],190:[function(require,module,exports){
14953 "use strict";
14954 Object.defineProperty(exports, "__esModule", { value: true });
14955 exports.observable = typeof Symbol === 'function' && Symbol.observable || '@@observable';
14956
14957 },{}],191:[function(require,module,exports){
14958 "use strict";
14959 Object.defineProperty(exports, "__esModule", { value: true });
14960 exports.rxSubscriber = typeof Symbol === 'function'
14961     ? Symbol('rxSubscriber')
14962     : '@@rxSubscriber_' + Math.random();
14963 exports.$$rxSubscriber = exports.rxSubscriber;
14964
14965 },{}],192:[function(require,module,exports){
14966 "use strict";
14967 Object.defineProperty(exports, "__esModule", { value: true });
14968 function ArgumentOutOfRangeErrorImpl() {
14969     Error.call(this);
14970     this.message = 'argument out of range';
14971     this.name = 'ArgumentOutOfRangeError';
14972     return this;
14973 }
14974 ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);
14975 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;
14976
14977 },{}],193:[function(require,module,exports){
14978 "use strict";
14979 Object.defineProperty(exports, "__esModule", { value: true });
14980 function EmptyErrorImpl() {
14981     Error.call(this);
14982     this.message = 'no elements in sequence';
14983     this.name = 'EmptyError';
14984     return this;
14985 }
14986 EmptyErrorImpl.prototype = Object.create(Error.prototype);
14987 exports.EmptyError = EmptyErrorImpl;
14988
14989 },{}],194:[function(require,module,exports){
14990 "use strict";
14991 Object.defineProperty(exports, "__esModule", { value: true });
14992 var nextHandle = 1;
14993 var tasksByHandle = {};
14994 function runIfPresent(handle) {
14995     var cb = tasksByHandle[handle];
14996     if (cb) {
14997         cb();
14998     }
14999 }
15000 exports.Immediate = {
15001     setImmediate: function (cb) {
15002         var handle = nextHandle++;
15003         tasksByHandle[handle] = cb;
15004         Promise.resolve().then(function () { return runIfPresent(handle); });
15005         return handle;
15006     },
15007     clearImmediate: function (handle) {
15008         delete tasksByHandle[handle];
15009     },
15010 };
15011
15012 },{}],195:[function(require,module,exports){
15013 "use strict";
15014 Object.defineProperty(exports, "__esModule", { value: true });
15015 function ObjectUnsubscribedErrorImpl() {
15016     Error.call(this);
15017     this.message = 'object unsubscribed';
15018     this.name = 'ObjectUnsubscribedError';
15019     return this;
15020 }
15021 ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);
15022 exports.ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;
15023
15024 },{}],196:[function(require,module,exports){
15025 "use strict";
15026 Object.defineProperty(exports, "__esModule", { value: true });
15027 function TimeoutErrorImpl() {
15028     Error.call(this);
15029     this.message = 'Timeout has occurred';
15030     this.name = 'TimeoutError';
15031     return this;
15032 }
15033 TimeoutErrorImpl.prototype = Object.create(Error.prototype);
15034 exports.TimeoutError = TimeoutErrorImpl;
15035
15036 },{}],197:[function(require,module,exports){
15037 "use strict";
15038 Object.defineProperty(exports, "__esModule", { value: true });
15039 function UnsubscriptionErrorImpl(errors) {
15040     Error.call(this);
15041     this.message = errors ?
15042         errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n  ') : '';
15043     this.name = 'UnsubscriptionError';
15044     this.errors = errors;
15045     return this;
15046 }
15047 UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);
15048 exports.UnsubscriptionError = UnsubscriptionErrorImpl;
15049
15050 },{}],198:[function(require,module,exports){
15051 "use strict";
15052 Object.defineProperty(exports, "__esModule", { value: true });
15053 var Subscriber_1 = require("../Subscriber");
15054 function canReportError(observer) {
15055     while (observer) {
15056         var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;
15057         if (closed_1 || isStopped) {
15058             return false;
15059         }
15060         else if (destination && destination instanceof Subscriber_1.Subscriber) {
15061             observer = destination;
15062         }
15063         else {
15064             observer = null;
15065         }
15066     }
15067     return true;
15068 }
15069 exports.canReportError = canReportError;
15070
15071 },{"../Subscriber":38}],199:[function(require,module,exports){
15072 "use strict";
15073 Object.defineProperty(exports, "__esModule", { value: true });
15074 exports.errorObject = { e: {} };
15075
15076 },{}],200:[function(require,module,exports){
15077 "use strict";
15078 Object.defineProperty(exports, "__esModule", { value: true });
15079 function hostReportError(err) {
15080     setTimeout(function () { throw err; });
15081 }
15082 exports.hostReportError = hostReportError;
15083
15084 },{}],201:[function(require,module,exports){
15085 "use strict";
15086 Object.defineProperty(exports, "__esModule", { value: true });
15087 function identity(x) {
15088     return x;
15089 }
15090 exports.identity = identity;
15091
15092 },{}],202:[function(require,module,exports){
15093 "use strict";
15094 Object.defineProperty(exports, "__esModule", { value: true });
15095 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
15096
15097 },{}],203:[function(require,module,exports){
15098 "use strict";
15099 Object.defineProperty(exports, "__esModule", { value: true });
15100 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
15101
15102 },{}],204:[function(require,module,exports){
15103 "use strict";
15104 Object.defineProperty(exports, "__esModule", { value: true });
15105 function isDate(value) {
15106     return value instanceof Date && !isNaN(+value);
15107 }
15108 exports.isDate = isDate;
15109
15110 },{}],205:[function(require,module,exports){
15111 "use strict";
15112 Object.defineProperty(exports, "__esModule", { value: true });
15113 function isFunction(x) {
15114     return typeof x === 'function';
15115 }
15116 exports.isFunction = isFunction;
15117
15118 },{}],206:[function(require,module,exports){
15119 "use strict";
15120 Object.defineProperty(exports, "__esModule", { value: true });
15121 var observable_1 = require("../symbol/observable");
15122 function isInteropObservable(input) {
15123     return input && typeof input[observable_1.observable] === 'function';
15124 }
15125 exports.isInteropObservable = isInteropObservable;
15126
15127 },{"../symbol/observable":190}],207:[function(require,module,exports){
15128 "use strict";
15129 Object.defineProperty(exports, "__esModule", { value: true });
15130 var iterator_1 = require("../symbol/iterator");
15131 function isIterable(input) {
15132     return input && typeof input[iterator_1.iterator] === 'function';
15133 }
15134 exports.isIterable = isIterable;
15135
15136 },{"../symbol/iterator":189}],208:[function(require,module,exports){
15137 "use strict";
15138 Object.defineProperty(exports, "__esModule", { value: true });
15139 var isArray_1 = require("./isArray");
15140 function isNumeric(val) {
15141     return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
15142 }
15143 exports.isNumeric = isNumeric;
15144
15145 },{"./isArray":202}],209:[function(require,module,exports){
15146 "use strict";
15147 Object.defineProperty(exports, "__esModule", { value: true });
15148 function isObject(x) {
15149     return x != null && typeof x === 'object';
15150 }
15151 exports.isObject = isObject;
15152
15153 },{}],210:[function(require,module,exports){
15154 "use strict";
15155 Object.defineProperty(exports, "__esModule", { value: true });
15156 var Observable_1 = require("../Observable");
15157 function isObservable(obj) {
15158     return !!obj && (obj instanceof Observable_1.Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function'));
15159 }
15160 exports.isObservable = isObservable;
15161
15162 },{"../Observable":31}],211:[function(require,module,exports){
15163 "use strict";
15164 Object.defineProperty(exports, "__esModule", { value: true });
15165 function isPromise(value) {
15166     return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
15167 }
15168 exports.isPromise = isPromise;
15169
15170 },{}],212:[function(require,module,exports){
15171 "use strict";
15172 Object.defineProperty(exports, "__esModule", { value: true });
15173 function isScheduler(value) {
15174     return value && typeof value.schedule === 'function';
15175 }
15176 exports.isScheduler = isScheduler;
15177
15178 },{}],213:[function(require,module,exports){
15179 "use strict";
15180 Object.defineProperty(exports, "__esModule", { value: true });
15181 function noop() { }
15182 exports.noop = noop;
15183
15184 },{}],214:[function(require,module,exports){
15185 "use strict";
15186 Object.defineProperty(exports, "__esModule", { value: true });
15187 function not(pred, thisArg) {
15188     function notPred() {
15189         return !(notPred.pred.apply(notPred.thisArg, arguments));
15190     }
15191     notPred.pred = pred;
15192     notPred.thisArg = thisArg;
15193     return notPred;
15194 }
15195 exports.not = not;
15196
15197 },{}],215:[function(require,module,exports){
15198 "use strict";
15199 Object.defineProperty(exports, "__esModule", { value: true });
15200 var noop_1 = require("./noop");
15201 function pipe() {
15202     var fns = [];
15203     for (var _i = 0; _i < arguments.length; _i++) {
15204         fns[_i] = arguments[_i];
15205     }
15206     return pipeFromArray(fns);
15207 }
15208 exports.pipe = pipe;
15209 function pipeFromArray(fns) {
15210     if (!fns) {
15211         return noop_1.noop;
15212     }
15213     if (fns.length === 1) {
15214         return fns[0];
15215     }
15216     return function piped(input) {
15217         return fns.reduce(function (prev, fn) { return fn(prev); }, input);
15218     };
15219 }
15220 exports.pipeFromArray = pipeFromArray;
15221
15222 },{"./noop":213}],216:[function(require,module,exports){
15223 "use strict";
15224 Object.defineProperty(exports, "__esModule", { value: true });
15225 var Observable_1 = require("../Observable");
15226 var subscribeToArray_1 = require("./subscribeToArray");
15227 var subscribeToPromise_1 = require("./subscribeToPromise");
15228 var subscribeToIterable_1 = require("./subscribeToIterable");
15229 var subscribeToObservable_1 = require("./subscribeToObservable");
15230 var isArrayLike_1 = require("./isArrayLike");
15231 var isPromise_1 = require("./isPromise");
15232 var isObject_1 = require("./isObject");
15233 var iterator_1 = require("../symbol/iterator");
15234 var observable_1 = require("../symbol/observable");
15235 exports.subscribeTo = function (result) {
15236     if (result instanceof Observable_1.Observable) {
15237         return function (subscriber) {
15238             if (result._isScalar) {
15239                 subscriber.next(result.value);
15240                 subscriber.complete();
15241                 return undefined;
15242             }
15243             else {
15244                 return result.subscribe(subscriber);
15245             }
15246         };
15247     }
15248     else if (result && typeof result[observable_1.observable] === 'function') {
15249         return subscribeToObservable_1.subscribeToObservable(result);
15250     }
15251     else if (isArrayLike_1.isArrayLike(result)) {
15252         return subscribeToArray_1.subscribeToArray(result);
15253     }
15254     else if (isPromise_1.isPromise(result)) {
15255         return subscribeToPromise_1.subscribeToPromise(result);
15256     }
15257     else if (result && typeof result[iterator_1.iterator] === 'function') {
15258         return subscribeToIterable_1.subscribeToIterable(result);
15259     }
15260     else {
15261         var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
15262         var msg = "You provided " + value + " where a stream was expected."
15263             + ' You can provide an Observable, Promise, Array, or Iterable.';
15264         throw new TypeError(msg);
15265     }
15266 };
15267
15268 },{"../Observable":31,"../symbol/iterator":189,"../symbol/observable":190,"./isArrayLike":203,"./isObject":209,"./isPromise":211,"./subscribeToArray":217,"./subscribeToIterable":218,"./subscribeToObservable":219,"./subscribeToPromise":220}],217:[function(require,module,exports){
15269 "use strict";
15270 Object.defineProperty(exports, "__esModule", { value: true });
15271 exports.subscribeToArray = function (array) { return function (subscriber) {
15272     for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) {
15273         subscriber.next(array[i]);
15274     }
15275     if (!subscriber.closed) {
15276         subscriber.complete();
15277     }
15278 }; };
15279
15280 },{}],218:[function(require,module,exports){
15281 "use strict";
15282 Object.defineProperty(exports, "__esModule", { value: true });
15283 var iterator_1 = require("../symbol/iterator");
15284 exports.subscribeToIterable = function (iterable) { return function (subscriber) {
15285     var iterator = iterable[iterator_1.iterator]();
15286     do {
15287         var item = iterator.next();
15288         if (item.done) {
15289             subscriber.complete();
15290             break;
15291         }
15292         subscriber.next(item.value);
15293         if (subscriber.closed) {
15294             break;
15295         }
15296     } while (true);
15297     if (typeof iterator.return === 'function') {
15298         subscriber.add(function () {
15299             if (iterator.return) {
15300                 iterator.return();
15301             }
15302         });
15303     }
15304     return subscriber;
15305 }; };
15306
15307 },{"../symbol/iterator":189}],219:[function(require,module,exports){
15308 "use strict";
15309 Object.defineProperty(exports, "__esModule", { value: true });
15310 var observable_1 = require("../symbol/observable");
15311 exports.subscribeToObservable = function (obj) { return function (subscriber) {
15312     var obs = obj[observable_1.observable]();
15313     if (typeof obs.subscribe !== 'function') {
15314         throw new TypeError('Provided object does not correctly implement Symbol.observable');
15315     }
15316     else {
15317         return obs.subscribe(subscriber);
15318     }
15319 }; };
15320
15321 },{"../symbol/observable":190}],220:[function(require,module,exports){
15322 "use strict";
15323 Object.defineProperty(exports, "__esModule", { value: true });
15324 var hostReportError_1 = require("./hostReportError");
15325 exports.subscribeToPromise = function (promise) { return function (subscriber) {
15326     promise.then(function (value) {
15327         if (!subscriber.closed) {
15328             subscriber.next(value);
15329             subscriber.complete();
15330         }
15331     }, function (err) { return subscriber.error(err); })
15332         .then(null, hostReportError_1.hostReportError);
15333     return subscriber;
15334 }; };
15335
15336 },{"./hostReportError":200}],221:[function(require,module,exports){
15337 "use strict";
15338 Object.defineProperty(exports, "__esModule", { value: true });
15339 var InnerSubscriber_1 = require("../InnerSubscriber");
15340 var subscribeTo_1 = require("./subscribeTo");
15341 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) {
15342     if (destination === void 0) { destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex); }
15343     if (destination.closed) {
15344         return;
15345     }
15346     return subscribeTo_1.subscribeTo(result)(destination);
15347 }
15348 exports.subscribeToResult = subscribeToResult;
15349
15350 },{"../InnerSubscriber":29,"./subscribeTo":216}],222:[function(require,module,exports){
15351 "use strict";
15352 Object.defineProperty(exports, "__esModule", { value: true });
15353 var Subscriber_1 = require("../Subscriber");
15354 var rxSubscriber_1 = require("../symbol/rxSubscriber");
15355 var Observer_1 = require("../Observer");
15356 function toSubscriber(nextOrObserver, error, complete) {
15357     if (nextOrObserver) {
15358         if (nextOrObserver instanceof Subscriber_1.Subscriber) {
15359             return nextOrObserver;
15360         }
15361         if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
15362             return nextOrObserver[rxSubscriber_1.rxSubscriber]();
15363         }
15364     }
15365     if (!nextOrObserver && !error && !complete) {
15366         return new Subscriber_1.Subscriber(Observer_1.empty);
15367     }
15368     return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
15369 }
15370 exports.toSubscriber = toSubscriber;
15371
15372 },{"../Observer":32,"../Subscriber":38,"../symbol/rxSubscriber":191}],223:[function(require,module,exports){
15373 "use strict";
15374 Object.defineProperty(exports, "__esModule", { value: true });
15375 var errorObject_1 = require("./errorObject");
15376 var tryCatchTarget;
15377 function tryCatcher() {
15378     try {
15379         return tryCatchTarget.apply(this, arguments);
15380     }
15381     catch (e) {
15382         errorObject_1.errorObject.e = e;
15383         return errorObject_1.errorObject;
15384     }
15385 }
15386 function tryCatch(fn) {
15387     tryCatchTarget = fn;
15388     return tryCatcher;
15389 }
15390 exports.tryCatch = tryCatch;
15391
15392 },{"./errorObject":199}],224:[function(require,module,exports){
15393 "use strict";
15394 Object.defineProperty(exports, "__esModule", { value: true });
15395 var audit_1 = require("../internal/operators/audit");
15396 exports.audit = audit_1.audit;
15397 var auditTime_1 = require("../internal/operators/auditTime");
15398 exports.auditTime = auditTime_1.auditTime;
15399 var buffer_1 = require("../internal/operators/buffer");
15400 exports.buffer = buffer_1.buffer;
15401 var bufferCount_1 = require("../internal/operators/bufferCount");
15402 exports.bufferCount = bufferCount_1.bufferCount;
15403 var bufferTime_1 = require("../internal/operators/bufferTime");
15404 exports.bufferTime = bufferTime_1.bufferTime;
15405 var bufferToggle_1 = require("../internal/operators/bufferToggle");
15406 exports.bufferToggle = bufferToggle_1.bufferToggle;
15407 var bufferWhen_1 = require("../internal/operators/bufferWhen");
15408 exports.bufferWhen = bufferWhen_1.bufferWhen;
15409 var catchError_1 = require("../internal/operators/catchError");
15410 exports.catchError = catchError_1.catchError;
15411 var combineAll_1 = require("../internal/operators/combineAll");
15412 exports.combineAll = combineAll_1.combineAll;
15413 var combineLatest_1 = require("../internal/operators/combineLatest");
15414 exports.combineLatest = combineLatest_1.combineLatest;
15415 var concat_1 = require("../internal/operators/concat");
15416 exports.concat = concat_1.concat;
15417 var concatAll_1 = require("../internal/operators/concatAll");
15418 exports.concatAll = concatAll_1.concatAll;
15419 var concatMap_1 = require("../internal/operators/concatMap");
15420 exports.concatMap = concatMap_1.concatMap;
15421 var concatMapTo_1 = require("../internal/operators/concatMapTo");
15422 exports.concatMapTo = concatMapTo_1.concatMapTo;
15423 var count_1 = require("../internal/operators/count");
15424 exports.count = count_1.count;
15425 var debounce_1 = require("../internal/operators/debounce");
15426 exports.debounce = debounce_1.debounce;
15427 var debounceTime_1 = require("../internal/operators/debounceTime");
15428 exports.debounceTime = debounceTime_1.debounceTime;
15429 var defaultIfEmpty_1 = require("../internal/operators/defaultIfEmpty");
15430 exports.defaultIfEmpty = defaultIfEmpty_1.defaultIfEmpty;
15431 var delay_1 = require("../internal/operators/delay");
15432 exports.delay = delay_1.delay;
15433 var delayWhen_1 = require("../internal/operators/delayWhen");
15434 exports.delayWhen = delayWhen_1.delayWhen;
15435 var dematerialize_1 = require("../internal/operators/dematerialize");
15436 exports.dematerialize = dematerialize_1.dematerialize;
15437 var distinct_1 = require("../internal/operators/distinct");
15438 exports.distinct = distinct_1.distinct;
15439 var distinctUntilChanged_1 = require("../internal/operators/distinctUntilChanged");
15440 exports.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
15441 var distinctUntilKeyChanged_1 = require("../internal/operators/distinctUntilKeyChanged");
15442 exports.distinctUntilKeyChanged = distinctUntilKeyChanged_1.distinctUntilKeyChanged;
15443 var elementAt_1 = require("../internal/operators/elementAt");
15444 exports.elementAt = elementAt_1.elementAt;
15445 var endWith_1 = require("../internal/operators/endWith");
15446 exports.endWith = endWith_1.endWith;
15447 var every_1 = require("../internal/operators/every");
15448 exports.every = every_1.every;
15449 var exhaust_1 = require("../internal/operators/exhaust");
15450 exports.exhaust = exhaust_1.exhaust;
15451 var exhaustMap_1 = require("../internal/operators/exhaustMap");
15452 exports.exhaustMap = exhaustMap_1.exhaustMap;
15453 var expand_1 = require("../internal/operators/expand");
15454 exports.expand = expand_1.expand;
15455 var filter_1 = require("../internal/operators/filter");
15456 exports.filter = filter_1.filter;
15457 var finalize_1 = require("../internal/operators/finalize");
15458 exports.finalize = finalize_1.finalize;
15459 var find_1 = require("../internal/operators/find");
15460 exports.find = find_1.find;
15461 var findIndex_1 = require("../internal/operators/findIndex");
15462 exports.findIndex = findIndex_1.findIndex;
15463 var first_1 = require("../internal/operators/first");
15464 exports.first = first_1.first;
15465 var groupBy_1 = require("../internal/operators/groupBy");
15466 exports.groupBy = groupBy_1.groupBy;
15467 var ignoreElements_1 = require("../internal/operators/ignoreElements");
15468 exports.ignoreElements = ignoreElements_1.ignoreElements;
15469 var isEmpty_1 = require("../internal/operators/isEmpty");
15470 exports.isEmpty = isEmpty_1.isEmpty;
15471 var last_1 = require("../internal/operators/last");
15472 exports.last = last_1.last;
15473 var map_1 = require("../internal/operators/map");
15474 exports.map = map_1.map;
15475 var mapTo_1 = require("../internal/operators/mapTo");
15476 exports.mapTo = mapTo_1.mapTo;
15477 var materialize_1 = require("../internal/operators/materialize");
15478 exports.materialize = materialize_1.materialize;
15479 var max_1 = require("../internal/operators/max");
15480 exports.max = max_1.max;
15481 var merge_1 = require("../internal/operators/merge");
15482 exports.merge = merge_1.merge;
15483 var mergeAll_1 = require("../internal/operators/mergeAll");
15484 exports.mergeAll = mergeAll_1.mergeAll;
15485 var mergeMap_1 = require("../internal/operators/mergeMap");
15486 exports.mergeMap = mergeMap_1.mergeMap;
15487 var mergeMap_2 = require("../internal/operators/mergeMap");
15488 exports.flatMap = mergeMap_2.mergeMap;
15489 var mergeMapTo_1 = require("../internal/operators/mergeMapTo");
15490 exports.mergeMapTo = mergeMapTo_1.mergeMapTo;
15491 var mergeScan_1 = require("../internal/operators/mergeScan");
15492 exports.mergeScan = mergeScan_1.mergeScan;
15493 var min_1 = require("../internal/operators/min");
15494 exports.min = min_1.min;
15495 var multicast_1 = require("../internal/operators/multicast");
15496 exports.multicast = multicast_1.multicast;
15497 var observeOn_1 = require("../internal/operators/observeOn");
15498 exports.observeOn = observeOn_1.observeOn;
15499 var onErrorResumeNext_1 = require("../internal/operators/onErrorResumeNext");
15500 exports.onErrorResumeNext = onErrorResumeNext_1.onErrorResumeNext;
15501 var pairwise_1 = require("../internal/operators/pairwise");
15502 exports.pairwise = pairwise_1.pairwise;
15503 var partition_1 = require("../internal/operators/partition");
15504 exports.partition = partition_1.partition;
15505 var pluck_1 = require("../internal/operators/pluck");
15506 exports.pluck = pluck_1.pluck;
15507 var publish_1 = require("../internal/operators/publish");
15508 exports.publish = publish_1.publish;
15509 var publishBehavior_1 = require("../internal/operators/publishBehavior");
15510 exports.publishBehavior = publishBehavior_1.publishBehavior;
15511 var publishLast_1 = require("../internal/operators/publishLast");
15512 exports.publishLast = publishLast_1.publishLast;
15513 var publishReplay_1 = require("../internal/operators/publishReplay");
15514 exports.publishReplay = publishReplay_1.publishReplay;
15515 var race_1 = require("../internal/operators/race");
15516 exports.race = race_1.race;
15517 var reduce_1 = require("../internal/operators/reduce");
15518 exports.reduce = reduce_1.reduce;
15519 var repeat_1 = require("../internal/operators/repeat");
15520 exports.repeat = repeat_1.repeat;
15521 var repeatWhen_1 = require("../internal/operators/repeatWhen");
15522 exports.repeatWhen = repeatWhen_1.repeatWhen;
15523 var retry_1 = require("../internal/operators/retry");
15524 exports.retry = retry_1.retry;
15525 var retryWhen_1 = require("../internal/operators/retryWhen");
15526 exports.retryWhen = retryWhen_1.retryWhen;
15527 var refCount_1 = require("../internal/operators/refCount");
15528 exports.refCount = refCount_1.refCount;
15529 var sample_1 = require("../internal/operators/sample");
15530 exports.sample = sample_1.sample;
15531 var sampleTime_1 = require("../internal/operators/sampleTime");
15532 exports.sampleTime = sampleTime_1.sampleTime;
15533 var scan_1 = require("../internal/operators/scan");
15534 exports.scan = scan_1.scan;
15535 var sequenceEqual_1 = require("../internal/operators/sequenceEqual");
15536 exports.sequenceEqual = sequenceEqual_1.sequenceEqual;
15537 var share_1 = require("../internal/operators/share");
15538 exports.share = share_1.share;
15539 var shareReplay_1 = require("../internal/operators/shareReplay");
15540 exports.shareReplay = shareReplay_1.shareReplay;
15541 var single_1 = require("../internal/operators/single");
15542 exports.single = single_1.single;
15543 var skip_1 = require("../internal/operators/skip");
15544 exports.skip = skip_1.skip;
15545 var skipLast_1 = require("../internal/operators/skipLast");
15546 exports.skipLast = skipLast_1.skipLast;
15547 var skipUntil_1 = require("../internal/operators/skipUntil");
15548 exports.skipUntil = skipUntil_1.skipUntil;
15549 var skipWhile_1 = require("../internal/operators/skipWhile");
15550 exports.skipWhile = skipWhile_1.skipWhile;
15551 var startWith_1 = require("../internal/operators/startWith");
15552 exports.startWith = startWith_1.startWith;
15553 var subscribeOn_1 = require("../internal/operators/subscribeOn");
15554 exports.subscribeOn = subscribeOn_1.subscribeOn;
15555 var switchAll_1 = require("../internal/operators/switchAll");
15556 exports.switchAll = switchAll_1.switchAll;
15557 var switchMap_1 = require("../internal/operators/switchMap");
15558 exports.switchMap = switchMap_1.switchMap;
15559 var switchMapTo_1 = require("../internal/operators/switchMapTo");
15560 exports.switchMapTo = switchMapTo_1.switchMapTo;
15561 var take_1 = require("../internal/operators/take");
15562 exports.take = take_1.take;
15563 var takeLast_1 = require("../internal/operators/takeLast");
15564 exports.takeLast = takeLast_1.takeLast;
15565 var takeUntil_1 = require("../internal/operators/takeUntil");
15566 exports.takeUntil = takeUntil_1.takeUntil;
15567 var takeWhile_1 = require("../internal/operators/takeWhile");
15568 exports.takeWhile = takeWhile_1.takeWhile;
15569 var tap_1 = require("../internal/operators/tap");
15570 exports.tap = tap_1.tap;
15571 var throttle_1 = require("../internal/operators/throttle");
15572 exports.throttle = throttle_1.throttle;
15573 var throttleTime_1 = require("../internal/operators/throttleTime");
15574 exports.throttleTime = throttleTime_1.throttleTime;
15575 var throwIfEmpty_1 = require("../internal/operators/throwIfEmpty");
15576 exports.throwIfEmpty = throwIfEmpty_1.throwIfEmpty;
15577 var timeInterval_1 = require("../internal/operators/timeInterval");
15578 exports.timeInterval = timeInterval_1.timeInterval;
15579 var timeout_1 = require("../internal/operators/timeout");
15580 exports.timeout = timeout_1.timeout;
15581 var timeoutWith_1 = require("../internal/operators/timeoutWith");
15582 exports.timeoutWith = timeoutWith_1.timeoutWith;
15583 var timestamp_1 = require("../internal/operators/timestamp");
15584 exports.timestamp = timestamp_1.timestamp;
15585 var toArray_1 = require("../internal/operators/toArray");
15586 exports.toArray = toArray_1.toArray;
15587 var window_1 = require("../internal/operators/window");
15588 exports.window = window_1.window;
15589 var windowCount_1 = require("../internal/operators/windowCount");
15590 exports.windowCount = windowCount_1.windowCount;
15591 var windowTime_1 = require("../internal/operators/windowTime");
15592 exports.windowTime = windowTime_1.windowTime;
15593 var windowToggle_1 = require("../internal/operators/windowToggle");
15594 exports.windowToggle = windowToggle_1.windowToggle;
15595 var windowWhen_1 = require("../internal/operators/windowWhen");
15596 exports.windowWhen = windowWhen_1.windowWhen;
15597 var withLatestFrom_1 = require("../internal/operators/withLatestFrom");
15598 exports.withLatestFrom = withLatestFrom_1.withLatestFrom;
15599 var zip_1 = require("../internal/operators/zip");
15600 exports.zip = zip_1.zip;
15601 var zipAll_1 = require("../internal/operators/zipAll");
15602 exports.zipAll = zipAll_1.zipAll;
15603
15604 },{"../internal/operators/audit":72,"../internal/operators/auditTime":73,"../internal/operators/buffer":74,"../internal/operators/bufferCount":75,"../internal/operators/bufferTime":76,"../internal/operators/bufferToggle":77,"../internal/operators/bufferWhen":78,"../internal/operators/catchError":79,"../internal/operators/combineAll":80,"../internal/operators/combineLatest":81,"../internal/operators/concat":82,"../internal/operators/concatAll":83,"../internal/operators/concatMap":84,"../internal/operators/concatMapTo":85,"../internal/operators/count":86,"../internal/operators/debounce":87,"../internal/operators/debounceTime":88,"../internal/operators/defaultIfEmpty":89,"../internal/operators/delay":90,"../internal/operators/delayWhen":91,"../internal/operators/dematerialize":92,"../internal/operators/distinct":93,"../internal/operators/distinctUntilChanged":94,"../internal/operators/distinctUntilKeyChanged":95,"../internal/operators/elementAt":96,"../internal/operators/endWith":97,"../internal/operators/every":98,"../internal/operators/exhaust":99,"../internal/operators/exhaustMap":100,"../internal/operators/expand":101,"../internal/operators/filter":102,"../internal/operators/finalize":103,"../internal/operators/find":104,"../internal/operators/findIndex":105,"../internal/operators/first":106,"../internal/operators/groupBy":107,"../internal/operators/ignoreElements":108,"../internal/operators/isEmpty":109,"../internal/operators/last":110,"../internal/operators/map":111,"../internal/operators/mapTo":112,"../internal/operators/materialize":113,"../internal/operators/max":114,"../internal/operators/merge":115,"../internal/operators/mergeAll":116,"../internal/operators/mergeMap":117,"../internal/operators/mergeMapTo":118,"../internal/operators/mergeScan":119,"../internal/operators/min":120,"../internal/operators/multicast":121,"../internal/operators/observeOn":122,"../internal/operators/onErrorResumeNext":123,"../internal/operators/pairwise":124,"../internal/operators/partition":125,"../internal/operators/pluck":126,"../internal/operators/publish":127,"../internal/operators/publishBehavior":128,"../internal/operators/publishLast":129,"../internal/operators/publishReplay":130,"../internal/operators/race":131,"../internal/operators/reduce":132,"../internal/operators/refCount":133,"../internal/operators/repeat":134,"../internal/operators/repeatWhen":135,"../internal/operators/retry":136,"../internal/operators/retryWhen":137,"../internal/operators/sample":138,"../internal/operators/sampleTime":139,"../internal/operators/scan":140,"../internal/operators/sequenceEqual":141,"../internal/operators/share":142,"../internal/operators/shareReplay":143,"../internal/operators/single":144,"../internal/operators/skip":145,"../internal/operators/skipLast":146,"../internal/operators/skipUntil":147,"../internal/operators/skipWhile":148,"../internal/operators/startWith":149,"../internal/operators/subscribeOn":150,"../internal/operators/switchAll":151,"../internal/operators/switchMap":152,"../internal/operators/switchMapTo":153,"../internal/operators/take":154,"../internal/operators/takeLast":155,"../internal/operators/takeUntil":156,"../internal/operators/takeWhile":157,"../internal/operators/tap":158,"../internal/operators/throttle":159,"../internal/operators/throttleTime":160,"../internal/operators/throwIfEmpty":161,"../internal/operators/timeInterval":162,"../internal/operators/timeout":163,"../internal/operators/timeoutWith":164,"../internal/operators/timestamp":165,"../internal/operators/toArray":166,"../internal/operators/window":167,"../internal/operators/windowCount":168,"../internal/operators/windowTime":169,"../internal/operators/windowToggle":170,"../internal/operators/windowWhen":171,"../internal/operators/withLatestFrom":172,"../internal/operators/zip":173,"../internal/operators/zipAll":174}],225:[function(require,module,exports){
15605 // threejs.org/license
15606 (function(l,ya){"object"===typeof exports&&"undefined"!==typeof module?ya(exports):"function"===typeof define&&define.amd?define(["exports"],ya):ya(l.THREE={})})(this,function(l){function ya(){}function z(a,b){this.x=a||0;this.y=b||0}function I(){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 fa(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}function p(a,
15607 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 T(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:Ef++});this.uuid=H.generateUUID();this.name="";this.image=void 0!==a?a:T.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:T.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=void 0!==d?d:1001;this.magFilter=void 0!==
15608 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 z(0,0);this.repeat=new z(1,1);this.center=new z(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!==m?m:3E3;this.version=0;this.onUpdate=null}function V(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function fb(a,
15609 b,c){this.width=a;this.height=b;this.scissor=new V(0,0,a,b);this.scissorTest=!1;this.viewport=new V(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new T(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.texture.generateMipmaps=void 0!==c.generateMipmaps?c.generateMipmaps:!0;this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0;this.depthTexture=void 0!==c.depthTexture?
15610 c.depthTexture:null}function Gb(a,b,c){fb.call(this,a,b,c);this.activeMipMapLevel=this.activeCubeFace=0}function gb(a,b,c,d,e,f,g,h,k,m,q,n){T.call(this,null,f,g,h,k,m,d,e,q,n);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==m?m:1003;this.flipY=this.generateMipmaps=!1;this.unpackAlignment=1}function Sa(a,b){this.min=void 0!==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!==
15611 a?a:new p;this.radius=void 0!==b?b:0}function Ma(a,b){this.normal=void 0!==a?a:new p(1,0,0);this.constant=void 0!==b?b:0}function md(a,b,c,d,e,f){this.planes=[void 0!==a?a:new Ma,void 0!==b?b:new Ma,void 0!==c?c:new Ma,void 0!==d?d:new Ma,void 0!==e?e:new Ma,void 0!==f?f:new Ma]}function G(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function Qd(){function a(e,f){!1!==c&&(d(e,f),b.requestAnimationFrame(a))}var b=null,c=!1,d=null;return{start:function(){!0!==c&&null!==d&&(b.requestAnimationFrame(a),
15612 c=!0)},stop:function(){c=!1},setAnimationLoop:function(a){d=a},setContext:function(a){b=a}}}function Ff(a){function b(b,c){var d=b.array,e=b.dynamic?a.DYNAMIC_DRAW:a.STATIC_DRAW,h=a.createBuffer();a.bindBuffer(c,h);a.bufferData(c,d,e);b.onUploadCallback();c=a.FLOAT;d instanceof Float32Array?c=a.FLOAT:d instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):d instanceof Uint16Array?c=a.UNSIGNED_SHORT:d instanceof Int16Array?c=a.SHORT:d instanceof
15613 Uint32Array?c=a.UNSIGNED_INT:d instanceof Int32Array?c=a.INT:d instanceof Int8Array?c=a.BYTE:d instanceof Uint8Array&&(c=a.UNSIGNED_BYTE);return{buffer:h,type:c,bytesPerElement:d.BYTES_PER_ELEMENT,version:b.version}}var c=new WeakMap;return{get:function(a){a.isInterleavedBufferAttribute&&(a=a.data);return c.get(a)},remove:function(b){b.isInterleavedBufferAttribute&&(b=b.data);var d=c.get(b);d&&(a.deleteBuffer(d.buffer),c.delete(b))},update:function(d,e){d.isInterleavedBufferAttribute&&(d=d.data);
15614 var f=c.get(d);if(void 0===f)c.set(d,b(d,e));else if(f.version<d.version){var g=d,h=g.array,k=g.updateRange;a.bindBuffer(e,f.buffer);!1===g.dynamic?a.bufferData(e,h,a.STATIC_DRAW):-1===k.count?a.bufferSubData(e,0,h):0===k.count?console.error("THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually."):(a.bufferSubData(e,k.offset*h.BYTES_PER_ELEMENT,h.subarray(k.offset,k.offset+k.count)),k.count=
15615 -1);f.version=d.version}}}}function hb(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||hb.DefaultOrder}function Rd(){this.mask=1}function D(){Object.defineProperty(this,"id",{value:Gf++});this.uuid=H.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=D.DefaultUp.clone();var a=new p,b=new hb,c=new fa,d=new p(1,1,1);b.onChange(function(){c.setFromEuler(b,!1)});c.onChange(function(){b.setFromQuaternion(c,void 0,!1)});Object.defineProperties(this,
15616 {position:{enumerable:!0,value:a},rotation:{enumerable:!0,value:b},quaternion:{enumerable:!0,value:c},scale:{enumerable:!0,value:d},modelViewMatrix:{value:new I},normalMatrix:{value:new ra}});this.matrix=new I;this.matrixWorld=new I;this.matrixAutoUpdate=D.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new Rd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=0;this.userData={}}function Na(){D.call(this);this.type="Camera";this.matrixWorldInverse=
15617 new I;this.projectionMatrix=new I}function Hb(a,b,c,d,e,f){Na.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=void 0!==e?e:.1;this.far=void 0!==f?f:2E3;this.updateProjectionMatrix()}function Ta(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?e:new G;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function R(){Object.defineProperty(this,
15618 "id",{value:Hf+=2});this.uuid=H.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=this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function Q(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
15619 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.version=0}function oc(a,b,c){Q.call(this,new Int8Array(a),b,c)}function pc(a,b,c){Q.call(this,new Uint8Array(a),b,c)}function qc(a,b,c){Q.call(this,new Uint8ClampedArray(a),b,c)}function rc(a,b,c){Q.call(this,new Int16Array(a),b,c)}function ib(a,b,c){Q.call(this,new Uint16Array(a),b,c)}function sc(a,b,c){Q.call(this,new Int32Array(a),b,c)}function jb(a,
15620 b,c){Q.call(this,new Uint32Array(a),b,c)}function A(a,b,c){Q.call(this,new Float32Array(a),b,c)}function tc(a,b,c){Q.call(this,new Float64Array(a),b,c)}function Ee(){this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=[];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.uvsNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.verticesNeedUpdate=!1}function Fe(a){if(0===a.length)return-Infinity;
15621 for(var b=a[0],c=1,d=a.length;c<d;++c)a[c]>b&&(b=a[c]);return b}function C(){Object.defineProperty(this,"id",{value:If+=2});this.uuid=H.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange={start:0,count:Infinity};this.userData={}}function Ib(a,b,c,d,e,f){R.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,
15622 depthSegments:f};this.fromBufferGeometry(new kb(a,b,c,d,e,f));this.mergeVertices()}function kb(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,l,N,O,Jf){var r=f/N,v=g/O,P=f/2,y=g/2,w=l/2;g=N+1;var E=O+1,x=f=0,B,z,A=new p;for(z=0;z<E;z++){var D=z*v-y;for(B=0;B<g;B++)A[a]=(B*r-P)*d,A[b]=D*e,A[c]=w,m.push(A.x,A.y,A.z),A[a]=0,A[b]=0,A[c]=0<l?1:-1,q.push(A.x,A.y,A.z),n.push(B/N),n.push(1-z/O),f+=1}for(z=0;z<O;z++)for(B=0;B<N;B++)a=t+B+g*(z+1),b=t+(B+1)+g*(z+1),c=t+(B+1)+g*z,k.push(t+B+g*z,a,c),k.push(a,b,c),x+=
15623 6;h.addGroup(u,x,Jf);u+=x;t+=f}C.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=[],m=[],q=[],n=[],t=0,u=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",
15624 new A(m,3));this.addAttribute("normal",new A(q,3));this.addAttribute("uv",new A(n,2))}function uc(a,b,c,d){R.call(this);this.type="PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new lb(a,b,c,d));this.mergeVertices()}function lb(a,b,c,d){C.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,m=
15625 b/d,q=[],n=[],t=[],u=[];for(a=0;a<h;a++){var r=a*m-f;for(b=0;b<g;b++)n.push(b*k-e,-r,0),t.push(0,0,1),u.push(b/c),u.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",new A(n,3));this.addAttribute("normal",new A(t,3));this.addAttribute("uv",new A(u,2))}function J(){Object.defineProperty(this,"id",{value:Kf++});this.uuid=H.generateUUID();this.name="";this.type="Material";this.lights=this.fog=
15626 !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=null;this.depthFunc=3;this.depthWrite=this.depthTest=!0;this.clippingPlanes=null;this.clipShadows=this.clipIntersection=!1;this.shadowSide=null;this.colorWrite=!0;this.precision=null;this.polygonOffset=!1;this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.dithering=!1;
15627 this.alphaTest=0;this.premultipliedAlpha=!1;this.overdraw=0;this.visible=!0;this.userData={};this.needsUpdate=!0}function da(a){J.call(this);this.type="MeshBasicMaterial";this.color=new G(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.lights=
15628 this.morphTargets=this.skinning=!1;this.setValues(a)}function ta(a){J.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=
15629 {derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1};this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]};this.index0AttributeName=void 0;this.uniformsNeedUpdate=!1;void 0!==a&&(void 0!==a.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),this.setValues(a))}function mb(a,b){this.origin=void 0!==a?a:new p;this.direction=void 0!==b?b:new p}function ja(a,b,c){this.a=void 0!==a?a:new p;this.b=void 0!==b?b:new p;this.c=
15630 void 0!==c?c:new p}function la(a,b){D.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new C;this.material=void 0!==b?b:new da({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function Lf(a,b,c,d){function e(a,c){b.buffers.color.setClear(a.r,a.g,a.b,c,d)}var f=new G(0),g=0,h,k,m;return{getClearColor:function(){return f},setClearColor:function(a,b){f.set(a);g=void 0!==b?b:1;e(f,g)},getClearAlpha:function(){return g},setClearAlpha:function(a){g=a;e(f,g)},render:function(b,
15631 d,t,u){d=d.background;null===d?e(f,g):d&&d.isColor&&(e(d,1),u=!0);(a.autoClear||u)&&a.clear(a.autoClearColor,a.autoClearDepth,a.autoClearStencil);d&&d.isCubeTexture?(void 0===m&&(m=new la(new kb(1,1,1),new ta({uniforms:nb.cube.uniforms,vertexShader:nb.cube.vertexShader,fragmentShader:nb.cube.fragmentShader,side:1,depthTest:!0,depthWrite:!1,fog:!1})),m.geometry.removeAttribute("normal"),m.geometry.removeAttribute("uv"),m.onBeforeRender=function(a,b,c){this.matrixWorld.copyPosition(c.matrixWorld)},
15632 c.update(m)),m.material.uniforms.tCube.value=d,b.push(m,m.geometry,m.material,0,null)):d&&d.isTexture&&(void 0===h&&(h=new Hb(-1,1,1,-1,0,1),k=new la(new lb(2,2),new da({depthTest:!1,depthWrite:!1,fog:!1})),c.update(k)),k.material.map=d,a.renderBufferDirect(h,null,k.geometry,k.material,k,null))}}}function Mf(a,b,c,d){var e;this.setMode=function(a){e=a};this.render=function(b,d){a.drawArrays(e,b,d);c.update(d,e)};this.renderInstances=function(f,g,h){if(d.isWebGL2)var k=a;else if(k=b.get("ANGLE_instanced_arrays"),
15633 null===k){console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}k[d.isWebGL2?"drawArraysInstanced":"drawArraysInstancedANGLE"](e,g,h,f.maxInstancedCount);c.update(h,e,f.maxInstancedCount)}}function Nf(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"===
15634 b&&0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.MEDIUM_FLOAT).precision?"mediump":"lowp"}var e,f="undefined"!==typeof WebGL2RenderingContext&&a instanceof WebGL2RenderingContext,g=void 0!==c.precision?c.precision:"highp",h=d(g);h!==g&&(console.warn("THREE.WebGLRenderer:",g,"not supported, using",h,"instead."),g=h);c=!0===c.logarithmicDepthBuffer;h=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS);var k=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
15635 m=a.getParameter(a.MAX_TEXTURE_SIZE),q=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),n=a.getParameter(a.MAX_VERTEX_ATTRIBS),t=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),u=a.getParameter(a.MAX_VARYING_VECTORS),r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),l=0<k,y=f||!!b.get("OES_texture_float");return{isWebGL2:f,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,
15636 precision:g,logarithmicDepthBuffer:c,maxTextures:h,maxVertexTextures:k,maxTextureSize:m,maxCubemapSize:q,maxAttributes:n,maxVertexUniforms:t,maxVaryings:u,maxFragmentUniforms:r,vertexTextures:l,floatFragmentTextures:y,floatVertexTextures:l&&y}}function Of(){function a(){m.value!==d&&(m.value=d,m.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=m.value;if(!0!==e||null===g){e=d+4*f;b=b.matrixWorldInverse;k.getNormalMatrix(b);if(null===
15637 g||g.length<e)g=new Float32Array(e);for(e=0;e!==f;++e,d+=4)h.copy(a[e]).applyMatrix4(b,k),h.normal.toArray(g,d),g[d+3]=h.constant}m.value=g;m.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new Ma,k=new ra,m={value:null,needsUpdate:!1};this.uniform=m;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=
15638 function(c,h,k,u,r,l){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var n=4*k,q=r.clippingState||null;m.value=q;q=b(c,u,n,l);for(c=0;c!==n;++c)q[c]=d[c];r.clippingState=q;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Pf(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;
15639 case "EXT_texture_filter_anisotropic":d=a.getExtension("EXT_texture_filter_anisotropic")||a.getExtension("MOZ_EXT_texture_filter_anisotropic")||a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case "WEBGL_compressed_texture_s3tc":d=a.getExtension("WEBGL_compressed_texture_s3tc")||a.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||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");
15640 break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function Qf(a,b,c){function d(a){var h=a.target;a=e[h.id];null!==a.index&&b.remove(a.index);for(var g in a.attributes)b.remove(a.attributes[g]);h.removeEventListener("dispose",d);delete e[h.id];if(g=f[a.id])b.remove(g),delete f[a.id];c.memory.geometries--}var e={},f={};return{get:function(a,b){var f=e[b.id];if(f)return f;b.addEventListener("dispose",d);b.isBufferGeometry?
15641 f=b:b.isGeometry&&(void 0===b._bufferGeometry&&(b._bufferGeometry=(new C).setFromObject(a)),f=b._bufferGeometry);e[b.id]=f;c.memory.geometries++;return f},update:function(c){var d=c.index,e=c.attributes;null!==d&&b.update(d,a.ELEMENT_ARRAY_BUFFER);for(var f in e)b.update(e[f],a.ARRAY_BUFFER);c=c.morphAttributes;for(f in c){d=c[f];e=0;for(var 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,g=c.attributes;if(null!==
15642 e){e=e.array;g=0;for(var q=e.length;g<q;g+=3){var n=e[g+0],t=e[g+1],u=e[g+2];d.push(n,t,t,u,u,n)}}else for(e=g.position.array,g=0,q=e.length/3-1;g<q;g+=3)n=g+0,t=g+1,u=g+2,d.push(n,t,t,u,u,n);d=new (65535<Fe(d)?jb:ib)(d,1);b.update(d,a.ELEMENT_ARRAY_BUFFER);return f[c.id]=d}}}function Rf(a,b,c,d){var e,f,g;this.setMode=function(a){e=a};this.setIndex=function(a){f=a.type;g=a.bytesPerElement};this.render=function(b,d){a.drawElements(e,d,f,b*g);c.update(d,e)};this.renderInstances=function(h,k,m){if(d.isWebGL2)var q=
15643 a;else if(q=b.get("ANGLE_instanced_arrays"),null===q){console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");return}q[d.isWebGL2?"drawElementsInstanced":"drawElementsInstancedANGLE"](e,m,f,k*g,h.maxInstancedCount);c.update(m,e,h.maxInstancedCount)}}function Sf(a){var b={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:b,programs:null,autoReset:!0,reset:function(){b.frame++;
15644 b.calls=0;b.triangles=0;b.points=0;b.lines=0},update:function(c,d,e){e=e||1;b.calls++;switch(d){case a.TRIANGLES:b.triangles+=c/3*e;break;case a.TRIANGLE_STRIP:case a.TRIANGLE_FAN:b.triangles+=e*(c-2);break;case a.LINES:b.lines+=c/2*e;break;case a.LINE_STRIP:b.lines+=e*(c-1);break;case a.LINE_LOOP:b.lines+=e*c;break;case a.POINTS:b.points+=e*c;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",d)}}}}function Tf(a,b){return Math.abs(b[1])-Math.abs(a[1])}function Uf(a){var b={},c=new Float32Array(8);
15645 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 m=0;m<k;m++)d[m]=[m,0];b[e.id]=d}var q=f.morphTargets&&e.morphAttributes.position;f=f.morphNormals&&e.morphAttributes.normal;for(m=0;m<k;m++){var n=d[m];0!==n[1]&&(q&&e.removeAttribute("morphTarget"+m),f&&e.removeAttribute("morphNormal"+m))}for(m=0;m<k;m++)n=d[m],n[0]=m,n[1]=h[m];d.sort(Tf);for(m=0;8>m;m++){if(n=d[m])if(h=n[0],k=n[1]){q&&e.addAttribute("morphTarget"+m,q[h]);f&&e.addAttribute("morphNormal"+
15646 m,f[h]);c[m]=k;continue}c[m]=0}g.getUniforms().setValue(a,"morphTargetInfluences",c)}}}function Vf(a,b){var c={};return{update:function(d){var e=b.render.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},dispose:function(){c={}}}}function Ua(a,b,c,d,e,f,g,h,k,m){a=void 0!==a?a:[];T.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,k,m);this.flipY=!1}function Jb(a,b,c){var d=a[0];if(0>=d||0<d)return a;var e=b*c,f=Ge[e];void 0===f&&(f=new Float32Array(e),
15647 Ge[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 ea(a,b){if(a.length!==b.length)return!1;for(var c=0,d=a.length;c<d;c++)if(a[c]!==b[c])return!1;return!0}function qa(a,b){for(var c=0,d=b.length;c<d;c++)a[c]=b[c]}function He(a,b){var c=Ie[b];void 0===c&&(c=new Int32Array(b),Ie[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function Wf(a,b){var c=this.cache;c[0]!==b&&(a.uniform1f(this.addr,b),c[0]=b)}function Xf(a,b){var c=this.cache;c[0]!==
15648 b&&(a.uniform1i(this.addr,b),c[0]=b)}function Yf(a,b){var c=this.cache;if(void 0!==b.x){if(c[0]!==b.x||c[1]!==b.y)a.uniform2f(this.addr,b.x,b.y),c[0]=b.x,c[1]=b.y}else ea(c,b)||(a.uniform2fv(this.addr,b),qa(c,b))}function Zf(a,b){var c=this.cache;if(void 0!==b.x){if(c[0]!==b.x||c[1]!==b.y||c[2]!==b.z)a.uniform3f(this.addr,b.x,b.y,b.z),c[0]=b.x,c[1]=b.y,c[2]=b.z}else if(void 0!==b.r){if(c[0]!==b.r||c[1]!==b.g||c[2]!==b.b)a.uniform3f(this.addr,b.r,b.g,b.b),c[0]=b.r,c[1]=b.g,c[2]=b.b}else ea(c,b)||(a.uniform3fv(this.addr,
15649 b),qa(c,b))}function $f(a,b){var c=this.cache;if(void 0!==b.x){if(c[0]!==b.x||c[1]!==b.y||c[2]!==b.z||c[3]!==b.w)a.uniform4f(this.addr,b.x,b.y,b.z,b.w),c[0]=b.x,c[1]=b.y,c[2]=b.z,c[3]=b.w}else ea(c,b)||(a.uniform4fv(this.addr,b),qa(c,b))}function ag(a,b){var c=this.cache,d=b.elements;void 0===d?ea(c,b)||(a.uniformMatrix2fv(this.addr,!1,b),qa(c,b)):ea(c,d)||(Je.set(d),a.uniformMatrix2fv(this.addr,!1,Je),qa(c,d))}function bg(a,b){var c=this.cache,d=b.elements;void 0===d?ea(c,b)||(a.uniformMatrix3fv(this.addr,
15650 !1,b),qa(c,b)):ea(c,d)||(Ke.set(d),a.uniformMatrix3fv(this.addr,!1,Ke),qa(c,d))}function cg(a,b){var c=this.cache,d=b.elements;void 0===d?ea(c,b)||(a.uniformMatrix4fv(this.addr,!1,b),qa(c,b)):ea(c,d)||(Le.set(d),a.uniformMatrix4fv(this.addr,!1,Le),qa(c,d))}function dg(a,b,c){var d=this.cache,e=c.allocTextureUnit();d[0]!==e&&(a.uniform1i(this.addr,e),d[0]=e);c.setTexture2D(b||Me,e)}function eg(a,b,c){var d=this.cache,e=c.allocTextureUnit();d[0]!==e&&(a.uniform1i(this.addr,e),d[0]=e);c.setTextureCube(b||
15651 Ne,e)}function Oe(a,b){var c=this.cache;ea(c,b)||(a.uniform2iv(this.addr,b),qa(c,b))}function Pe(a,b){var c=this.cache;ea(c,b)||(a.uniform3iv(this.addr,b),qa(c,b))}function Qe(a,b){var c=this.cache;ea(c,b)||(a.uniform4iv(this.addr,b),qa(c,b))}function fg(a){switch(a){case 5126:return Wf;case 35664:return Yf;case 35665:return Zf;case 35666:return $f;case 35674:return ag;case 35675:return bg;case 35676:return cg;case 35678:case 36198:return dg;case 35680:return eg;case 5124:case 35670:return Xf;case 35667:case 35671:return Oe;
15652 case 35668:case 35672:return Pe;case 35669:case 35673:return Qe}}function gg(a,b){var c=this.cache;ea(c,b)||(a.uniform1fv(this.addr,b),qa(c,b))}function hg(a,b){var c=this.cache;ea(c,b)||(a.uniform1iv(this.addr,b),qa(c,b))}function ig(a,b){var c=this.cache;b=Jb(b,this.size,2);ea(c,b)||(a.uniform2fv(this.addr,b),this.updateCache(b))}function jg(a,b){var c=this.cache;b=Jb(b,this.size,3);ea(c,b)||(a.uniform3fv(this.addr,b),this.updateCache(b))}function kg(a,b){var c=this.cache;b=Jb(b,this.size,4);ea(c,
15653 b)||(a.uniform4fv(this.addr,b),this.updateCache(b))}function lg(a,b){var c=this.cache;b=Jb(b,this.size,4);ea(c,b)||(a.uniformMatrix2fv(this.addr,!1,b),this.updateCache(b))}function mg(a,b){var c=this.cache;b=Jb(b,this.size,9);ea(c,b)||(a.uniformMatrix3fv(this.addr,!1,b),this.updateCache(b))}function ng(a,b){var c=this.cache;b=Jb(b,this.size,16);ea(c,b)||(a.uniformMatrix4fv(this.addr,!1,b),this.updateCache(b))}function og(a,b,c){var d=this.cache,e=b.length,f=He(c,e);!1===ea(d,f)&&(a.uniform1iv(this.addr,
15654 f),qa(d,f));for(a=0;a!==e;++a)c.setTexture2D(b[a]||Me,f[a])}function pg(a,b,c){var d=this.cache,e=b.length,f=He(c,e);!1===ea(d,f)&&(a.uniform1iv(this.addr,f),qa(d,f));for(a=0;a!==e;++a)c.setTextureCube(b[a]||Ne,f[a])}function qg(a){switch(a){case 5126:return gg;case 35664:return ig;case 35665:return jg;case 35666:return kg;case 35674:return lg;case 35675:return mg;case 35676:return ng;case 35678:return og;case 35680:return pg;case 5124:case 35670:return hg;case 35667:case 35671:return Oe;case 35668:case 35672:return Pe;
15655 case 35669:case 35673:return Qe}}function rg(a,b,c){this.id=a;this.addr=c;this.cache=[];this.setValue=fg(b.type)}function Re(a,b,c){this.id=a;this.addr=c;this.cache=[];this.size=b.size;this.setValue=qg(b.type)}function Se(a){this.id=a;this.seq=[];this.map={}}function Za(a,b,c){this.seq=[];this.map={};this.renderer=c;c=a.getProgramParameter(b,a.ACTIVE_UNIFORMS);for(var d=0;d<c;++d){var e=a.getActiveUniform(b,d),f=a.getUniformLocation(b,e.name),g=this,h=e.name,k=h.length;for(Vd.lastIndex=0;;){var m=
15656 Vd.exec(h),q=Vd.lastIndex,n=m[1],t=m[3];"]"===m[2]&&(n|=0);if(void 0===t||"["===t&&q+2===k){h=g;e=void 0===t?new rg(n,e,f):new Re(n,e,f);h.seq.push(e);h.map[e.id]=e;break}else t=g.map[n],void 0===t&&(t=new Se(n),n=g,g=t,n.seq.push(g),n.map[g.id]=g),g=t}}}function sg(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function Te(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.");
15657 ""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),sg(c));return d}function Ue(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: "+
15658 a);}}function Wd(a,b){b=Ue(b);return"vec4 "+a+"( vec4 value ) { return "+b[0]+"ToLinear"+b[1]+"; }"}function tg(a,b){b=Ue(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+b[0]+b[1]+"; }"}function ug(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 vg(a,b,c){a=a||{};return[a.derivatives||
15659 b.envMapCubeUV||b.bumpMap||b.normalMap&&!b.objectSpaceNormalMap||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(vc).join("\n")}function wg(a){var b=[],c;for(c in a){var d=
15660 a[c];!1!==d&&b.push("#define "+c+" "+d)}return b.join("\n")}function vc(a){return""!==a}function Ve(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 We(a,b){return a.replace(/NUM_CLIPPING_PLANES/g,b.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,b.numClippingPlanes-b.numClipIntersection)}function Xd(a){return a.replace(/^[ \t]*#include +<([\w\d./]+)>/gm,
15661 function(a,c){a=S[c];if(void 0===a)throw Error("Can not resolve #include <"+c+">");return Xd(a)})}function Xe(a){return a.replace(/#pragma unroll_loop[\s]+?for \( int i = (\d+); i < (\d+); i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);c<parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function xg(a,b,c,d,e,f,g){var h=a.context,k=d.defines,m=e.vertexShader,q=e.fragmentShader,n="SHADOWMAP_TYPE_BASIC";1===f.shadowMapType?n="SHADOWMAP_TYPE_PCF":2===f.shadowMapType&&
15662 (n="SHADOWMAP_TYPE_PCF_SOFT");var t="ENVMAP_TYPE_CUBE",u="ENVMAP_MODE_REFLECTION",r="ENVMAP_BLENDING_MULTIPLY";if(f.envMap){switch(d.envMap.mapping){case 301:case 302:t="ENVMAP_TYPE_CUBE";break;case 306:case 307:t="ENVMAP_TYPE_CUBE_UV";break;case 303:case 304:t="ENVMAP_TYPE_EQUIREC";break;case 305:t="ENVMAP_TYPE_SPHERE"}switch(d.envMap.mapping){case 302:case 304:u="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 l=
15663 0<a.gammaFactor?a.gammaFactor:1,y=g.isWebGL2?"":vg(d.extensions,f,b),p=wg(k),w=h.createProgram();d.isRawShaderMaterial?(k=[p].filter(vc).join("\n"),0<k.length&&(k+="\n"),b=[y,p].filter(vc).join("\n"),0<b.length&&(b+="\n")):(k=["precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,p,f.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+l,"#define MAX_BONES "+f.maxBones,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":
15664 "",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+u:"",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.normalMap&&f.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",f.displacementMap&&f.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":
15665 "",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&&!1===f.flatShading?"#define USE_MORPHNORMALS":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"",f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+
15666 n:"",f.sizeAttenuation?"#define USE_SIZEATTENUATION":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&(g.isWebGL2||b.get("EXT_frag_depth"))?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;",
15667 "#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;","\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",
15668 "#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(vc).join("\n"),b=[y,"precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,p,f.alphaTest?"#define ALPHATEST "+f.alphaTest+(f.alphaTest%1?"":".0"):"","#define GAMMA_FACTOR "+l,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.envMap?"#define "+
15669 u:"",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.normalMap&&f.objectSpaceNormalMap?"#define OBJECTSPACE_NORMALMAP":"",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.gradientMap?
15670 "#define USE_GRADIENTMAP":"",f.flatShading?"#define FLAT_SHADED":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"",f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+n:"",f.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",f.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&(g.isWebGL2||b.get("EXT_frag_depth"))?"#define USE_LOGDEPTHBUF_EXT":"",f.envMap&&
15671 (g.isWebGL2||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?S.tonemapping_pars_fragment:"",0!==f.toneMapping?ug("toneMapping",f.toneMapping):"",f.dithering?"#define DITHERING":"",f.outputEncoding||f.mapEncoding||f.envMapEncoding||f.emissiveMapEncoding?S.encodings_pars_fragment:"",f.mapEncoding?Wd("mapTexelToLinear",f.mapEncoding):"",f.envMapEncoding?Wd("envMapTexelToLinear",
15672 f.envMapEncoding):"",f.emissiveMapEncoding?Wd("emissiveMapTexelToLinear",f.emissiveMapEncoding):"",f.outputEncoding?tg("linearToOutputTexel",f.outputEncoding):"",f.depthPacking?"#define DEPTH_PACKING "+d.depthPacking:"","\n"].filter(vc).join("\n"));m=Xd(m);m=Ve(m,f);m=We(m,f);q=Xd(q);q=Ve(q,f);q=We(q,f);m=Xe(m);q=Xe(q);g.isWebGL2&&!d.isRawShaderMaterial&&(g=!1,n=/^\s*#version\s+300\s+es\s*\n/,d.isShaderMaterial&&null!==m.match(n)&&null!==q.match(n)&&(g=!0,m=m.replace(n,""),q=q.replace(n,"")),k="#version 300 es\n\n#define attribute in\n#define varying out\n#define texture2D texture\n"+
15673 k,b=["#version 300 es\n\n#define varying in",g?"":"out highp vec4 pc_fragColor;",g?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth\n#define texture2D texture\n#define textureCube texture\n#define texture2DProj textureProj\n#define texture2DLodEXT textureLod\n#define texture2DProjLodEXT textureProjLod\n#define textureCubeLodEXT textureLod\n#define texture2DGradEXT textureGrad\n#define texture2DProjGradEXT textureProjGrad\n#define textureCubeGradEXT textureGrad"].join("\n")+
15674 "\n"+b);q=b+q;m=Te(h,h.VERTEX_SHADER,k+m);q=Te(h,h.FRAGMENT_SHADER,q);h.attachShader(w,m);h.attachShader(w,q);void 0!==d.index0AttributeName?h.bindAttribLocation(w,0,d.index0AttributeName):!0===f.morphTargets&&h.bindAttribLocation(w,0,"position");h.linkProgram(w);f=h.getProgramInfoLog(w).trim();g=h.getShaderInfoLog(m).trim();n=h.getShaderInfoLog(q).trim();u=t=!0;if(!1===h.getProgramParameter(w,h.LINK_STATUS))t=!1,console.error("THREE.WebGLProgram: shader error: ",h.getError(),"gl.VALIDATE_STATUS",
15675 h.getProgramParameter(w,h.VALIDATE_STATUS),"gl.getProgramInfoLog",f,g,n);else if(""!==f)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",f);else if(""===g||""===n)u=!1;u&&(this.diagnostics={runnable:t,material:d,programLog:f,vertexShader:{log:g,prefix:k},fragmentShader:{log:n,prefix:b}});h.deleteShader(m);h.deleteShader(q);var B;this.getUniforms=function(){void 0===B&&(B=new Za(h,w,a));return B};var E;this.getAttributes=function(){if(void 0===E){for(var a={},b=h.getProgramParameter(w,h.ACTIVE_ATTRIBUTES),
15676 c=0;c<b;c++){var d=h.getActiveAttrib(w,c).name;a[d]=h.getAttribLocation(w,d)}E=a}return E};this.destroy=function(){h.deleteProgram(w);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.name=e.name;this.id=yg++;this.code=c;this.usedTimes=1;this.program=
15677 w;this.vertexShader=m;this.fragmentShader=q;return this}function zg(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",
15678 MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"},g="precision supportsVertexTextures map mapEncoding envMap envMapMode envMapEncoding lightMap aoMap emissiveMap emissiveMapEncoding bumpMap normalMap objectSpaceNormalMap 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(" ");
15679 this.getParameters=function(b,e,g,q,n,t,u){var h=f[b.type];if(u.isSkinnedMesh){var k=u.skeleton.bones;if(c.floatVertexTextures)k=1024;else{var m=Math.min(Math.floor((c.maxVertexUniforms-20)/4),k.length);m<k.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+k.length+" bones. This GPU supports "+m+"."),k=0):k=m}}else k=0;m=c.precision;null!==b.precision&&(m=c.getMaxPrecision(b.precision),m!==b.precision&&console.warn("THREE.WebGLProgram.getParameters:",b.precision,"not supported, using",m,"instead."));
15680 var l=a.getRenderTarget();return{shaderID:h,precision:m,supportsVertexTextures:c.vertexTextures,outputEncoding:d(l?l.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,
15681 objectSpaceNormalMap:1===b.normalMapType,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<k,maxBones:k,useVertexTexture:c.floatVertexTextures,morphTargets:b.morphTargets,
15682 morphNormals:b.morphNormals,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&&u.receiveShadow&&0<g.length,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:b.premultipliedAlpha,
15683 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(d,f,g,q){for(var h,k=0,m=e.length;k<
15684 m;k++){var r=e[k];if(r.code===q){h=r;++h.usedTimes;break}}void 0===h&&(h=new xg(a,b,q,d,f,g,c),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 Ag(){var a=new WeakMap;return{get:function(b){var c=a.get(b);void 0===c&&(c={},a.set(b,c));return c},remove:function(b){a.delete(b)},update:function(b,c,d){a.get(b)[c]=d},dispose:function(){a=new WeakMap}}}function Bg(a,b){return a.renderOrder!==
15685 b.renderOrder?a.renderOrder-b.renderOrder:a.program&&b.program&&a.program!==b.program?a.program.id-b.program.id:a.material.id!==b.material.id?a.material.id-b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function Cg(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function Dg(){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 m=a[b];void 0===m?(m={id:e.id,object:e,geometry:f,material:g,
15686 program:g.program,renderOrder:e.renderOrder,z:h,group:k},a[b]=m):(m.id=e.id,m.object=e,m.geometry=f,m.material=g,m.program=g.program,m.renderOrder=e.renderOrder,m.z=h,m.group=k);(!0===g.transparent?d:c).push(m);b++},sort:function(){1<c.length&&c.sort(Bg);1<d.length&&d.sort(Cg)}}}function Eg(){var a={};return{get:function(b,c){b=b.id+","+c.id;c=a[b];void 0===c&&(c=new Dg,a[b]=c);return c},dispose:function(){a={}}}}function Fg(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];switch(b.type){case "DirectionalLight":var c=
15687 {direction:new p,color:new G,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new z};break;case "SpotLight":c={position:new p,direction:new p,color:new G,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new z};break;case "PointLight":c={position:new p,color:new G,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new z,shadowCameraNear:1,shadowCameraFar:1E3};break;case "HemisphereLight":c={direction:new p,skyColor:new G,groundColor:new G};
15688 break;case "RectAreaLight":c={color:new G,position:new p,halfWidth:new p,halfHeight:new p}}return a[b.id]=c}}}function Gg(){var a=new Fg,b={id:Hg++,hash:{stateID:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,shadowsLength:-1},ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]},c=new p,d=new I,e=new I;return{setup:function(f,
15689 g,h){var k=0,m=0,q=0,n=0,t=0,u=0,r=0,l=0;h=h.matrixWorldInverse;for(var y=0,p=f.length;y<p;y++){var w=f[y],B=w.color,E=w.intensity,P=w.distance,N=w.shadow&&w.shadow.map?w.shadow.map.texture:null;if(w.isAmbientLight)k+=B.r*E,m+=B.g*E,q+=B.b*E;else if(w.isDirectionalLight){var O=a.get(w);O.color.copy(w.color).multiplyScalar(w.intensity);O.direction.setFromMatrixPosition(w.matrixWorld);c.setFromMatrixPosition(w.target.matrixWorld);O.direction.sub(c);O.direction.transformDirection(h);if(O.shadow=w.castShadow)B=
15690 w.shadow,O.shadowBias=B.bias,O.shadowRadius=B.radius,O.shadowMapSize=B.mapSize;b.directionalShadowMap[n]=N;b.directionalShadowMatrix[n]=w.shadow.matrix;b.directional[n]=O;n++}else if(w.isSpotLight){O=a.get(w);O.position.setFromMatrixPosition(w.matrixWorld);O.position.applyMatrix4(h);O.color.copy(B).multiplyScalar(E);O.distance=P;O.direction.setFromMatrixPosition(w.matrixWorld);c.setFromMatrixPosition(w.target.matrixWorld);O.direction.sub(c);O.direction.transformDirection(h);O.coneCos=Math.cos(w.angle);
15691 O.penumbraCos=Math.cos(w.angle*(1-w.penumbra));O.decay=0===w.distance?0:w.decay;if(O.shadow=w.castShadow)B=w.shadow,O.shadowBias=B.bias,O.shadowRadius=B.radius,O.shadowMapSize=B.mapSize;b.spotShadowMap[u]=N;b.spotShadowMatrix[u]=w.shadow.matrix;b.spot[u]=O;u++}else if(w.isRectAreaLight)O=a.get(w),O.color.copy(B).multiplyScalar(E),O.position.setFromMatrixPosition(w.matrixWorld),O.position.applyMatrix4(h),e.identity(),d.copy(w.matrixWorld),d.premultiply(h),e.extractRotation(d),O.halfWidth.set(.5*w.width,
15692 0,0),O.halfHeight.set(0,.5*w.height,0),O.halfWidth.applyMatrix4(e),O.halfHeight.applyMatrix4(e),b.rectArea[r]=O,r++;else if(w.isPointLight){O=a.get(w);O.position.setFromMatrixPosition(w.matrixWorld);O.position.applyMatrix4(h);O.color.copy(w.color).multiplyScalar(w.intensity);O.distance=w.distance;O.decay=0===w.distance?0:w.decay;if(O.shadow=w.castShadow)B=w.shadow,O.shadowBias=B.bias,O.shadowRadius=B.radius,O.shadowMapSize=B.mapSize,O.shadowCameraNear=B.camera.near,O.shadowCameraFar=B.camera.far;
15693 b.pointShadowMap[t]=N;b.pointShadowMatrix[t]=w.shadow.matrix;b.point[t]=O;t++}else w.isHemisphereLight&&(O=a.get(w),O.direction.setFromMatrixPosition(w.matrixWorld),O.direction.transformDirection(h),O.direction.normalize(),O.skyColor.copy(w.color).multiplyScalar(E),O.groundColor.copy(w.groundColor).multiplyScalar(E),b.hemi[l]=O,l++)}b.ambient[0]=k;b.ambient[1]=m;b.ambient[2]=q;b.directional.length=n;b.spot.length=u;b.rectArea.length=r;b.point.length=t;b.hemi.length=l;b.hash.stateID=b.id;b.hash.directionalLength=
15694 n;b.hash.pointLength=t;b.hash.spotLength=u;b.hash.rectAreaLength=r;b.hash.hemiLength=l;b.hash.shadowsLength=g.length},state:b}}function Ye(){var a=new Gg,b=[],c=[];return{init:function(){b.length=0;c.length=0},state:{lightsArray:b,shadowsArray:c,lights:a},setupLights:function(d){a.setup(b,c,d)},pushLight:function(a){b.push(a)},pushShadow:function(a){c.push(a)}}}function Ig(){var a={};return{get:function(b,c){if(void 0===a[b.id]){var d=new Ye;a[b.id]={};a[b.id][c.id]=d}else void 0===a[b.id][c.id]?
15695 (d=new Ye,a[b.id][c.id]=d):d=a[b.id][c.id];return d},dispose:function(){a={}}}}function $a(a){J.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=this.skinning=!1;this.displacementMap=this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.lights=this.fog=!1;this.setValues(a)}function ab(a){J.call(this);this.type="MeshDistanceMaterial";this.referencePosition=new p;this.nearDistance=1;this.farDistance=
15696 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 Ze(a,b,c){function d(b,c,d,e,f,g){var h=b.geometry;var k=n;var m=b.customDepthMaterial;d&&(k=t,m=b.customDistanceMaterial);m?k=m:(m=!1,c.morphTargets&&(h&&h.isBufferGeometry?m=h.morphAttributes&&h.morphAttributes.position&&0<h.morphAttributes.position.length:h&&h.isGeometry&&(m=h.morphTargets&&0<h.morphTargets.length)),
15697 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,m&&(h|=1),b&&(h|=2),k=k[h]);a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length&&(h=k.uuid,m=c.uuid,b=u[h],void 0===b&&(b={},u[h]=b),h=b[m],void 0===h&&(h=k.clone(),b[m]=h),k=h);k.visible=c.visible;k.wireframe=c.wireframe;k.side=null!=c.shadowSide?c.shadowSide:r[c.side];k.clipShadows=c.clipShadows;k.clippingPlanes=c.clippingPlanes;
15698 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}function e(c,g,h,k){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 m=b.update(c),n=c.material;if(Array.isArray(n))for(var t=m.groups,
15699 u=0,r=t.length;u<r;u++){var l=t[u],P=n[l.materialIndex];P&&P.visible&&(P=d(c,P,k,q,h.near,h.far),a.renderBufferDirect(h,null,m,P,c,l))}else n.visible&&(P=d(c,n,k,q,h.near,h.far),a.renderBufferDirect(h,null,m,P,c,null))}c=c.children;m=0;for(n=c.length;m<n;m++)e(c[m],g,h,k)}}var f=new md,g=new I,h=new z,k=new z(c,c),m=new p,q=new p,n=Array(4),t=Array(4),u={},r={0:1,1:0,2:2},l=[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)],y=[new p(0,1,0),new p(0,1,0),new p(0,1,0),
15700 new p(0,1,0),new p(0,0,1),new p(0,0,-1)],x=[new V,new V,new V,new V,new V,new V];for(c=0;4!==c;++c){var w=0!==(c&1),B=0!==(c&2),E=new $a({depthPacking:3201,morphTargets:w,skinning:B});n[c]=E;w=new ab({morphTargets:w,skinning:B});t[c]=w}var P=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.render=function(b,c,d){if(!1!==P.enabled&&(!1!==P.autoUpdate||!1!==P.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);
15701 n.setScissorTest(!1);for(var t,u=0,r=b.length;u<r;u++){var v=b[u];t=v.shadow;var p=v&&v.isPointLight;if(void 0===t)console.warn("THREE.WebGLShadowMap:",v,"has no shadow.");else{var w=t.camera;h.copy(t.mapSize);h.min(k);if(p){var N=h.x,E=h.y;x[0].set(2*N,E,N,E);x[1].set(0,E,N,E);x[2].set(3*N,E,N,E);x[3].set(N,E,N,E);x[4].set(3*N,0,N,E);x[5].set(N,0,N,E);h.x*=4;h.y*=2}null===t.map&&(t.map=new fb(h.x,h.y,{minFilter:1003,magFilter:1003,format:1023}),t.map.texture.name=v.name+".shadowMap",w.updateProjectionMatrix());
15702 t.isSpotLightShadow&&t.update(v);N=t.map;E=t.matrix;q.setFromMatrixPosition(v.matrixWorld);w.position.copy(q);p?(t=6,E.makeTranslation(-q.x,-q.y,-q.z)):(t=1,m.setFromMatrixPosition(v.target.matrixWorld),w.lookAt(m),w.updateMatrixWorld(),E.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),E.multiply(w.projectionMatrix),E.multiply(w.matrixWorldInverse));a.setRenderTarget(N);a.clear();for(v=0;v<t;v++)p&&(m.copy(w.position),m.add(l[v]),w.up.copy(y[v]),w.lookAt(m),w.updateMatrixWorld(),n.viewport(x[v])),g.multiplyMatrices(w.projectionMatrix,
15703 w.matrixWorldInverse),f.setFromMatrix(g),e(c,d,w,p)}}P.needsUpdate=!1}}}function Jg(a,b,c,d){function e(b,c,d){var e=new Uint8Array(4),f=a.createTexture();a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b<d;b++)a.texImage2D(c+b,0,a.RGBA,1,1,0,a.RGBA,a.UNSIGNED_BYTE,e);return f}function f(c,e){x[c]=1;0===w[c]&&(a.enableVertexAttribArray(c),w[c]=1);B[c]!==e&&((d.isWebGL2?a:b.get("ANGLE_instanced_arrays"))[d.isWebGL2?"vertexAttribDivisor":
15704 "vertexAttribDivisorANGLE"](c,e),B[c]=e)}function g(b){!0!==E[b]&&(a.enable(b),E[b]=!0)}function h(b){!1!==E[b]&&(a.disable(b),E[b]=!1)}function k(b,d,e,f,k,m,n,q){0!==b?g(a.BLEND):h(a.BLEND);if(5!==b){if(b!==O||q!==C)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),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,
15705 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,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,
15706 a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA))}D=A=Ud=Td=Sd=z=null}else{k=k||d;m=m||e;n=n||f;if(d!==z||k!==Ud)a.blendEquationSeparate(c.convert(d),c.convert(k)),z=d,Ud=k;if(e!==Sd||f!==Td||m!==A||n!==D)a.blendFuncSeparate(c.convert(e),c.convert(f),c.convert(m),c.convert(n)),Sd=e,Td=f,A=m,D=n}O=b;C=q}function m(b){G!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),G=b)}function q(b){0!==b?(g(a.CULL_FACE),b!==K&&(1===b?a.cullFace(a.BACK):2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):h(a.CULL_FACE);
15707 K=b}function n(b,c,d){if(b){if(g(a.POLYGON_OFFSET_FILL),R!==c||I!==d)a.polygonOffset(c,d),R=c,I=d}else h(a.POLYGON_OFFSET_FILL)}function t(b){void 0===b&&(b=a.TEXTURE0+J-1);Q!==b&&(a.activeTexture(b),Q=b)}var u=new function(){var b=!1,c=new V,d=null,e=new V(0,0,0,0);return{setMask:function(c){d===c||b||(a.colorMask(c,c,c,c),d=c)},setLocked:function(a){b=a},setClear:function(b,d,f,g,h){!0===h&&(b*=g,d*=g,f*=g);c.set(b,d,f,g);!1===e.equals(c)&&(a.clearColor(b,d,f,g),e.copy(c))},reset:function(){b=!1;
15708 d=null;e.set(-1,0,0,0)}}},r=new function(){var b=!1,c=null,d=null,e=null;return{setTest:function(b){b?g(a.DEPTH_TEST):h(a.DEPTH_TEST)},setMask:function(d){c===d||b||(a.depthMask(d),c=d)},setFunc:function(b){if(d!==b){if(b)switch(b){case 0:a.depthFunc(a.NEVER);break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);break;case 4:a.depthFunc(a.EQUAL);break;case 5:a.depthFunc(a.GEQUAL);break;case 6:a.depthFunc(a.GREATER);break;case 7:a.depthFunc(a.NOTEQUAL);
15709 break;default:a.depthFunc(a.LEQUAL)}else a.depthFunc(a.LEQUAL);d=b}},setLocked:function(a){b=a},setClear:function(b){e!==b&&(a.clearDepth(b),e=b)},reset:function(){b=!1;e=d=c=null}}},l=new function(){var b=!1,c=null,d=null,e=null,f=null,k=null,m=null,n=null,q=null;return{setTest:function(b){b?g(a.STENCIL_TEST):h(a.STENCIL_TEST)},setMask:function(d){c===d||b||(a.stencilMask(d),c=d)},setFunc:function(b,c,g){if(d!==b||e!==c||f!==g)a.stencilFunc(b,c,g),d=b,e=c,f=g},setOp:function(b,c,d){if(k!==b||m!==
15710 c||n!==d)a.stencilOp(b,c,d),k=b,m=c,n=d},setLocked:function(a){b=a},setClear:function(b){q!==b&&(a.clearStencil(b),q=b)},reset:function(){b=!1;q=n=m=k=f=e=d=c=null}}},p=a.getParameter(a.MAX_VERTEX_ATTRIBS),x=new Uint8Array(p),w=new Uint8Array(p),B=new Uint8Array(p),E={},P=null,N=null,O=null,z=null,Sd=null,Td=null,Ud=null,A=null,D=null,C=!1,G=null,K=null,L=null,R=null,I=null,J=a.getParameter(a.MAX_COMBINED_TEXTURE_IMAGE_UNITS),H=!1;p=0;p=a.getParameter(a.VERSION);-1!==p.indexOf("WebGL")?(p=parseFloat(/^WebGL ([0-9])/.exec(p)[1]),
15711 H=1<=p):-1!==p.indexOf("OpenGL ES")&&(p=parseFloat(/^OpenGL ES ([0-9])/.exec(p)[1]),H=2<=p);var Q=null,S={},Y=new V,W=new V,M={};M[a.TEXTURE_2D]=e(a.TEXTURE_2D,a.TEXTURE_2D,1);M[a.TEXTURE_CUBE_MAP]=e(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);u.setClear(0,0,0,1);r.setClear(1);l.setClear(0);g(a.DEPTH_TEST);r.setFunc(3);m(!1);q(1);g(a.CULL_FACE);g(a.BLEND);k(1);return{buffers:{color:u,depth:r,stencil:l},initAttributes:function(){for(var a=0,b=x.length;a<b;a++)x[a]=0},enableAttribute:function(a){f(a,
15712 0)},enableAttributeAndDivisor:f,disableUnusedAttributes:function(){for(var b=0,c=w.length;b!==c;++b)w[b]!==x[b]&&(a.disableVertexAttribArray(b),w[b]=0)},enable:g,disable:h,getCompressedTextureFormats:function(){if(null===P&&(P=[],b.get("WEBGL_compressed_texture_pvrtc")||b.get("WEBGL_compressed_texture_s3tc")||b.get("WEBGL_compressed_texture_etc1")||b.get("WEBGL_compressed_texture_astc")))for(var c=a.getParameter(a.COMPRESSED_TEXTURE_FORMATS),d=0;d<c.length;d++)P.push(c[d]);return P},useProgram:function(b){return N!==
15713 b?(a.useProgram(b),N=b,!0):!1},setBlending:k,setMaterial:function(b,c){2===b.side?h(a.CULL_FACE):g(a.CULL_FACE);var d=1===b.side;c&&(d=!d);m(d);1===b.blending&&!1===b.transparent?k(0):k(b.blending,b.blendEquation,b.blendSrc,b.blendDst,b.blendEquationAlpha,b.blendSrcAlpha,b.blendDstAlpha,b.premultipliedAlpha);r.setFunc(b.depthFunc);r.setTest(b.depthTest);r.setMask(b.depthWrite);u.setMask(b.colorWrite);n(b.polygonOffset,b.polygonOffsetFactor,b.polygonOffsetUnits)},setFlipSided:m,setCullFace:q,setLineWidth:function(b){b!==
15714 L&&(H&&a.lineWidth(b),L=b)},setPolygonOffset:n,setScissorTest:function(b){b?g(a.SCISSOR_TEST):h(a.SCISSOR_TEST)},activeTexture:t,bindTexture:function(b,c){null===Q&&t();var d=S[Q];void 0===d&&(d={type:void 0,texture:void 0},S[Q]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||M[b]),d.type=b,d.texture=c},compressedTexImage2D:function(){try{a.compressedTexImage2D.apply(a,arguments)}catch(U){console.error("THREE.WebGLState:",U)}},texImage2D:function(){try{a.texImage2D.apply(a,arguments)}catch(U){console.error("THREE.WebGLState:",
15715 U)}},scissor:function(b){!1===Y.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),Y.copy(b))},viewport:function(b){!1===W.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),W.copy(b))},reset:function(){for(var b=0;b<w.length;b++)1===w[b]&&(a.disableVertexAttribArray(b),w[b]=0);E={};Q=P=null;S={};K=G=O=N=null;u.reset();r.reset();l.reset()}}}function Kg(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||a.height>b){if("data"in a){console.warn("THREE.WebGLRenderer: image in DataTexture is too big ("+a.width+"x"+a.height+").");
15716 return}b/=Math.max(a.width,a.height);var c=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");c.width=Math.floor(a.width*b);c.height=Math.floor(a.height*b);c.getContext("2d").drawImage(a,0,0,a.width,a.height,0,0,c.width,c.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+c.width+"x"+c.height);return c}return a}function k(a){return H.isPowerOfTwo(a.width)&&H.isPowerOfTwo(a.height)}function m(a,b){return a.generateMipmaps&&b&&1003!==
15717 a.minFilter&&1006!==a.minFilter}function q(b,c,e,f){a.generateMipmap(b);d.get(c).__maxMipLevel=Math.log(Math.max(e,f))*Math.LOG2E}function n(b,c){if(!e.isWebGL2)return b;if(b===a.RGB){if(c===a.FLOAT)return a.RGB32F;if(c===a.HALF_FLOAT)return a.RGB16F;if(c===a.UNSIGNED_BYTE)return a.RGB8}if(b===a.RGBA){if(c===a.FLOAT)return a.RGBA32F;if(c===a.HALF_FLOAT)return a.RGBA16F;if(c===a.UNSIGNED_BYTE)return a.RGBA8}return b}function t(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function u(b){b=
15718 b.target;b.removeEventListener("dispose",u);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}b.isVideoTexture&&delete B[b.id];g.memory.textures--}function r(b){b=b.target;b.removeEventListener("dispose",r);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=
15719 0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.memory.textures--}function l(b,t){var r=d.get(b);if(b.isVideoTexture){var l=b.id,v=g.render.frame;B[l]!==v&&(B[l]=v,b.update())}if(0<b.version&&r.__version!==b.version)if(l=b.image,void 0===l)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined");
15720 else if(!1===l.complete)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{void 0===r.__webglInit&&(r.__webglInit=!0,b.addEventListener("dispose",u),r.__webglTexture=a.createTexture(),g.memory.textures++);c.activeTexture(a.TEXTURE0+t);c.bindTexture(a.TEXTURE_2D,r.__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);t=h(b.image,e.maxTextureSize);
15721 (e.isWebGL2?0:1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(t)&&(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof ImageBitmap)&&(void 0===E&&(E=document.createElementNS("http://www.w3.org/1999/xhtml","canvas")),E.width=H.floorPowerOfTwo(t.width),E.height=H.floorPowerOfTwo(t.height),E.getContext("2d").drawImage(t,0,0,E.width,E.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+t.width+"x"+t.height+"). Resized to "+E.width+
15722 "x"+E.height),t=E);l=k(t);v=f.convert(b.format);var w=f.convert(b.type),y=n(v,w);p(a.TEXTURE_2D,b,l);var P=b.mipmaps;if(b.isDepthTexture){y=a.DEPTH_COMPONENT;if(1015===b.type){if(!e.isWebGL2)throw Error("Float Depth Texture only supported in WebGL2.0");y=a.DEPTH_COMPONENT32F}else e.isWebGL2&&(y=a.DEPTH_COMPONENT16);1026===b.format&&y===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),b.type=
15723 1012,w=f.convert(b.type));1027===b.format&&(y=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,w=f.convert(b.type)));c.texImage2D(a.TEXTURE_2D,0,y,t.width,t.height,0,v,w,null)}else if(b.isDataTexture)if(0<P.length&&l){for(var N=0,x=P.length;N<x;N++){var z=P[N];c.texImage2D(a.TEXTURE_2D,N,y,z.width,z.height,0,v,w,z.data)}b.generateMipmaps=!1;r.__maxMipLevel=P.length-1}else c.texImage2D(a.TEXTURE_2D,0,y,t.width,
15724 t.height,0,v,w,t.data),r.__maxMipLevel=0;else if(b.isCompressedTexture){N=0;for(x=P.length;N<x;N++)z=P[N],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(v)?c.compressedTexImage2D(a.TEXTURE_2D,N,y,z.width,z.height,0,z.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):c.texImage2D(a.TEXTURE_2D,N,y,z.width,z.height,0,v,w,z.data);r.__maxMipLevel=P.length-1}else if(0<P.length&&l){N=0;for(x=P.length;N<x;N++)z=
15725 P[N],c.texImage2D(a.TEXTURE_2D,N,y,v,w,z);b.generateMipmaps=!1;r.__maxMipLevel=P.length-1}else c.texImage2D(a.TEXTURE_2D,0,y,v,w,t),r.__maxMipLevel=0;m(b,l)&&q(a.TEXTURE_2D,b,t.width,t.height);r.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}c.activeTexture(a.TEXTURE0+t);c.bindTexture(a.TEXTURE_2D,r.__webglTexture)}function p(c,g,h){h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f.convert(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,f.convert(g.wrapT)),a.texParameteri(c,a.TEXTURE_MAG_FILTER,f.convert(g.magFilter)),
15726 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."),a.texParameteri(c,a.TEXTURE_MAG_FILTER,t(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,t(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."));
15727 !(h=b.get("EXT_texture_filter_anisotropic"))||1015===g.type&&null===b.get("OES_texture_float_linear")||1016===g.type&&null===(e.isWebGL2||b.get("OES_texture_half_float_linear"))||!(1<g.anisotropy||d.get(g).__currentAnisotropy)||(a.texParameterf(c,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=g.anisotropy)}function x(b,e,g,h){var k=f.convert(e.texture.format),m=f.convert(e.texture.type),q=n(k,m);c.texImage2D(h,0,q,e.width,e.height,0,k,m,null);
15728 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),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,
15729 a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b)):a.renderbufferStorage(a.RENDERBUFFER,a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var B={},E;this.setTexture2D=l;this.setTextureCube=function(b,t){var r=d.get(b);if(6===b.image.length)if(0<b.version&&r.__version!==b.version){r.__image__webglTextureCube||(b.addEventListener("dispose",u),r.__image__webglTextureCube=a.createTexture(),g.memory.textures++);c.activeTexture(a.TEXTURE0+t);c.bindTexture(a.TEXTURE_CUBE_MAP,r.__image__webglTextureCube);
15730 a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);t=b&&b.isCompressedTexture;for(var l=b.image[0]&&b.image[0].isDataTexture,v=[],w=0;6>w;w++)v[w]=t||l?l?b.image[w].image:b.image[w]:h(b.image[w],e.maxCubemapSize);var y=v[0],E=k(y),P=f.convert(b.format),x=f.convert(b.type),N=n(P,x);p(a.TEXTURE_CUBE_MAP,b,E);for(w=0;6>w;w++)if(t)for(var B,z=v[w].mipmaps,A=0,D=z.length;A<D;A++)B=z[A],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(P)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+
15731 w,A,N,B.width,B.height,0,B.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,A,N,B.width,B.height,0,P,x,B.data);else l?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,0,N,v[w].width,v[w].height,0,P,x,v[w].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+w,0,N,P,x,v[w]);r.__maxMipLevel=t?z.length-1:0;m(b,E)&&q(a.TEXTURE_CUBE_MAP,b,y.width,y.height);r.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+
15732 t),c.bindTexture(a.TEXTURE_CUBE_MAP,r.__image__webglTextureCube)};this.setTextureCubeDynamic=function(b,e){c.activeTexture(a.TEXTURE0+e);c.bindTexture(a.TEXTURE_CUBE_MAP,d.get(b).__webglTexture)};this.setupRenderTarget=function(b){var e=d.get(b),f=d.get(b.texture);b.addEventListener("dispose",r);f.__webglTexture=a.createTexture();g.memory.textures++;var h=!0===b.isWebGLRenderTargetCube,n=k(b);if(h){e.__webglFramebuffer=[];for(var t=0;6>t;t++)e.__webglFramebuffer[t]=a.createFramebuffer()}else e.__webglFramebuffer=
15733 a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);p(a.TEXTURE_CUBE_MAP,b.texture,n);for(t=0;6>t;t++)x(e.__webglFramebuffer[t],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+t);m(b.texture,n)&&q(a.TEXTURE_CUBE_MAP,b.texture,b.width,b.height);c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),p(a.TEXTURE_2D,b.texture,n),x(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),m(b.texture,n)&&q(a.TEXTURE_2D,b.texture,b.width,b.height),
15734 c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported");a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&
15735 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);l(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0);else throw Error("Unknown depthTexture format");
15736 }else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),w(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),w(e.__webglDepthbuffer,b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture,f=k(b);if(m(e,f)){f=b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D;var g=d.get(e).__webglTexture;
15737 c.bindTexture(f,g);q(f,e,b.width,b.height);c.bindTexture(f,null)}}}function $e(a,b,c){return{convert:function(d){if(1E3===d)return a.REPEAT;if(1001===d)return a.CLAMP_TO_EDGE;if(1002===d)return a.MIRRORED_REPEAT;if(1003===d)return a.NEAREST;if(1004===d)return a.NEAREST_MIPMAP_NEAREST;if(1005===d)return a.NEAREST_MIPMAP_LINEAR;if(1006===d)return a.LINEAR;if(1007===d)return a.LINEAR_MIPMAP_NEAREST;if(1008===d)return a.LINEAR_MIPMAP_LINEAR;if(1009===d)return a.UNSIGNED_BYTE;if(1017===d)return a.UNSIGNED_SHORT_4_4_4_4;
15738 if(1018===d)return a.UNSIGNED_SHORT_5_5_5_1;if(1019===d)return a.UNSIGNED_SHORT_5_6_5;if(1010===d)return a.BYTE;if(1011===d)return a.SHORT;if(1012===d)return a.UNSIGNED_SHORT;if(1013===d)return a.INT;if(1014===d)return a.UNSIGNED_INT;if(1015===d)return a.FLOAT;if(1016===d){if(c.isWebGL2)return a.HALF_FLOAT;var e=b.get("OES_texture_half_float");if(null!==e)return e.HALF_FLOAT_OES}if(1021===d)return a.ALPHA;if(1022===d)return a.RGB;if(1023===d)return a.RGBA;if(1024===d)return a.LUMINANCE;if(1025===
15739 d)return a.LUMINANCE_ALPHA;if(1026===d)return a.DEPTH_COMPONENT;if(1027===d)return a.DEPTH_STENCIL;if(100===d)return a.FUNC_ADD;if(101===d)return a.FUNC_SUBTRACT;if(102===d)return a.FUNC_REVERSE_SUBTRACT;if(200===d)return a.ZERO;if(201===d)return a.ONE;if(202===d)return a.SRC_COLOR;if(203===d)return a.ONE_MINUS_SRC_COLOR;if(204===d)return a.SRC_ALPHA;if(205===d)return a.ONE_MINUS_SRC_ALPHA;if(206===d)return a.DST_ALPHA;if(207===d)return a.ONE_MINUS_DST_ALPHA;if(208===d)return a.DST_COLOR;if(209===
15740 d)return a.ONE_MINUS_DST_COLOR;if(210===d)return a.SRC_ALPHA_SATURATE;if(33776===d||33777===d||33778===d||33779===d)if(e=b.get("WEBGL_compressed_texture_s3tc"),null!==e){if(33776===d)return e.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===d)return e.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===d)return e.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===d)return e.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===d||35841===d||35842===d||35843===d)if(e=b.get("WEBGL_compressed_texture_pvrtc"),null!==e){if(35840===d)return e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
15741 if(35841===d)return e.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===d)return e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===d)return e.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===d&&(e=b.get("WEBGL_compressed_texture_etc1"),null!==e))return e.COMPRESSED_RGB_ETC1_WEBGL;if(37808===d||37809===d||37810===d||37811===d||37812===d||37813===d||37814===d||37815===d||37816===d||37817===d||37818===d||37819===d||37820===d||37821===d)if(e=b.get("WEBGL_compressed_texture_astc"),null!==e)return d;if(103===d||104===
15742 d){if(c.isWebGL2){if(103===d)return a.MIN;if(104===d)return a.MAX}e=b.get("EXT_blend_minmax");if(null!==e){if(103===d)return e.MIN_EXT;if(104===d)return e.MAX_EXT}}if(1020===d){if(c.isWebGL2)return a.UNSIGNED_INT_24_8;e=b.get("WEBGL_depth_texture");if(null!==e)return e.UNSIGNED_INT_24_8_WEBGL}return 0}}}function Kb(){D.call(this);this.type="Group"}function Z(a,b,c,d){Na.call(this);this.type="PerspectiveCamera";this.fov=void 0!==a?a:50;this.zoom=1;this.near=void 0!==c?c:.1;this.far=void 0!==d?d:2E3;
15743 this.focus=10;this.aspect=void 0!==b?b:1;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}function yc(a){Z.call(this);this.cameras=a||[]}function af(a){function b(){return null!==e&&!0===e.isPresenting}function c(){if(b()){var c=e.getEyeParameters("left"),f=c.renderWidth;c=c.renderHeight;x=a.getPixelRatio();y=a.getSize();a.setDrawingBufferSize(2*f,c,1);B.start()}else d.enabled&&(a.setDrawingBufferSize(y.width,y.height,x),B.stop())}var d=this,e=null,f=null,g=null,h=
15744 [],k=new I,m=new I;"undefined"!==typeof window&&"VRFrameData"in window&&(f=new window.VRFrameData,window.addEventListener("vrdisplaypresentchange",c,!1));var q=new I,n=new fa,t=new p,u=new Z;u.bounds=new V(0,0,.5,1);u.layers.enable(1);var r=new Z;r.bounds=new V(.5,0,.5,1);r.layers.enable(2);var l=new yc([u,r]);l.layers.enable(1);l.layers.enable(2);var y,x,w=[];this.enabled=!1;this.userHeight=1.6;this.getController=function(a){var b=h[a];void 0===b&&(b=new Kb,b.matrixAutoUpdate=!1,b.visible=!1,h[a]=
15745 b);return b};this.getDevice=function(){return e};this.setDevice=function(a){void 0!==a&&(e=a);B.setContext(a)};this.setPoseTarget=function(a){void 0!==a&&(g=a)};this.getCamera=function(a){if(null===e)return a.position.set(0,d.userHeight,0),a;e.depthNear=a.near;e.depthFar=a.far;e.getFrameData(f);var b=e.stageParameters;b?k.fromArray(b.sittingToStandingTransform):k.makeTranslation(0,d.userHeight,0);b=f.pose;var c=null!==g?g:a;c.matrix.copy(k);c.matrix.decompose(c.position,c.quaternion,c.scale);null!==
15746 b.orientation&&(n.fromArray(b.orientation),c.quaternion.multiply(n));null!==b.position&&(n.setFromRotationMatrix(k),t.fromArray(b.position),t.applyQuaternion(n),c.position.add(t));c.updateMatrixWorld();if(!1===e.isPresenting)return a;u.near=a.near;r.near=a.near;u.far=a.far;r.far=a.far;l.matrixWorld.copy(a.matrixWorld);l.matrixWorldInverse.copy(a.matrixWorldInverse);u.matrixWorldInverse.fromArray(f.leftViewMatrix);r.matrixWorldInverse.fromArray(f.rightViewMatrix);m.getInverse(k);u.matrixWorldInverse.multiply(m);
15747 r.matrixWorldInverse.multiply(m);a=c.parent;null!==a&&(q.getInverse(a.matrixWorld),u.matrixWorldInverse.multiply(q),r.matrixWorldInverse.multiply(q));u.matrixWorld.getInverse(u.matrixWorldInverse);r.matrixWorld.getInverse(r.matrixWorldInverse);u.projectionMatrix.fromArray(f.leftProjectionMatrix);r.projectionMatrix.fromArray(f.rightProjectionMatrix);l.projectionMatrix.copy(u.projectionMatrix);a=e.getLayers();a.length&&(a=a[0],null!==a.leftBounds&&4===a.leftBounds.length&&u.bounds.fromArray(a.leftBounds),
15748 null!==a.rightBounds&&4===a.rightBounds.length&&r.bounds.fromArray(a.rightBounds));a:for(a=0;a<h.length;a++){b=h[a];b:{c=a;for(var v=navigator.getGamepads&&navigator.getGamepads(),p=0,y=0,x=v.length;p<x;p++){var E=v[p];if(E&&("Daydream Controller"===E.id||"Gear VR Controller"===E.id||"Oculus Go Controller"===E.id||"OpenVR Gamepad"===E.id||E.id.startsWith("Oculus Touch")||E.id.startsWith("Spatial Controller"))){if(y===c){c=E;break b}y++}}c=void 0}if(void 0!==c&&void 0!==c.pose){if(null===c.pose)break a;
15749 v=c.pose;!1===v.hasPosition&&b.position.set(.2,-.6,-.05);null!==v.position&&b.position.fromArray(v.position);null!==v.orientation&&b.quaternion.fromArray(v.orientation);b.matrix.compose(b.position,b.quaternion,b.scale);b.matrix.premultiply(k);b.matrix.decompose(b.position,b.quaternion,b.scale);b.matrixWorldNeedsUpdate=!0;b.visible=!0;v="Daydream Controller"===c.id?0:1;w[a]!==c.buttons[v].pressed&&(w[a]=c.buttons[v].pressed,!0===w[a]?b.dispatchEvent({type:"selectstart"}):(b.dispatchEvent({type:"selectend"}),
15750 b.dispatchEvent({type:"select"})))}else b.visible=!1}return l};this.getStandingMatrix=function(){return k};this.isPresenting=b;var B=new Qd;this.setAnimationLoop=function(a){B.setAnimationLoop(a)};this.submitFrame=function(){b()&&e.submitFrame()};this.dispose=function(){"undefined"!==typeof window&&window.removeEventListener("vrdisplaypresentchange",c)}}function Lg(a){function b(){return null!==h&&null!==k}function c(a){var b=q[n.indexOf(a.inputSource)];b&&b.dispatchEvent({type:a.type})}function d(){a.setFramebuffer(null);
15751 p.stop()}function e(a,b){null===b?a.matrixWorld.copy(a.matrix):a.matrixWorld.multiplyMatrices(b.matrixWorld,a.matrix);a.matrixWorldInverse.getInverse(a.matrixWorld)}var f=a.context,g=null,h=null,k=null,m=null,q=[],n=[],t=new Z;t.layers.enable(1);t.viewport=new V;var u=new Z;u.layers.enable(2);u.viewport=new V;var r=new yc([t,u]);r.layers.enable(1);r.layers.enable(2);this.enabled=!1;this.getController=function(a){var b=q[a];void 0===b&&(b=new Kb,b.matrixAutoUpdate=!1,b.visible=!1,q[a]=b);return b};
15752 this.getDevice=function(){return g};this.setDevice=function(a){void 0!==a&&(g=a);a instanceof XRDevice&&f.setCompatibleXRDevice(a)};this.setSession=function(b,e){h=b;null!==h&&(h.addEventListener("select",c),h.addEventListener("selectstart",c),h.addEventListener("selectend",c),h.addEventListener("end",d),h.baseLayer=new XRWebGLLayer(h,f),h.requestFrameOfReference(e.frameOfReferenceType).then(function(b){k=b;a.setFramebuffer(h.baseLayer.framebuffer);p.setContext(h);p.start()}),n=h.getInputSources(),
15753 h.addEventListener("inputsourceschange",function(){n=h.getInputSources();console.log(n)}))};this.getCamera=function(a){if(b()){var c=a.parent,d=r.cameras;e(r,c);for(var f=0;f<d.length;f++)e(d[f],c);a.matrixWorld.copy(r.matrixWorld);a=a.children;f=0;for(c=a.length;f<c;f++)a[f].updateMatrixWorld(!0);return r}return a};this.isPresenting=b;var l=null,p=new Qd;p.setAnimationLoop(function(a,b){m=b.getDevicePose(k);if(null!==m)for(var c=h.baseLayer,d=b.views,e=0;e<d.length;e++){var f=d[e],g=c.getViewport(f),
15754 t=m.getViewMatrix(f),u=r.cameras[e];u.matrix.fromArray(t).getInverse(u.matrix);u.projectionMatrix.fromArray(f.projectionMatrix);u.viewport.set(g.x,g.y,g.width,g.height);0===e&&(r.matrix.copy(u.matrix),r.projectionMatrix.copy(u.projectionMatrix))}for(e=0;e<q.length;e++){c=q[e];if(d=n[e])if(d=b.getInputPose(d,k),null!==d){c.matrix.elements=d.pointerMatrix;c.matrix.decompose(c.position,c.rotation,c.scale);c.visible=!0;continue}c.visible=!1}l&&l(a)});this.setAnimationLoop=function(a){l=a};this.dispose=
15755 function(){};this.getStandingMatrix=function(){console.warn("THREE.WebXRManager: getStandingMatrix() is no longer needed.");return new THREE.Matrix4};this.submitFrame=function(){}}function Zd(a){var b;function c(){ha=new Pf(F);ua=new Nf(F,ha,a);ua.isWebGL2||(ha.get("WEBGL_depth_texture"),ha.get("OES_texture_float"),ha.get("OES_texture_half_float"),ha.get("OES_texture_half_float_linear"),ha.get("OES_standard_derivatives"),ha.get("OES_element_index_uint"),ha.get("ANGLE_instanced_arrays"));ha.get("OES_texture_float_linear");
15756 da=new $e(F,ha,ua);ba=new Jg(F,ha,da,ua);ba.scissor(wc.copy(fa).multiplyScalar(U));ba.viewport(T.copy(od).multiplyScalar(U));ca=new Sf(F);Ba=new Ag;ia=new Kg(F,ha,ba,Ba,ua,da,ca);pa=new Ff(F);ra=new Qf(F,pa,ca);ma=new Vf(ra,ca);va=new Uf(F);la=new zg(C,ha,ua);sa=new Eg;na=new Ig;ka=new Lf(C,ba,ma,N);xa=new Mf(F,ha,ca,ua);ya=new Rf(F,ha,ca,ua);ca.programs=la.programs;C.context=F;C.capabilities=ua;C.extensions=ha;C.properties=Ba;C.renderLists=sa;C.state=ba;C.info=ca}function d(a){a.preventDefault();
15757 console.log("THREE.WebGLRenderer: Context Lost.");G=!0}function e(){console.log("THREE.WebGLRenderer: Context Restored.");G=!1;c()}function f(a){a=a.target;a.removeEventListener("dispose",f);g(a);Ba.remove(a)}function g(a){var b=Ba.get(a).program;a.program=void 0;void 0!==b&&la.releaseProgram(b)}function h(a,b){a.render(function(a){C.renderBufferImmediate(a,b)})}function k(a,b,c){if(!1!==a.visible){if(a.layers.test(b.layers))if(a.isLight)D.pushLight(a),a.castShadow&&D.pushShadow(a);else if(a.isSprite){if(!a.frustumCulled||
15758 oa.intersectsSprite(a)){c&&bb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(xc);var d=ma.update(a),e=a.material;A.push(a,d,e,bb.z,null)}}else if(a.isImmediateRenderObject)c&&bb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(xc),A.push(a,null,a.material,bb.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||oa.intersectsObject(a))if(c&&bb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(xc),d=ma.update(a),e=a.material,Array.isArray(e))for(var f=
15759 d.groups,g=0,h=f.length;g<h;g++){var m=f[g],n=e[m.materialIndex];n&&n.visible&&A.push(a,d,n,bb.z,m)}else e.visible&&A.push(a,d,e,bb.z,null);a=a.children;g=0;for(h=a.length;g<h;g++)k(a[g],b,c)}}function m(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,k=g.geometry,m=void 0===d?g.material:d;g=g.group;if(c.isArrayCamera){W=c;for(var n=c.cameras,t=0,u=n.length;t<u;t++){var l=n[t];if(h.layers.test(l.layers)){if("viewport"in l)ba.viewport(T.copy(l.viewport));else{var r=l.bounds;ba.viewport(T.set(r.x*
15760 Z,r.y*M,r.z*Z,r.w*M).multiplyScalar(U))}q(h,b,l,k,m,g)}}}else W=null,q(h,b,c,k,m,g)}}function q(a,c,d,e,f,g){a.onBeforeRender(C,c,d,e,f,g);D=na.get(c,W||d);a.modelViewMatrix.multiplyMatrices(d.matrixWorldInverse,a.matrixWorld);a.normalMatrix.getNormalMatrix(a.modelViewMatrix);if(a.isImmediateRenderObject){ba.setMaterial(f);var k=t(d,c.fog,f,a);S=b=null;nd=!1;h(a,k)}else C.renderBufferDirect(d,c.fog,e,f,a,g);a.onAfterRender(C,c,d,e,f,g);D=na.get(c,W||d)}function n(a,b,c){var d=Ba.get(a),e=D.state.lights,
15761 h=d.lightsHash,k=e.state.hash;c=la.getParameters(a,e.state,D.state.shadowsArray,b,aa.numPlanes,aa.numIntersection,c);var m=la.getProgramCode(a,c),n=d.program,q=!0;if(void 0===n)a.addEventListener("dispose",f);else if(n.code!==m)g(a);else{if(h.stateID!==k.stateID||h.directionalLength!==k.directionalLength||h.pointLength!==k.pointLength||h.spotLength!==k.spotLength||h.rectAreaLength!==k.rectAreaLength||h.hemiLength!==k.hemiLength||h.shadowsLength!==k.shadowsLength)h.stateID=k.stateID,h.directionalLength=
15762 k.directionalLength,h.pointLength=k.pointLength,h.spotLength=k.spotLength,h.rectAreaLength=k.rectAreaLength,h.hemiLength=k.hemiLength,h.shadowsLength=k.shadowsLength;else if(void 0!==c.shaderID)return;q=!1}q&&(c.shaderID?(m=nb[c.shaderID],d.shader={name:a.type,uniforms:Aa.clone(m.uniforms),vertexShader:m.vertexShader,fragmentShader:m.fragmentShader}):d.shader={name:a.type,uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader},a.onBeforeCompile(d.shader,C),m=la.getProgramCode(a,
15763 c),n=la.acquireProgram(a,d.shader,c,m),d.program=n,a.program=n);c=n.getAttributes();if(a.morphTargets)for(m=a.numSupportedMorphTargets=0;m<C.maxMorphTargets;m++)0<=c["morphTarget"+m]&&a.numSupportedMorphTargets++;if(a.morphNormals)for(m=a.numSupportedMorphNormals=0;m<C.maxMorphNormals;m++)0<=c["morphNormal"+m]&&a.numSupportedMorphNormals++;c=d.shader.uniforms;if(!a.isShaderMaterial&&!a.isRawShaderMaterial||!0===a.clipping)d.numClippingPlanes=aa.numPlanes,d.numIntersection=aa.numIntersection,c.clippingPlanes=
15764 aa.uniform;d.fog=b;void 0===h&&(d.lightsHash=h={});h.stateID=k.stateID;h.directionalLength=k.directionalLength;h.pointLength=k.pointLength;h.spotLength=k.spotLength;h.rectAreaLength=k.rectAreaLength;h.hemiLength=k.hemiLength;h.shadowsLength=k.shadowsLength;a.lights&&(c.ambientLightColor.value=e.state.ambient,c.directionalLights.value=e.state.directional,c.spotLights.value=e.state.spot,c.rectAreaLights.value=e.state.rectArea,c.pointLights.value=e.state.point,c.hemisphereLights.value=e.state.hemi,c.directionalShadowMap.value=
15765 e.state.directionalShadowMap,c.directionalShadowMatrix.value=e.state.directionalShadowMatrix,c.spotShadowMap.value=e.state.spotShadowMap,c.spotShadowMatrix.value=e.state.spotShadowMatrix,c.pointShadowMap.value=e.state.pointShadowMap,c.pointShadowMatrix.value=e.state.pointShadowMatrix);a=d.program.getUniforms();a=Za.seqWithValue(a.seq,c);d.uniformsList=a}function t(a,b,c,d){X=0;var e=Ba.get(c),f=e.lightsHash,g=D.state.lights.state.hash;pd&&(Yd||a!==Y)&&aa.setState(c.clippingPlanes,c.clipIntersection,
15766 c.clipShadows,a,e,a===Y&&c.id===J);!1===c.needsUpdate&&(void 0===e.program?c.needsUpdate=!0:c.fog&&e.fog!==b?c.needsUpdate=!0:!c.lights||f.stateID===g.stateID&&f.directionalLength===g.directionalLength&&f.pointLength===g.pointLength&&f.spotLength===g.spotLength&&f.rectAreaLength===g.rectAreaLength&&f.hemiLength===g.hemiLength&&f.shadowsLength===g.shadowsLength?void 0===e.numClippingPlanes||e.numClippingPlanes===aa.numPlanes&&e.numIntersection===aa.numIntersection||(c.needsUpdate=!0):c.needsUpdate=
15767 !0);c.needsUpdate&&(n(c,b,d),c.needsUpdate=!1);var h=!1,k=!1,m=!1;f=e.program;g=f.getUniforms();var q=e.shader.uniforms;ba.useProgram(f.program)&&(m=k=h=!0);c.id!==J&&(J=c.id,k=!0);if(h||a!==Y){g.setValue(F,"projectionMatrix",a.projectionMatrix);ua.logarithmicDepthBuffer&&g.setValue(F,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));Y!==(W||a)&&(Y=W||a,m=k=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)h=g.map.cameraPosition,void 0!==h&&h.setValue(F,bb.setFromMatrixPosition(a.matrixWorld));
15768 (c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||c.isShaderMaterial||c.skinning)&&g.setValue(F,"viewMatrix",a.matrixWorldInverse)}if(c.skinning&&(g.setOptional(F,d,"bindMatrix"),g.setOptional(F,d,"bindMatrixInverse"),a=d.skeleton))if(h=a.bones,ua.floatVertexTextures){if(void 0===a.boneTexture){h=Math.sqrt(4*h.length);h=H.ceilPowerOfTwo(h);h=Math.max(h,4);var t=new Float32Array(h*h*4);t.set(a.boneMatrices);var v=new gb(t,h,h,1023,1015);v.needsUpdate=
15769 !0;a.boneMatrices=t;a.boneTexture=v;a.boneTextureSize=h}g.setValue(F,"boneTexture",a.boneTexture);g.setValue(F,"boneTextureSize",a.boneTextureSize)}else g.setOptional(F,a,"boneMatrices");k&&(g.setValue(F,"toneMappingExposure",C.toneMappingExposure),g.setValue(F,"toneMappingWhitePoint",C.toneMappingWhitePoint),c.lights&&(k=m,q.ambientLightColor.needsUpdate=k,q.directionalLights.needsUpdate=k,q.pointLights.needsUpdate=k,q.spotLights.needsUpdate=k,q.rectAreaLights.needsUpdate=k,q.hemisphereLights.needsUpdate=
15770 k),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?u(q,c):c.isMeshLambertMaterial?(u(q,c),c.emissiveMap&&(q.emissiveMap.value=c.emissiveMap)):c.isMeshPhongMaterial?(u(q,c),c.isMeshToonMaterial?(r(q,c),c.gradientMap&&(q.gradientMap.value=c.gradientMap)):r(q,c)):c.isMeshStandardMaterial?(u(q,c),c.isMeshPhysicalMaterial?(l(q,c),q.reflectivity.value=c.reflectivity,q.clearCoat.value=c.clearCoat,
15771 q.clearCoatRoughness.value=c.clearCoatRoughness):l(q,c)):c.isMeshDepthMaterial?(u(q,c),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias)):c.isMeshDistanceMaterial?(u(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,
15772 q.farDistance.value=c.farDistance):c.isMeshNormalMaterial?(u(q,c),c.bumpMap&&(q.bumpMap.value=c.bumpMap,q.bumpScale.value=c.bumpScale,1===c.side&&(q.bumpScale.value*=-1)),c.normalMap&&(q.normalMap.value=c.normalMap,q.normalScale.value.copy(c.normalScale),1===c.side&&q.normalScale.value.negate()),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=
15773 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*U,q.scale.value=.5*M,q.map.value=c.map,null!==c.map&&(!0===c.map.matrixAutoUpdate&&c.map.updateMatrix(),q.uvTransform.value.copy(c.map.matrix))):c.isSpriteMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,q.rotation.value=c.rotation,q.map.value=c.map,null!==c.map&&(!0===c.map.matrixAutoUpdate&&
15774 c.map.updateMatrix(),q.uvTransform.value.copy(c.map.matrix))):c.isShadowMaterial&&(q.color.value=c.color,q.opacity.value=c.opacity),void 0!==q.ltc_1&&(q.ltc_1.value=K.LTC_1),void 0!==q.ltc_2&&(q.ltc_2.value=K.LTC_2),Za.upload(F,e.uniformsList,q,C));c.isShaderMaterial&&!0===c.uniformsNeedUpdate&&(Za.upload(F,e.uniformsList,q,C),c.uniformsNeedUpdate=!1);c.isSpriteMaterial&&g.setValue(F,"center",d.center);g.setValue(F,"modelViewMatrix",d.modelViewMatrix);g.setValue(F,"normalMatrix",d.normalMatrix);g.setValue(F,
15775 "modelMatrix",d.matrixWorld);return f}function u(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,a.maxMipLevel.value=
15776 Ba.get(b.envMap).__maxMipLevel);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);void 0!==c&&(c.isWebGLRenderTarget&&(c=c.texture),
15777 !0===c.matrixAutoUpdate&&c.updateMatrix(),a.uvTransform.value.copy(c.matrix))}function r(a,b){a.specular.value=b.specular;a.shininess.value=Math.max(b.shininess,1E-4);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale,1===b.side&&(a.bumpScale.value*=-1));b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale),1===b.side&&a.normalScale.value.negate());b.displacementMap&&(a.displacementMap.value=b.displacementMap,
15778 a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias)}function l(a,b){a.roughness.value=b.roughness;a.metalness.value=b.metalness;b.roughnessMap&&(a.roughnessMap.value=b.roughnessMap);b.metalnessMap&&(a.metalnessMap.value=b.metalnessMap);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale,1===b.side&&(a.bumpScale.value*=-1));b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale),
15779 1===b.side&&a.normalScale.value.negate());b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias);b.envMap&&(a.envMapIntensity.value=b.envMapIntensity)}console.log("THREE.WebGLRenderer","95");a=a||{};var y=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),x=void 0!==a.context?a.context:null,w=void 0!==a.alpha?a.alpha:!1,B=void 0!==a.depth?a.depth:!0,E=void 0!==
15780 a.stencil?a.stencil:!0,P=void 0!==a.antialias?a.antialias:!1,N=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,O=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,z=void 0!==a.powerPreference?a.powerPreference:"default",A=null,D=null;this.domElement=y;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=
15781 !1;this.toneMappingWhitePoint=this.toneMappingExposure=this.toneMapping=1;this.maxMorphTargets=8;this.maxMorphNormals=4;var C=this,G=!1,L=null,R=null,Q=null,J=-1;var S=b=null;var nd=!1;var Y=null,W=null,T=new V,wc=new V,ea=null,X=0,Z=y.width,M=y.height,U=1,od=new V(0,0,Z,M),fa=new V(0,0,Z,M),qa=!1,oa=new md,aa=new Of,pd=!1,Yd=!1,xc=new I,bb=new p;try{w={alpha:w,depth:B,stencil:E,antialias:P,premultipliedAlpha:N,preserveDrawingBuffer:O,powerPreference:z};y.addEventListener("webglcontextlost",d,!1);
15782 y.addEventListener("webglcontextrestored",e,!1);var F=x||y.getContext("webgl",w)||y.getContext("experimental-webgl",w);if(null===F){if(null!==y.getContext("webgl"))throw Error("Error creating WebGL context with your selected attributes.");throw Error("Error creating WebGL context.");}void 0===F.getShaderPrecisionFormat&&(F.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(Mg){console.error("THREE.WebGLRenderer: "+Mg.message)}var ha,ua,ba,ca,Ba,ia,pa,ra,ma,la,sa,
15783 na,ka,va,xa,ya,da;c();var ja="xr"in navigator?new Lg(C):new af(C);this.vr=ja;var za=new Ze(C,ma,ua.maxTextureSize);this.shadowMap=za;this.getContext=function(){return F};this.getContextAttributes=function(){return F.getContextAttributes()};this.forceContextLoss=function(){var a=ha.get("WEBGL_lose_context");a&&a.loseContext()};this.forceContextRestore=function(){var a=ha.get("WEBGL_lose_context");a&&a.restoreContext()};this.getPixelRatio=function(){return U};this.setPixelRatio=function(a){void 0!==
15784 a&&(U=a,this.setSize(Z,M,!1))};this.getSize=function(){return{width:Z,height:M}};this.setSize=function(a,b,c){ja.isPresenting()?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(Z=a,M=b,y.width=a*U,y.height=b*U,!1!==c&&(y.style.width=a+"px",y.style.height=b+"px"),this.setViewport(0,0,a,b))};this.getDrawingBufferSize=function(){return{width:Z*U,height:M*U}};this.setDrawingBufferSize=function(a,b,c){Z=a;M=b;U=c;y.width=a*c;y.height=b*c;this.setViewport(0,0,a,b)};
15785 this.getCurrentViewport=function(){return T};this.setViewport=function(a,b,c,d){od.set(a,M-b-d,c,d);ba.viewport(T.copy(od).multiplyScalar(U))};this.setScissor=function(a,b,c,d){fa.set(a,M-b-d,c,d);ba.scissor(wc.copy(fa).multiplyScalar(U))};this.setScissorTest=function(a){ba.setScissorTest(qa=a)};this.getClearColor=function(){return ka.getClearColor()};this.setClearColor=function(){ka.setClearColor.apply(ka,arguments)};this.getClearAlpha=function(){return ka.getClearAlpha()};this.setClearAlpha=function(){ka.setClearAlpha.apply(ka,
15786 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)};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(){y.removeEventListener("webglcontextlost",d,!1);y.removeEventListener("webglcontextrestored",
15787 e,!1);sa.dispose();na.dispose();Ba.dispose();ma.dispose();ja.dispose();ta.stop()};this.renderBufferImmediate=function(a,b){ba.initAttributes();var c=Ba.get(a);a.hasPositions&&!c.position&&(c.position=F.createBuffer());a.hasNormals&&!c.normal&&(c.normal=F.createBuffer());a.hasUvs&&!c.uv&&(c.uv=F.createBuffer());a.hasColors&&!c.color&&(c.color=F.createBuffer());b=b.getAttributes();a.hasPositions&&(F.bindBuffer(F.ARRAY_BUFFER,c.position),F.bufferData(F.ARRAY_BUFFER,a.positionArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.position),
15788 F.vertexAttribPointer(b.position,3,F.FLOAT,!1,0,0));a.hasNormals&&(F.bindBuffer(F.ARRAY_BUFFER,c.normal),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&&(F.bindBuffer(F.ARRAY_BUFFER,c.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&&(F.bindBuffer(F.ARRAY_BUFFER,c.color),F.bufferData(F.ARRAY_BUFFER,a.colorArray,
15789 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,c,d,e,f,g){var h=f.isMesh&&0>f.normalMatrix.determinant();ba.setMaterial(e,h);var k=t(a,c,e,f),m=!1;if(b!==d.id||S!==k.id||nd!==(!0===e.wireframe))b=d.id,S=k.id,nd=!0===e.wireframe,m=!0;f.morphTargetInfluences&&(va.update(f,d,e,k),m=!0);h=d.index;var q=d.attributes.position;c=1;!0===e.wireframe&&
15790 (h=ra.getWireframeAttribute(d),c=2);a=xa;if(null!==h){var n=pa.get(h);a=ya;a.setIndex(n)}if(m){if(d&&d.isInstancedBufferGeometry&!ua.isWebGL2&&null===ha.get("ANGLE_instanced_arrays"))console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{ba.initAttributes();m=d.attributes;k=k.getAttributes();var u=e.defaultAttributeValues;for(N in k){var l=k[N];if(0<=l){var r=m[N];if(void 0!==r){var v=r.normalized,
15791 p=r.itemSize,w=pa.get(r);if(void 0!==w){var y=w.buffer,E=w.type;w=w.bytesPerElement;if(r.isInterleavedBufferAttribute){var x=r.data,B=x.stride;r=r.offset;x&&x.isInstancedInterleavedBuffer?(ba.enableAttributeAndDivisor(l,x.meshPerAttribute),void 0===d.maxInstancedCount&&(d.maxInstancedCount=x.meshPerAttribute*x.count)):ba.enableAttribute(l);F.bindBuffer(F.ARRAY_BUFFER,y);F.vertexAttribPointer(l,p,E,v,B*w,r*w)}else r.isInstancedBufferAttribute?(ba.enableAttributeAndDivisor(l,r.meshPerAttribute),void 0===
15792 d.maxInstancedCount&&(d.maxInstancedCount=r.meshPerAttribute*r.count)):ba.enableAttribute(l),F.bindBuffer(F.ARRAY_BUFFER,y),F.vertexAttribPointer(l,p,E,v,0,0)}}else if(void 0!==u&&(v=u[N],void 0!==v))switch(v.length){case 2:F.vertexAttrib2fv(l,v);break;case 3:F.vertexAttrib3fv(l,v);break;case 4:F.vertexAttrib4fv(l,v);break;default:F.vertexAttrib1fv(l,v)}}}ba.disableUnusedAttributes()}null!==h&&F.bindBuffer(F.ELEMENT_ARRAY_BUFFER,n.buffer)}n=Infinity;null!==h?n=h.count:void 0!==q&&(n=q.count);h=d.drawRange.start*
15793 c;q=null!==g?g.start*c:0;var N=Math.max(h,q);g=Math.max(0,Math.min(n,h+d.drawRange.count*c,q+(null!==g?g.count*c:Infinity))-1-N+1);if(0!==g){if(f.isMesh)if(!0===e.wireframe)ba.setLineWidth(e.wireframeLinewidth*(null===R?U:1)),a.setMode(F.LINES);else switch(f.drawMode){case 0:a.setMode(F.TRIANGLES);break;case 1:a.setMode(F.TRIANGLE_STRIP);break;case 2:a.setMode(F.TRIANGLE_FAN)}else f.isLine?(e=e.linewidth,void 0===e&&(e=1),ba.setLineWidth(e*(null===R?U:1)),f.isLineSegments?a.setMode(F.LINES):f.isLineLoop?
15794 a.setMode(F.LINE_LOOP):a.setMode(F.LINE_STRIP)):f.isPoints?a.setMode(F.POINTS):f.isSprite&&a.setMode(F.TRIANGLES);d&&d.isInstancedBufferGeometry?0<d.maxInstancedCount&&a.renderInstances(d,N,g):a.render(N,g)}};this.compile=function(a,b){D=na.get(a,b);D.init();a.traverse(function(a){a.isLight&&(D.pushLight(a),a.castShadow&&D.pushShadow(a))});D.setupLights(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,
15795 a.fog,b)})};var wa=null,ta=new Qd;ta.setAnimationLoop(function(a){ja.isPresenting()||wa&&wa(a)});"undefined"!==typeof window&&ta.setContext(window);this.setAnimationLoop=function(a){wa=a;ja.setAnimationLoop(a);ta.start()};this.render=function(a,c,d,e){if(!c||!c.isCamera)console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");else if(!G){S=b=null;nd=!1;J=-1;Y=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===c.parent&&c.updateMatrixWorld();ja.enabled&&(c=ja.getCamera(c));
15796 D=na.get(a,c);D.init();a.onBeforeRender(C,a,c,d);xc.multiplyMatrices(c.projectionMatrix,c.matrixWorldInverse);oa.setFromMatrix(xc);Yd=this.localClippingEnabled;pd=aa.init(this.clippingPlanes,Yd,c);A=sa.get(a,c);A.init();k(a,c,C.sortObjects);!0===C.sortObjects&&A.sort();pd&&aa.beginShadows();za.render(D.state.shadowsArray,a,c);D.setupLights(c);pd&&aa.endShadows();this.info.autoReset&&this.info.reset();void 0===d&&(d=null);this.setRenderTarget(d);ka.render(A,a,c,e);e=A.opaque;var f=A.transparent;if(a.overrideMaterial){var g=
15797 a.overrideMaterial;e.length&&m(e,a,c,g);f.length&&m(f,a,c,g)}else e.length&&m(e,a,c),f.length&&m(f,a,c);d&&ia.updateRenderTargetMipmap(d);ba.buffers.depth.setTest(!0);ba.buffers.depth.setMask(!0);ba.buffers.color.setMask(!0);ba.setPolygonOffset(!1);a.onAfterRender(C,a,c);ja.enabled&&ja.submitFrame();D=A=null}};this.allocTextureUnit=function(){var a=X;a>=ua.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+a+" texture units while this GPU supports only "+ua.maxTextures);X+=1;return a};
15798 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);ia.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);ia.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&&
15799 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?ia.setTextureCube(b,c):ia.setTextureCubeDynamic(b,c)}}();this.setFramebuffer=function(a){L=a};this.getRenderTarget=function(){return R};this.setRenderTarget=function(a){(R=a)&&void 0===Ba.get(a).__webglFramebuffer&&ia.setupRenderTarget(a);var b=L,c=!1;a?(b=
15800 Ba.get(a).__webglFramebuffer,a.isWebGLRenderTargetCube&&(b=b[a.activeCubeFace],c=!0),T.copy(a.viewport),wc.copy(a.scissor),ea=a.scissorTest):(T.copy(od).multiplyScalar(U),wc.copy(fa).multiplyScalar(U),ea=qa);Q!==b&&(F.bindFramebuffer(F.FRAMEBUFFER,b),Q=b);ba.viewport(T);ba.scissor(wc);ba.setScissorTest(ea);c&&(c=Ba.get(a.texture),F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,c.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=
15801 function(a,b,c,d,e,f){if(a&&a.isWebGLRenderTarget){var g=Ba.get(a).__webglFramebuffer;if(g){var h=!1;g!==Q&&(F.bindFramebuffer(F.FRAMEBUFFER,g),h=!0);try{var k=a.texture,m=k.format,q=k.type;1023!==m&&da.convert(m)!==F.getParameter(F.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===q||da.convert(q)===F.getParameter(F.IMPLEMENTATION_COLOR_READ_TYPE)||1015===q&&(ua.isWebGL2||ha.get("OES_texture_float")||
15802 ha.get("WEBGL_color_buffer_float"))||1016===q&&(ua.isWebGL2?ha.get("EXT_color_buffer_float"):ha.get("EXT_color_buffer_half_float"))?F.checkFramebufferStatus(F.FRAMEBUFFER)===F.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&F.readPixels(b,c,d,e,da.convert(m),da.convert(q),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&
15803 F.bindFramebuffer(F.FRAMEBUFFER,Q)}}}else console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.")};this.copyFramebufferToTexture=function(a,b,c){var d=b.image.width,e=b.image.height,f=da.convert(b.format);this.setTexture2D(b,0);F.copyTexImage2D(F.TEXTURE_2D,c||0,f,a.x,a.y,d,e,0)};this.copyTextureToTexture=function(a,b,c,d){var e=b.image.width,f=b.image.height,g=da.convert(c.format),h=da.convert(c.type);this.setTexture2D(c,0);b.isDataTexture?F.texSubImage2D(F.TEXTURE_2D,
15804 d||0,a.x,a.y,e,f,g,h,b.image.data):F.texSubImage2D(F.TEXTURE_2D,d||0,a.x,a.y,g,h,b.image)}}function Lb(a,b){this.name="";this.color=new G(a);this.density=void 0!==b?b:2.5E-4}function Mb(a,b,c){this.name="";this.color=new G(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function qd(){D.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function ob(a,b){this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange=
15805 {offset:0,count:-1};this.version=0}function zc(a,b,c,d){this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function cb(a){J.call(this);this.type="SpriteMaterial";this.color=new G(16777215);this.map=null;this.rotation=0;this.lights=!1;this.transparent=!0;this.setValues(a)}function Ac(a){D.call(this);this.type="Sprite";if(void 0===Nb){Nb=new C;var b=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]);b=new ob(b,5);Nb.setIndex([0,1,2,0,2,3]);Nb.addAttribute("position",
15806 new zc(b,3,0,!1));Nb.addAttribute("uv",new zc(b,2,3,!1))}this.geometry=Nb;this.material=void 0!==a?a:new cb;this.center=new z(.5,.5)}function Bc(){D.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Cc(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."),
15807 this.boneInverses=[],a=0,b=this.bones.length;a<b;a++)this.boneInverses.push(new I)}function rd(){D.call(this);this.type="Bone"}function sd(a,b){la.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new I;this.bindMatrixInverse=new I;a=this.initBones();a=new Cc(a);this.bind(a,this.matrixWorld);this.normalizeSkinWeights()}function Y(a){J.call(this);this.type="LineBasicMaterial";this.color=new G(16777215);this.linewidth=1;this.linejoin=this.linecap="round";this.lights=!1;
15808 this.setValues(a)}function sa(a,b,c){1===c&&console.error("THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.");D.call(this);this.type="Line";this.geometry=void 0!==a?a:new C;this.material=void 0!==b?b:new Y({color:16777215*Math.random()})}function W(a,b){sa.call(this,a,b);this.type="LineSegments"}function td(a,b){sa.call(this,a,b);this.type="LineLoop"}function Ea(a){J.call(this);this.type="PointsMaterial";this.color=new G(16777215);this.map=null;this.size=
15809 1;this.sizeAttenuation=!0;this.lights=this.morphTargets=!1;this.setValues(a)}function Ob(a,b){D.call(this);this.type="Points";this.geometry=void 0!==a?a:new C;this.material=void 0!==b?b:new Ea({color:16777215*Math.random()})}function $d(a,b,c,d,e,f,g,h,k){T.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1}function Pb(a,b,c,d,e,f,g,h,k,m,q,n){T.call(this,null,f,g,h,k,m,d,e,q,n);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function Dc(a,b,c,d,e,f,g,h,k){T.call(this,
15810 a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Ec(a,b,c,d,e,f,g,h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==m)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===m&&(c=1012);void 0===c&&1027===m&&(c=1020);T.call(this,null,d,e,f,g,h,m,c,k);this.image={width:a,height:b};this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!==h?h:1003;this.generateMipmaps=this.flipY=!1}function Qb(a){C.call(this);this.type="WireframeGeometry";var b=
15811 [],c,d,e,f=[0,0],g={},h=["a","b","c"];if(a&&a.isGeometry){var k=a.faces;var m=0;for(d=k.length;m<d;m++){var q=k[m];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)m=g[n],h=a.vertices[m.index1],b.push(h.x,h.y,h.z),h=a.vertices[m.index2],b.push(h.x,h.y,h.z)}else if(a&&a.isBufferGeometry)if(h=new p,null!==a.index){k=a.attributes.position;q=a.index;var u=a.groups;0===u.length&&(u=[{start:0,
15812 count:q.count,materialIndex:0}]);a=0;for(e=u.length;a<e;++a)for(m=u[a],c=m.start,d=m.count,m=c,d=c+d;m<d;m+=3)for(c=0;3>c;c++)n=q.getX(m+c),t=q.getX(m+(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)m=g[n],h.fromBufferAttribute(k,m.index1),b.push(h.x,h.y,h.z),h.fromBufferAttribute(k,m.index2),b.push(h.x,h.y,h.z)}else for(k=a.attributes.position,m=0,d=k.count/3;m<d;m++)for(c=0;3>c;c++)g=3*m+c,h.fromBufferAttribute(k,g),b.push(h.x,
15813 h.y,h.z),g=3*m+(c+1)%3,h.fromBufferAttribute(k,g),b.push(h.x,h.y,h.z);this.addAttribute("position",new A(b,3))}function Fc(a,b,c){R.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Rb(a,b,c));this.mergeVertices()}function Rb(a,b,c){C.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f=[],g=[],h=new p,k=new p,m=new p,q=new p,n=new p,t,u;3>a.length&&console.error("THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.");
15814 var r=b+1;for(t=0;t<=c;t++){var l=t/c;for(u=0;u<=b;u++){var y=u/b;a(y,l,k);e.push(k.x,k.y,k.z);0<=y-1E-5?(a(y-1E-5,l,m),q.subVectors(k,m)):(a(y+1E-5,l,m),q.subVectors(m,k));0<=l-1E-5?(a(y,l-1E-5,m),n.subVectors(k,m)):(a(y,l+1E-5,m),n.subVectors(m,k));h.crossVectors(q,n).normalize();f.push(h.x,h.y,h.z);g.push(y,l)}}for(t=0;t<c;t++)for(u=0;u<b;u++)a=t*r+u+1,h=(t+1)*r+u+1,k=(t+1)*r+u,d.push(t*r+u,a,k),d.push(a,h,k);this.setIndex(d);this.addAttribute("position",new A(e,3));this.addAttribute("normal",
15815 new A(f,3));this.addAttribute("uv",new A(g,2))}function Gc(a,b,c,d){R.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};this.fromBufferGeometry(new na(a,b,c,d));this.mergeVertices()}function na(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)}C.call(this);this.type="PolyhedronBufferGeometry";this.parameters={vertices:a,
15816 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,m,l=c,x=d,w=g,B=Math.pow(2,a),E=[];for(m=0;m<=B;m++){E[m]=[];var P=l.clone().lerp(w,m/B),N=x.clone().lerp(w,m/B),O=B-m;for(k=0;k<=O;k++)E[m][k]=0===k&&m===B?P:P.clone().lerp(N,k/O)}for(m=0;m<B;m++)for(k=0;k<2*(B-m)-1;k++)l=Math.floor(k/2),0===k%2?(e(E[m][l+1]),e(E[m+1][l]),e(E[m][l])):(e(E[m][l+1]),e(E[m+1][l+1]),e(E[m+1][l]))}})(d);(function(a){for(var b=
15817 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));a=new p;b=new p;for(var c=new p,d=new p,e=new z,f=new z,l=new z,y=0,x=0;y<h.length;y+=9,x+=6){a.set(h[y+0],h[y+1],h[y+2]);b.set(h[y+3],h[y+4],h[y+5]);c.set(h[y+6],h[y+7],h[y+8]);e.set(k[x+0],
15818 k[x+1]);f.set(k[x+2],k[x+3]);l.set(k[x+4],k[x+5]);d.copy(a).add(b).add(c).divideScalar(3);var w=Math.atan2(d.z,-d.x);g(e,x+0,a,w);g(f,x+2,b,w);g(l,x+4,c,w)}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 A(h,3));this.addAttribute("normal",new A(h.slice(),3));this.addAttribute("uv",new A(k,2));0===d?this.computeVertexNormals():this.normalizeNormals()}function Hc(a,
15819 b){R.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Sb(a,b));this.mergeVertices()}function Sb(a,b){na.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 Ic(a,b){R.call(this);this.type="OctahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new pb(a,b));this.mergeVertices()}function pb(a,b){na.call(this,[1,0,0,
15820 -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 Jc(a,b){R.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Tb(a,b));this.mergeVertices()}function Tb(a,b){var c=(1+Math.sqrt(5))/2;na.call(this,[-1,c,0,1,c,0,-1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,
15821 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 Kc(a,b){R.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ub(a,b));this.mergeVertices()}function Ub(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;na.call(this,[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-d,-c,0,-d,c,0,d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,
15822 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 Lc(a,b,c,d,e,f){R.call(this);this.type="TubeGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,
15823 closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Vb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Vb(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 m=t/d*Math.PI*2,n=Math.sin(m);m=-Math.cos(m);k.x=m*f.x+n*e.x;k.y=m*f.y+n*e.y;k.z=m*f.z+n*e.z;k.normalize();r.push(k.x,k.y,k.z);h.x=q.x+c*k.x;h.y=q.y+c*k.y;h.z=
15824 q.z+c*k.z;l.push(h.x,h.y,h.z)}}C.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,m=new z,q=new p,n,t,l=[],r=[],v=[],y=[];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++)m.x=n/b,m.y=t/d,v.push(m.x,m.y);(function(){for(t=1;t<=b;t++)for(n=1;n<=d;n++){var a=
15825 (d+1)*t+(n-1),c=(d+1)*t+n,e=(d+1)*(t-1)+n;y.push((d+1)*(t-1)+(n-1),a,e);y.push(a,c,e)}})();this.setIndex(y);this.addAttribute("position",new A(l,3));this.addAttribute("normal",new A(r,3));this.addAttribute("uv",new A(v,2))}function Mc(a,b,c,d,e,f,g){R.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.");this.fromBufferGeometry(new Wb(a,
15826 b,c,d,e,f));this.mergeVertices()}function Wb(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}C.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=[],m=[],q=[],n,t=new p,l=new p,r=new p,v=new p,y=new p,x=new p,w=new p;for(n=0;n<=c;++n){var B=n/c*e*Math.PI*2;
15827 g(B,e,f,a,r);g(B+.01,e,f,a,v);x.subVectors(v,r);w.addVectors(v,r);y.crossVectors(x,w);w.crossVectors(y,x);y.normalize();w.normalize();for(B=0;B<=d;++B){var E=B/d*Math.PI*2,P=-b*Math.cos(E);E=b*Math.sin(E);t.x=r.x+(P*w.x+E*y.x);t.y=r.y+(P*w.y+E*y.y);t.z=r.z+(P*w.z+E*y.z);k.push(t.x,t.y,t.z);l.subVectors(t,r).normalize();m.push(l.x,l.y,l.z);q.push(n/c);q.push(B/d)}}for(B=1;B<=c;B++)for(n=1;n<=d;n++)a=(d+1)*B+(n-1),b=(d+1)*B+n,e=(d+1)*(B-1)+n,h.push((d+1)*(B-1)+(n-1),a,e),h.push(a,b,e);this.setIndex(h);
15828 this.addAttribute("position",new A(k,3));this.addAttribute("normal",new A(m,3));this.addAttribute("uv",new A(q,2))}function Nc(a,b,c,d,e){R.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Xb(a,b,c,d,e));this.mergeVertices()}function Xb(a,b,c,d,e){C.call(this);this.type="TorusBufferGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||1;b=b||.4;c=Math.floor(c)||8;d=Math.floor(d)||
15829 6;e=e||2*Math.PI;var f=[],g=[],h=[],k=[],m=new p,q=new p,n=new p,t,l;for(t=0;t<=c;t++)for(l=0;l<=d;l++){var r=l/d*e,v=t/c*Math.PI*2;q.x=(a+b*Math.cos(v))*Math.cos(r);q.y=(a+b*Math.cos(v))*Math.sin(r);q.z=b*Math.sin(v);g.push(q.x,q.y,q.z);m.x=a*Math.cos(r);m.y=a*Math.sin(r);n.subVectors(q,m).normalize();h.push(n.x,n.y,n.z);k.push(l/d);k.push(t/c)}for(t=1;t<=c;t++)for(l=1;l<=d;l++)a=(d+1)*(t-1)+l-1,b=(d+1)*(t-1)+l,e=(d+1)*t+l,f.push((d+1)*t+l-1,a,e),f.push(a,b,e);this.setIndex(f);this.addAttribute("position",
15830 new A(g,3));this.addAttribute("normal",new A(h,3));this.addAttribute("uv",new A(k,2))}function bf(a,b,c,d,e){for(var f,g=0,h=b,k=c-d;h<c;h+=d)g+=(a[k]-a[h])*(a[h+1]+a[k+1]),k=h;if(e===0<g)for(e=b;e<c;e+=d)f=cf(e,a[e],a[e+1],f);else for(e=c-d;e>=b;e-=d)f=cf(e,a[e],a[e+1],f);f&&qb(f,f.next)&&(Oc(f),f=f.next);return f}function Pc(a,b){if(!a)return a;b||(b=a);do{var c=!1;if(a.steiner||!qb(a,a.next)&&0!==ma(a.prev,a,a.next))a=a.next;else{Oc(a);a=b=a.prev;if(a===a.next)break;c=!0}}while(c||a!==b);return b}
15831 function Qc(a,b,c,d,e,f,g){if(a){if(!g&&f){var h=a,k=h;do null===k.z&&(k.z=ae(k.x,k.y,d,e,f)),k.prevZ=k.prev,k=k.nextZ=k.next;while(k!==h);k.prevZ.nextZ=null;k.prevZ=null;h=k;var m,q,n,t,l=1;do{k=h;var r=h=null;for(q=0;k;){q++;var v=k;for(m=n=0;m<l&&(n++,v=v.nextZ,v);m++);for(t=l;0<n||0<t&&v;)0!==n&&(0===t||!v||k.z<=v.z)?(m=k,k=k.nextZ,n--):(m=v,v=v.nextZ,t--),r?r.nextZ=m:h=m,m.prevZ=r,r=m;k=v}r.nextZ=null;l*=2}while(1<q)}for(h=a;a.prev!==a.next;){k=a.prev;v=a.next;if(f)a:{r=a;t=d;var p=e,x=f;q=r.prev;
15832 n=r;l=r.next;if(0<=ma(q,n,l))r=!1;else{var w=q.x>n.x?q.x>l.x?q.x:l.x:n.x>l.x?n.x:l.x,B=q.y>n.y?q.y>l.y?q.y:l.y:n.y>l.y?n.y:l.y;m=ae(q.x<n.x?q.x<l.x?q.x:l.x:n.x<l.x?n.x:l.x,q.y<n.y?q.y<l.y?q.y:l.y:n.y<l.y?n.y:l.y,t,p,x);t=ae(w,B,t,p,x);for(p=r.nextZ;p&&p.z<=t;){if(p!==r.prev&&p!==r.next&&ud(q.x,q.y,n.x,n.y,l.x,l.y,p.x,p.y)&&0<=ma(p.prev,p,p.next)){r=!1;break a}p=p.nextZ}for(p=r.prevZ;p&&p.z>=m;){if(p!==r.prev&&p!==r.next&&ud(q.x,q.y,n.x,n.y,l.x,l.y,p.x,p.y)&&0<=ma(p.prev,p,p.next)){r=!1;break a}p=
15833 p.prevZ}r=!0}}else a:if(r=a,q=r.prev,n=r,l=r.next,0<=ma(q,n,l))r=!1;else{for(m=r.next.next;m!==r.prev;){if(ud(q.x,q.y,n.x,n.y,l.x,l.y,m.x,m.y)&&0<=ma(m.prev,m,m.next)){r=!1;break a}m=m.next}r=!0}if(r)b.push(k.i/c),b.push(a.i/c),b.push(v.i/c),Oc(a),h=a=v.next;else if(a=v,a===h){if(!g)Qc(Pc(a),b,c,d,e,f,1);else if(1===g){g=b;h=c;k=a;do v=k.prev,r=k.next.next,!qb(v,r)&&df(v,k,k.next,r)&&Rc(v,r)&&Rc(r,v)&&(g.push(v.i/h),g.push(k.i/h),g.push(r.i/h),Oc(k),Oc(k.next),k=a=r),k=k.next;while(k!==a);a=k;Qc(a,
15834 b,c,d,e,f,2)}else if(2===g)a:{g=a;do{for(h=g.next.next;h!==g.prev;){if(k=g.i!==h.i){k=g;v=h;if(r=k.next.i!==v.i&&k.prev.i!==v.i){b:{r=k;do{if(r.i!==k.i&&r.next.i!==k.i&&r.i!==v.i&&r.next.i!==v.i&&df(r,r.next,k,v)){r=!0;break b}r=r.next}while(r!==k);r=!1}r=!r}if(r=r&&Rc(k,v)&&Rc(v,k)){r=k;q=!1;n=(k.x+v.x)/2;v=(k.y+v.y)/2;do r.y>v!==r.next.y>v&&r.next.y!==r.y&&n<(r.next.x-r.x)*(v-r.y)/(r.next.y-r.y)+r.x&&(q=!q),r=r.next;while(r!==k);r=q}k=r}if(k){a=ef(g,h);g=Pc(g,g.next);a=Pc(a,a.next);Qc(g,b,c,d,e,
15835 f);Qc(a,b,c,d,e,f);break a}h=h.next}g=g.next}while(g!==a)}break}}}}function Ng(a,b){return a.x-b.x}function Og(a,b){var c=b,d=a.x,e=a.y,f=-Infinity;do{if(e<=c.y&&e>=c.next.y&&c.next.y!==c.y){var g=c.x+(e-c.y)*(c.next.x-c.x)/(c.next.y-c.y);if(g<=d&&g>f){f=g;if(g===d){if(e===c.y)return c;if(e===c.next.y)return c.next}var h=c.x<c.next.x?c:c.next}}c=c.next}while(c!==b);if(!h)return null;if(d===f)return h.prev;b=h;g=h.x;var k=h.y,m=Infinity;for(c=h.next;c!==b;){if(d>=c.x&&c.x>=g&&d!==c.x&&ud(e<k?d:f,e,
15836 g,k,e<k?f:d,e,c.x,c.y)){var q=Math.abs(e-c.y)/(d-c.x);(q<m||q===m&&c.x>h.x)&&Rc(c,a)&&(h=c,m=q)}c=c.next}return h}function ae(a,b,c,d,e){a=32767*(a-c)*e;b=32767*(b-d)*e;a=(a|a<<8)&16711935;a=(a|a<<4)&252645135;a=(a|a<<2)&858993459;b=(b|b<<8)&16711935;b=(b|b<<4)&252645135;b=(b|b<<2)&858993459;return(a|a<<1)&1431655765|((b|b<<1)&1431655765)<<1}function Pg(a){var b=a,c=a;do b.x<c.x&&(c=b),b=b.next;while(b!==a);return c}function ud(a,b,c,d,e,f,g,h){return 0<=(e-g)*(b-h)-(a-g)*(f-h)&&0<=(a-g)*(d-h)-(c-
15837 g)*(b-h)&&0<=(c-g)*(f-h)-(e-g)*(d-h)}function ma(a,b,c){return(b.y-a.y)*(c.x-b.x)-(b.x-a.x)*(c.y-b.y)}function qb(a,b){return a.x===b.x&&a.y===b.y}function df(a,b,c,d){return qb(a,b)&&qb(c,d)||qb(a,d)&&qb(c,b)?!0:0<ma(a,b,c)!==0<ma(a,b,d)&&0<ma(c,d,a)!==0<ma(c,d,b)}function Rc(a,b){return 0>ma(a.prev,a,a.next)?0<=ma(a,b,a.next)&&0<=ma(a,a.prev,b):0>ma(a,b,a.prev)||0>ma(a,a.next,b)}function ef(a,b){var c=new be(a.i,a.x,a.y),d=new be(b.i,b.x,b.y),e=a.next,f=b.prev;a.next=b;b.prev=a;c.next=e;e.prev=
15838 c;d.next=c;c.prev=d;f.next=d;d.prev=f;return d}function cf(a,b,c,d){a=new be(a,b,c);d?(a.next=d.next,a.prev=d,d.next.prev=a,d.next=a):(a.prev=a,a.next=a);return a}function Oc(a){a.next.prev=a.prev;a.prev.next=a.next;a.prevZ&&(a.prevZ.nextZ=a.nextZ);a.nextZ&&(a.nextZ.prevZ=a.prevZ)}function be(a,b,c){this.i=a;this.x=b;this.y=c;this.nextZ=this.prevZ=this.z=this.next=this.prev=null;this.steiner=!1}function ff(a){var b=a.length;2<b&&a[b-1].equals(a[0])&&a.pop()}function gf(a,b){for(var c=0;c<b.length;c++)a.push(b[c].x),
15839 a.push(b[c].y)}function rb(a,b){R.call(this);this.type="ExtrudeGeometry";this.parameters={shapes:a,options:b};this.fromBufferGeometry(new Oa(a,b));this.mergeVertices()}function Oa(a,b){function c(a){function c(a,b,c){b||console.error("THREE.ExtrudeGeometry: vec does not exist");return b.clone().multiplyScalar(c).add(a)}function g(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),m=Math.sqrt(f*f+g*g);h=b.x-e/k;b=b.y+d/k;
15840 g=((c.x-g/m-h)*g-(c.y+f/m-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 z(f,d);e=Math.sqrt(e/2)}else a=!1,d>Number.EPSILON?f>Number.EPSILON&&(a=!0):d<-Number.EPSILON?f<-Number.EPSILON&&(a=!0):Math.sign(e)===Math.sign(g)&&(a=!0),a?(f=-e,e=Math.sqrt(h)):(f=d,d=e,e=Math.sqrt(h/2));return new z(f/e,d/e)}function h(a,b){for(M=a.length;0<=--M;){var c=M;var f=M-1;0>f&&(f=a.length-1);var g,h=w+2*O;for(g=0;g<h;g++){var k=Z*g,m=Z*(g+1),q=b+f+k,n=b+f+m;m=b+c+m;r(b+c+k);r(q);r(m);r(q);
15841 r(n);r(m);k=e.length/3;k=D.generateSideWallUV(d,e,k-6,k-3,k-2,k-1);v(k[0]);v(k[1]);v(k[3]);v(k[1]);v(k[2]);v(k[3])}}}function k(a,b,c){y.push(a);y.push(b);y.push(c)}function l(a,b,c){r(a);r(b);r(c);a=e.length/3;a=D.generateTopUV(d,e,a-3,a-2,a-1);v(a[0]);v(a[1]);v(a[2])}function r(a){e.push(y[3*a]);e.push(y[3*a+1]);e.push(y[3*a+2])}function v(a){f.push(a.x);f.push(a.y)}var y=[],x=void 0!==b.curveSegments?b.curveSegments:12,w=void 0!==b.steps?b.steps:1,B=void 0!==b.depth?b.depth:100,E=void 0!==b.bevelEnabled?
15842 b.bevelEnabled:!0,P=void 0!==b.bevelThickness?b.bevelThickness:6,N=void 0!==b.bevelSize?b.bevelSize:P-2,O=void 0!==b.bevelSegments?b.bevelSegments:3,A=b.extrudePath,D=void 0!==b.UVGenerator?b.UVGenerator:Qg;void 0!==b.amount&&(console.warn("THREE.ExtrudeBufferGeometry: amount has been renamed to depth."),B=b.amount);var C=!1;if(A){var G=A.getSpacedPoints(w);C=!0;E=!1;var K=A.computeFrenetFrames(w,!1);var L=new p;var R=new p;var Q=new p}E||(N=P=O=0);var I;x=a.extractPoints(x);a=x.shape;var J=x.holes;
15843 if(!Va.isClockWise(a)){a=a.reverse();var H=0;for(I=J.length;H<I;H++){var S=J[H];Va.isClockWise(S)&&(J[H]=S.reverse())}}var Y=Va.triangulateShape(a,J),W=a;H=0;for(I=J.length;H<I;H++)S=J[H],a=a.concat(S);var T,Z=a.length,V,ea=Y.length;x=[];var M=0;var U=W.length;var X=U-1;for(T=M+1;M<U;M++,X++,T++)X===U&&(X=0),T===U&&(T=0),x[M]=g(W[M],W[X],W[T]);A=[];var fa=x.concat();H=0;for(I=J.length;H<I;H++){S=J[H];var ca=[];M=0;U=S.length;X=U-1;for(T=M+1;M<U;M++,X++,T++)X===U&&(X=0),T===U&&(T=0),ca[M]=g(S[M],S[X],
15844 S[T]);A.push(ca);fa=fa.concat(ca)}for(X=0;X<O;X++){U=X/O;var da=P*Math.cos(U*Math.PI/2);T=N*Math.sin(U*Math.PI/2);M=0;for(U=W.length;M<U;M++){var aa=c(W[M],x[M],T);k(aa.x,aa.y,-da)}H=0;for(I=J.length;H<I;H++)for(S=J[H],ca=A[H],M=0,U=S.length;M<U;M++)aa=c(S[M],ca[M],T),k(aa.x,aa.y,-da)}T=N;for(M=0;M<Z;M++)aa=E?c(a[M],fa[M],T):a[M],C?(R.copy(K.normals[0]).multiplyScalar(aa.x),L.copy(K.binormals[0]).multiplyScalar(aa.y),Q.copy(G[0]).add(R).add(L),k(Q.x,Q.y,Q.z)):k(aa.x,aa.y,0);for(U=1;U<=w;U++)for(M=
15845 0;M<Z;M++)aa=E?c(a[M],fa[M],T):a[M],C?(R.copy(K.normals[U]).multiplyScalar(aa.x),L.copy(K.binormals[U]).multiplyScalar(aa.y),Q.copy(G[U]).add(R).add(L),k(Q.x,Q.y,Q.z)):k(aa.x,aa.y,B/w*U);for(X=O-1;0<=X;X--){U=X/O;da=P*Math.cos(U*Math.PI/2);T=N*Math.sin(U*Math.PI/2);M=0;for(U=W.length;M<U;M++)aa=c(W[M],x[M],T),k(aa.x,aa.y,B+da);H=0;for(I=J.length;H<I;H++)for(S=J[H],ca=A[H],M=0,U=S.length;M<U;M++)aa=c(S[M],ca[M],T),C?k(aa.x,aa.y+G[w-1].y,G[w-1].x+da):k(aa.x,aa.y,B+da)}(function(){var a=e.length/3;if(E){var b=
15846 0*Z;for(M=0;M<ea;M++)V=Y[M],l(V[2]+b,V[1]+b,V[0]+b);b=Z*(w+2*O);for(M=0;M<ea;M++)V=Y[M],l(V[0]+b,V[1]+b,V[2]+b)}else{for(M=0;M<ea;M++)V=Y[M],l(V[2],V[1],V[0]);for(M=0;M<ea;M++)V=Y[M],l(V[0]+Z*w,V[1]+Z*w,V[2]+Z*w)}d.addGroup(a,e.length/3-a,0)})();(function(){var a=e.length/3,b=0;h(W,b);b+=W.length;H=0;for(I=J.length;H<I;H++)S=J[H],h(S,b),b+=S.length;d.addGroup(a,e.length/3-a,1)})()}C.call(this);this.type="ExtrudeBufferGeometry";this.parameters={shapes:a,options:b};a=Array.isArray(a)?a:[a];for(var d=
15847 this,e=[],f=[],g=0,h=a.length;g<h;g++)c(a[g]);this.addAttribute("position",new A(e,3));this.addAttribute("uv",new A(f,2));this.computeVertexNormals()}function hf(a,b,c){c.shapes=[];if(Array.isArray(a))for(var d=0,e=a.length;d<e;d++)c.shapes.push(a[d].uuid);else c.shapes.push(a.uuid);void 0!==b.extrudePath&&(c.options.extrudePath=b.extrudePath.toJSON());return c}function Sc(a,b){R.call(this);this.type="TextGeometry";this.parameters={text:a,parameters:b};this.fromBufferGeometry(new Yb(a,b));this.mergeVertices()}
15848 function Yb(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 R;a=c.generateShapes(a,b.size);b.depth=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);Oa.call(this,a,b);this.type="TextBufferGeometry"}function Tc(a,b,c,d,e,f,g){R.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,
15849 heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new sb(a,b,c,d,e,f,g));this.mergeVertices()}function sb(a,b,c,d,e,f,g){C.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!==d?d:0;e=void 0!==e?e:2*Math.PI;f=void 0!==f?f:0;g=void 0!==g?g:Math.PI;var h=f+g,k,m,q=0,n=[],l=new p,
15850 u=new p,r=[],v=[],y=[],x=[];for(m=0;m<=c;m++){var w=[],B=m/c;for(k=0;k<=b;k++){var E=k/b;l.x=-a*Math.cos(d+E*e)*Math.sin(f+B*g);l.y=a*Math.cos(f+B*g);l.z=a*Math.sin(d+E*e)*Math.sin(f+B*g);v.push(l.x,l.y,l.z);u.set(l.x,l.y,l.z).normalize();y.push(u.x,u.y,u.z);x.push(E,1-B);w.push(q++)}n.push(w)}for(m=0;m<c;m++)for(k=0;k<b;k++)a=n[m][k+1],d=n[m][k],e=n[m+1][k],g=n[m+1][k+1],(0!==m||0<f)&&r.push(a,d,g),(m!==c-1||h<Math.PI)&&r.push(d,e,g);this.setIndex(r);this.addAttribute("position",new A(v,3));this.addAttribute("normal",
15851 new A(y,3));this.addAttribute("uv",new A(x,2))}function Uc(a,b,c,d,e,f){R.call(this);this.type="RingGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new Zb(a,b,c,d,e,f));this.mergeVertices()}function Zb(a,b,c,d,e,f){C.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:a,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;
15852 c=void 0!==c?Math.max(3,c):8;d=void 0!==d?Math.max(1,d):1;var g=[],h=[],k=[],m=[],q=a,n=(b-a)/d,l=new p,u=new z,r,v;for(r=0;r<=d;r++){for(v=0;v<=c;v++)a=e+v/c*f,l.x=q*Math.cos(a),l.y=q*Math.sin(a),h.push(l.x,l.y,l.z),k.push(0,0,1),u.x=(l.x/b+1)/2,u.y=(l.y/b+1)/2,m.push(u.x,u.y);q+=n}for(r=0;r<d;r++)for(b=r*(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,f,q);this.setIndex(g);this.addAttribute("position",new A(h,3));this.addAttribute("normal",new A(k,3));this.addAttribute("uv",
15853 new A(m,2))}function Vc(a,b,c,d){R.call(this);this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new $b(a,b,c,d));this.mergeVertices()}function $b(a,b,c,d){C.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=H.clamp(d,0,2*Math.PI);var e=[],f=[],g=[],h=1/b,k=new p,m=new z,q;for(q=0;q<=b;q++){var n=c+q*h*d;var l=Math.sin(n),u=Math.cos(n);for(n=
15854 0;n<=a.length-1;n++)k.x=a[n].x*l,k.y=a[n].y,k.z=a[n].x*u,f.push(k.x,k.y,k.z),m.x=q/b,m.y=n/(a.length-1),g.push(m.x,m.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,m=c+1,e.push(c,h,m),e.push(h,k,m);this.setIndex(e);this.addAttribute("position",new A(f,3));this.addAttribute("uv",new A(g,2));this.computeVertexNormals();if(d===2*Math.PI)for(d=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=
15855 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 tb(a,b){R.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 ub(a,b));this.mergeVertices()}function ub(a,b){function c(a){var c,h=e.length/3;a=a.extractPoints(b);var m=a.shape,q=a.holes;
15856 if(!1===Va.isClockWise(m))for(m=m.reverse(),a=0,c=q.length;a<c;a++){var l=q[a];!0===Va.isClockWise(l)&&(q[a]=l.reverse())}var p=Va.triangulateShape(m,q);a=0;for(c=q.length;a<c;a++)l=q[a],m=m.concat(l);a=0;for(c=m.length;a<c;a++)l=m[a],e.push(l.x,l.y,0),f.push(0,0,1),g.push(l.x,l.y);a=0;for(c=p.length;a<c;a++)m=p[a],d.push(m[0]+h,m[1]+h,m[2]+h),k+=3}C.call(this);this.type="ShapeBufferGeometry";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);
15857 else for(var m=0;m<a.length;m++)c(a[m]),this.addGroup(h,k,m),h+=k,k=0;this.setIndex(d);this.addAttribute("position",new A(e,3));this.addAttribute("normal",new A(f,3));this.addAttribute("uv",new A(g,2))}function jf(a,b){b.shapes=[];if(Array.isArray(a))for(var c=0,d=a.length;c<d;c++)b.shapes.push(a[c].uuid);else b.shapes.push(a.uuid);return b}function ac(a,b){C.call(this);this.type="EdgesGeometry";this.parameters={thresholdAngle:b};var c=[];b=Math.cos(H.DEG2RAD*(void 0!==b?b:1));var d=[0,0],e={},f=
15858 ["a","b","c"];if(a.isBufferGeometry){var g=new R;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 m=g[h],q=0;3>q;q++){var n=m[f[q]];var l=m[f[(q+1)%3]];d[0]=Math.min(n,l);d[1]=Math.max(n,l);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],
15859 c.push(f.x,f.y,f.z);this.addAttribute("position",new A(c,3))}function vb(a,b,c,d,e,f,g,h){R.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 Wa(a,b,c,d,e,f,g,h));this.mergeVertices()}function Wa(a,b,c,d,e,f,g,h){function k(c){var e,f=new z,k=new p,t=0,v=!0===c?a:b,w=!0===c?1:-1;var A=r;for(e=1;e<=d;e++)n.push(0,y*w,0),l.push(0,w,0),u.push(.5,.5),r++;var C=
15860 r;for(e=0;e<=d;e++){var D=e/d*h+g,H=Math.cos(D);D=Math.sin(D);k.x=v*D;k.y=y*w;k.z=v*H;n.push(k.x,k.y,k.z);l.push(0,w,0);f.x=.5*H+.5;f.y=.5*D*w+.5;u.push(f.x,f.y);r++}for(e=0;e<d;e++)f=A+e,k=C+e,!0===c?q.push(k,k+1,f):q.push(k+1,k,f),t+=3;m.addGroup(x,t,!0===c?1:2);x+=t}C.call(this);this.type="CylinderBufferGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var m=this;a=void 0!==a?a:1;b=void 0!==b?b:1;c=c||1;d=Math.floor(d)||
15861 8;e=Math.floor(e)||1;f=void 0!==f?f:!1;g=void 0!==g?g:0;h=void 0!==h?h:2*Math.PI;var q=[],n=[],l=[],u=[],r=0,v=[],y=c/2,x=0;(function(){var f,k,t=new p,P=new p,N=0,z=(b-a)/c;for(k=0;k<=e;k++){var A=[],D=k/e,C=D*(b-a)+a;for(f=0;f<=d;f++){var H=f/d,G=H*h+g,K=Math.sin(G);G=Math.cos(G);P.x=C*K;P.y=-D*c+y;P.z=C*G;n.push(P.x,P.y,P.z);t.set(K,z,G).normalize();l.push(t.x,t.y,t.z);u.push(H,1-D);A.push(r++)}v.push(A)}for(f=0;f<d;f++)for(k=0;k<e;k++)t=v[k+1][f],P=v[k+1][f+1],z=v[k][f+1],q.push(v[k][f],t,z),
15862 q.push(t,P,z),N+=6;m.addGroup(x,N,0);x+=N})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(q);this.addAttribute("position",new A(n,3));this.addAttribute("normal",new A(l,3));this.addAttribute("uv",new A(u,2))}function Wc(a,b,c,d,e,f,g){vb.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 Xc(a,b,c,d,e,f,g){Wa.call(this,0,a,b,c,d,e,f,g);this.type="ConeBufferGeometry";this.parameters=
15863 {radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Yc(a,b,c,d){R.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new bc(a,b,c,d));this.mergeVertices()}function bc(a,b,c,d){C.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=
15864 [],g=[],h=[],k,m=new p,q=new z;f.push(0,0,0);g.push(0,0,1);h.push(.5,.5);var n=0;for(k=3;n<=b;n++,k+=3){var l=c+n/b*d;m.x=a*Math.cos(l);m.y=a*Math.sin(l);f.push(m.x,m.y,m.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 A(f,3));this.addAttribute("normal",new A(g,3));this.addAttribute("uv",new A(h,2))}function wb(a){J.call(this);this.type="ShadowMaterial";this.color=new G(0);this.transparent=!0;this.setValues(a)}
15865 function cc(a){ta.call(this,a);this.type="RawShaderMaterial"}function Pa(a){J.call(this);this.defines={STANDARD:""};this.type="MeshStandardMaterial";this.color=new G(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new G(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=0;this.normalScale=new z(1,1);this.displacementMap=null;this.displacementScale=
15866 1;this.displacementBias=0;this.envMap=this.alphaMap=this.metalnessMap=this.roughnessMap=null;this.envMapIntensity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function xb(a){Pa.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function Fa(a){J.call(this);
15867 this.type="MeshPhongMaterial";this.color=new G(16777215);this.specular=new G(1118481);this.shininess=30;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new G(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=0;this.normalScale=new z(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;
15868 this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function yb(a){Fa.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;this.setValues(a)}function zb(a){J.call(this);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=0;this.normalScale=new z(1,1);this.displacementMap=
15869 null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.lights=this.fog=!1;this.setValues(a)}function Ab(a){J.call(this);this.type="MeshLambertMaterial";this.color=new G(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new G(0);this.emissiveIntensity=1;this.envMap=this.alphaMap=this.specularMap=this.emissiveMap=null;this.combine=0;this.reflectivity=
15870 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 Bb(a){Y.call(this);this.type="LineDashedMaterial";this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(a)}function ce(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,
15871 f,g);e=!0};this.itemEnd=function(a){f++;if(void 0!==d.onProgress)d.onProgress(a,f,g);if(f===g&&(e=!1,void 0!==d.onLoad))d.onLoad()};this.itemError=function(a){if(void 0!==d.onError)d.onError(a)};this.resolveURL=function(a){return h?h(a):a};this.setURLModifier=function(a){h=a;return this}}function Ga(a){this.manager=void 0!==a?a:ka}function kf(a){this.manager=void 0!==a?a:ka;this._parser=null}function de(a){this.manager=void 0!==a?a:ka;this._parser=null}function Zc(a){this.manager=void 0!==a?a:ka}
15872 function ee(a){this.manager=void 0!==a?a:ka}function vd(a){this.manager=void 0!==a?a:ka}function L(){this.type="Curve";this.arcLengthDivisions=200}function za(a,b,c,d,e,f,g,h){L.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 dc(a,b,c,d,e,f){za.call(this,a,b,c,c,d,e,f);this.type="ArcCurve"}function fe(){var a=0,b=0,c=0,d=0;return{initCatmullRom:function(e,
15873 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,m,q){e=((f-e)/k-(g-e)/(k+m)+(g-f)/m)*m;h=((g-f)/m-(h-f)/(m+q)+(h-g)/q)*m;a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},calc:function(e){var f=e*e;return a+b*e+c*f+d*f*e}}}function ca(a,b,c,d){L.call(this);this.type="CatmullRomCurve3";this.points=a||[];this.closed=b||!1;this.curveType=c||"centripetal";this.tension=d||.5}function lf(a,b,c,d,e){b=.5*(d-b);e=.5*(e-c);var f=a*a;return(2*c-2*d+b+e)*
15874 a*f+(-3*c+3*d-2*b-e)*f+b*a+c}function $c(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}function ad(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 Ha(a,b,c,d){L.call(this);this.type="CubicBezierCurve";this.v0=a||new z;this.v1=b||new z;this.v2=c||new z;this.v3=d||new z}function Qa(a,b,c,d){L.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 va(a,b){L.call(this);this.type="LineCurve";this.v1=a||
15875 new z;this.v2=b||new z}function Ia(a,b){L.call(this);this.type="LineCurve3";this.v1=a||new p;this.v2=b||new p}function Ja(a,b,c){L.call(this);this.type="QuadraticBezierCurve";this.v0=a||new z;this.v1=b||new z;this.v2=c||new z}function Ra(a,b,c){L.call(this);this.type="QuadraticBezierCurve3";this.v0=a||new p;this.v1=b||new p;this.v2=c||new p}function Ka(a){L.call(this);this.type="SplineCurve";this.points=a||[]}function Xa(){L.call(this);this.type="CurvePath";this.curves=[];this.autoClose=!1}function La(a){Xa.call(this);
15876 this.type="Path";this.currentPoint=new z;a&&this.setFromPoints(a)}function db(a){La.call(this,a);this.uuid=H.generateUUID();this.type="Shape";this.holes=[]}function X(a,b){D.call(this);this.type="Light";this.color=new G(a);this.intensity=void 0!==b?b:1;this.receiveShadow=void 0}function wd(a,b,c){X.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(D.DefaultUp);this.updateMatrix();this.groundColor=new G(b)}function Cb(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=
15877 new z(512,512);this.map=null;this.matrix=new I}function xd(){Cb.call(this,new Z(50,1,.5,500))}function yd(a,b,c,d,e,f){X.call(this,a,b);this.type="SpotLight";this.position.copy(D.DefaultUp);this.updateMatrix();this.target=new D;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 xd}function zd(a,
15878 b,c,d){X.call(this,a,b);this.type="PointLight";Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(a){this.intensity=a/(4*Math.PI)}});this.distance=void 0!==c?c:0;this.decay=void 0!==d?d:1;this.shadow=new Cb(new Z(90,1,.5,500))}function Ad(){Cb.call(this,new Hb(-5,5,5,-5,.5,500))}function Bd(a,b){X.call(this,a,b);this.type="DirectionalLight";this.position.copy(D.DefaultUp);this.updateMatrix();this.target=new D;this.shadow=new Ad}function Cd(a,b){X.call(this,
15879 a,b);this.type="AmbientLight";this.castShadow=void 0}function Dd(a,b,c,d){X.call(this,a,b);this.type="RectAreaLight";this.width=void 0!==c?c:10;this.height=void 0!==d?d:10}function wa(a,b,c,d){this.parameterPositions=a;this._cachedIndex=0;this.resultBuffer=void 0!==d?d:new b.constructor(c);this.sampleValues=b;this.valueSize=c}function Ed(a,b,c,d){wa.call(this,a,b,c,d);this._offsetNext=this._weightNext=this._offsetPrev=this._weightPrev=-0}function bd(a,b,c,d){wa.call(this,a,b,c,d)}function Fd(a,b,
15880 c,d){wa.call(this,a,b,c,d)}function oa(a,b,c,d){if(void 0===a)throw Error("THREE.KeyframeTrack: track name is undefined");if(void 0===b||0===b.length)throw Error("THREE.KeyframeTrack: no keyframes in track named "+a);this.name=a;this.times=ia.convertArray(b,this.TimeBufferType);this.values=ia.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation)}function Gd(a,b,c){oa.call(this,a,b,c)}function Hd(a,b,c,d){oa.call(this,a,b,c,d)}function ec(a,b,c,d){oa.call(this,a,
15881 b,c,d)}function Id(a,b,c,d){wa.call(this,a,b,c,d)}function cd(a,b,c,d){oa.call(this,a,b,c,d)}function Jd(a,b,c,d){oa.call(this,a,b,c,d)}function fc(a,b,c,d){oa.call(this,a,b,c,d)}function Ca(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=H.generateUUID();0>this.duration&&this.resetDuration()}function Rg(a){switch(a.toLowerCase()){case "scalar":case "double":case "float":case "number":case "integer":return ec;case "vector":case "vector2":case "vector3":case "vector4":return fc;
15882 case "color":return Hd;case "quaternion":return cd;case "bool":case "boolean":return Gd;case "string":return Jd}throw Error("THREE.KeyframeTrack: Unsupported typeName: "+a);}function Sg(a){if(void 0===a.type)throw Error("THREE.KeyframeTrack: track type undefined, can not parse");var b=Rg(a.type);if(void 0===a.times){var c=[],d=[];ia.flattenJSON(a.keys,c,d,"value");a.times=c;a.values=d}return void 0!==b.parse?b.parse(a):new b(a.name,a.times,a.values,a.interpolation)}function Kd(a){this.manager=void 0!==
15883 a?a:ka;this.textures={}}function ge(a){this.manager=void 0!==a?a:ka}function gc(){}function he(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:ka;this.withCredentials=!1}function mf(a){this.manager=void 0!==a?a:ka;this.texturePath=""}function ie(a){"undefined"===typeof createImageBitmap&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported.");"undefined"===typeof fetch&&console.warn("THREE.ImageBitmapLoader: fetch() not supported.");
15884 this.manager=void 0!==a?a:ka;this.options=void 0}function je(){this.type="ShapePath";this.color=new G;this.subPaths=[];this.currentPath=null}function ke(a){this.type="Font";this.data=a}function nf(a){this.manager=void 0!==a?a:ka}function le(a){this.manager=void 0!==a?a:ka}function of(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new Z;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new Z;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=
15885 !1}function dd(a,b,c){D.call(this);this.type="CubeCamera";var d=new Z(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new p(1,0,0));this.add(d);var e=new Z(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new p(-1,0,0));this.add(e);var f=new Z(90,1,a,b);f.up.set(0,0,1);f.lookAt(new p(0,1,0));this.add(f);var g=new Z(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new p(0,-1,0));this.add(g);var h=new Z(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new p(0,0,1));this.add(h);var k=new Z(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new p(0,0,-1));this.add(k);
15886 this.renderTarget=new Gb(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,m=c.texture.generateMipmaps;c.texture.generateMipmaps=!1;c.activeCubeFace=0;a.render(b,d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=m;c.activeCubeFace=5;a.render(b,
15887 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 me(){D.call(this);this.type="AudioListener";this.context=ne.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function hc(a){D.call(this);this.type="Audio";this.context=a.context;this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=
15888 !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 oe(a){hc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}function pe(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 qe(a,b,c){this.binding=a;this.valueSize=
15889 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 pf(a,b,c){c=c||pa.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)}function pa(a,b,c){this.path=b;this.parsedPath=c||pa.parseTrackName(b);this.node=pa.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function qf(){this.uuid=
15890 H.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var a={};this._indicesByUUID=a;for(var b=0,c=arguments.length;b!==c;++b)a[arguments[b].uuid]=b;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var d=this;this.stats={objects:{get total(){return d._objects.length},get inUse(){return this.total-d.nCachedObjects_}},get bindingsPerObject(){return d._bindings.length}}}function rf(a,b,c){this._mixer=a;this._clip=b;this._localRoot=
15891 c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=this._byClipCacheIndex=this._cacheIndex=null;this.loop=2201;this._loopCount=-1;this._startTime=null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=this.timeScale=1;this.repetitions=Infinity;
15892 this.paused=!1;this.enabled=!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function re(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Ld(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function se(){C.call(this);this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function te(a,b,c){ob.call(this,a,b);this.meshPerAttribute=c||1}function ue(a,b,c){Q.call(this,
15893 a,b);this.meshPerAttribute=c||1}function sf(a,b,c,d){this.ray=new mb(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 tf(a,b){return a.distance-b.distance}function ve(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=a.length;d<e;d++)ve(a[d],
15894 b,c,!0)}}function uf(a){this.autoStart=void 0!==a?a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function vf(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 wf(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 we(a,b){this.min=void 0!==a?a:new z(Infinity,Infinity);this.max=void 0!==b?b:new z(-Infinity,-Infinity)}function xe(a,b){this.start=void 0!==a?a:new p;this.end=
15895 void 0!==b?b:new p}function ed(a){D.call(this);this.material=a;this.render=function(){}}function fd(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16711680;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=3*c.faces.length:c&&c.isBufferGeometry&&(b=c.attributes.normal.count);c=new C;b=new A(6*b,3);c.addAttribute("position",b);W.call(this,c,new Y({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function ic(a,b){D.call(this);this.light=a;this.light.updateMatrixWorld();
15896 this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=b;a=new C;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,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 A(b,3));b=new Y({fog:!1});this.cone=new W(a,b);this.add(this.cone);this.update()}function xf(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;c<a.children.length;c++)b.push.apply(b,xf(a.children[c]));return b}
15897 function jc(a){for(var b=xf(a),c=new C,d=[],e=[],f=new G(0,0,1),g=new G(0,1,0),h=0;h<b.length;h++){var k=b[h];k.parent&&k.parent.isBone&&(d.push(0,0,0),d.push(0,0,0),e.push(f.r,f.g,f.b),e.push(g.r,g.g,g.b))}c.addAttribute("position",new A(d,3));c.addAttribute("color",new A(e,3));d=new Y({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});W.call(this,c,d);this.root=a;this.bones=b;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1}function kc(a,b,c){this.light=a;this.light.updateMatrixWorld();
15898 this.color=c;a=new sb(b,4,2);b=new da({wireframe:!0,fog:!1});la.call(this,a,b);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1;this.update()}function lc(a,b){D.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=b;a=new Y({fog:!1});b=new C;b.addAttribute("position",new Q(new Float32Array(15),3));this.line=new sa(b,a);this.add(this.line);this.update()}function mc(a,b,c){D.call(this);this.light=a;this.light.updateMatrixWorld();
15899 this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=c;a=new pb(b);a.rotateY(.5*Math.PI);this.material=new da({wireframe:!0,fog:!1});void 0===this.color&&(this.material.vertexColors=2);b=a.getAttribute("position");b=new Float32Array(3*b.count);a.addAttribute("color",new Q(b,3));this.add(new la(a,this.material));this.update()}function gd(a,b,c,d){a=a||10;b=b||10;c=new G(void 0!==c?c:4473924);d=new G(void 0!==d?d:8947848);var e=b/2,f=a/b,g=a/2;a=[];for(var h=[],k=0,m=0,q=-g;k<=b;k++,q+=f){a.push(-g,
15900 0,q,g,0,q);a.push(q,0,-g,q,0,g);var n=k===e?c:d;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3;n.toArray(h,m);m+=3}b=new C;b.addAttribute("position",new A(a,3));b.addAttribute("color",new A(h,3));c=new Y({vertexColors:2});W.call(this,b,c)}function Md(a,b,c,d,e,f){a=a||10;b=b||16;c=c||8;d=d||64;e=new G(void 0!==e?e:4473924);f=new G(void 0!==f?f:8947848);var g=[],h=[],k;for(k=0;k<=b;k++){var m=k/b*2*Math.PI;var q=Math.sin(m)*a;m=Math.cos(m)*a;g.push(0,0,0);g.push(q,0,m);var n=k&1?e:f;h.push(n.r,
15901 n.g,n.b);h.push(n.r,n.g,n.b)}for(k=0;k<=c;k++){n=k&1?e:f;var l=a-a/c*k;for(b=0;b<d;b++)m=b/d*2*Math.PI,q=Math.sin(m)*l,m=Math.cos(m)*l,g.push(q,0,m),h.push(n.r,n.g,n.b),m=(b+1)/d*2*Math.PI,q=Math.sin(m)*l,m=Math.cos(m)*l,g.push(q,0,m),h.push(n.r,n.g,n.b)}a=new C;a.addAttribute("position",new A(g,3));a.addAttribute("color",new A(h,3));g=new Y({vertexColors:2});W.call(this,a,g)}function hd(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)&&
15902 c.isGeometry?b=c.faces.length:console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.");c=new C;b=new A(6*b,3);c.addAttribute("position",b);W.call(this,c,new Y({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function nc(a,b,c){D.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 C;a.addAttribute("position",new A([-b,b,0,b,b,0,b,-b,0,-b,
15903 -b,0,-b,b,0],3));b=new Y({fog:!1});this.lightPlane=new sa(a,b);this.add(this.lightPlane);a=new C;a.addAttribute("position",new A([0,0,0,0,0,1],3));this.targetLine=new sa(a,b);this.add(this.targetLine);this.update()}function id(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 C,e=new Y({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new G(16755200),m=new G(16711680),q=new G(43775),n=new G(16777215),l=new G(3355443);
15904 b("n1","n2",k);b("n2","n4",k);b("n4","n3",k);b("n3","n1",k);b("f1","f2",k);b("f2","f4",k);b("f4","f3",k);b("f3","f1",k);b("n1","f1",k);b("n2","f2",k);b("n3","f3",k);b("n4","f4",k);b("p","n1",m);b("p","n2",m);b("p","n3",m);b("p","n4",m);b("u1","u2",q);b("u2","u3",q);b("u3","u1",q);b("c","t",n);b("p","c",l);b("cn1","cn2",l);b("cn3","cn4",l);b("cf1","cf2",l);b("cf3","cf4",l);d.addAttribute("position",new A(f,3));d.addAttribute("color",new A(g,3));W.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&
15905 this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=h;this.update()}function Db(a,b){this.object=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 C;d.setIndex(new Q(a,1));d.addAttribute("position",new Q(c,3));W.call(this,d,new Y({color:b}));this.matrixAutoUpdate=!1;this.update()}function jd(a,b){this.type="Box3Helper";this.box=a;a=void 0!==b?b:16776960;b=new Uint16Array([0,
15906 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 C;c.setIndex(new Q(b,1));c.addAttribute("position",new A([1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3));W.call(this,c,new Y({color:a}));this.geometry.computeBoundingSphere()}function kd(a,b,c){this.type="PlaneHelper";this.plane=a;this.size=void 0===b?1:b;a=void 0!==c?c:16776960;b=new C;b.addAttribute("position",new A([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();sa.call(this,
15907 b,new Y({color:a}));b=new C;b.addAttribute("position",new A([1,1,1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,1],3));b.computeBoundingSphere();this.add(new la(b,new da({color:a,opacity:.2,transparent:!0,depthWrite:!1})))}function Eb(a,b,c,d,e,f){D.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===Nd&&(Nd=new C,Nd.addAttribute("position",new A([0,0,0,0,1,0],3)),ye=new Wa(0,.5,1,5,1),ye.translate(0,-.5,0));this.position.copy(b);this.line=new sa(Nd,new Y({color:d}));
15908 this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new la(ye,new da({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(a);this.setLength(c,e,f)}function ld(a){a=a||1;var b=[0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a];a=new C;a.addAttribute("position",new A(b,3));a.addAttribute("color",new A([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new Y({vertexColors:2});W.call(this,a,b)}function yf(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");
15909 ca.call(this,a);this.type="catmullrom";this.closed=!0}function zf(a){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");ca.call(this,a);this.type="catmullrom"}function ze(a){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");ca.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)===
15910 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===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,
15911 e)&&(b[e]=d[e])}return b}}();Object.assign(ya.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;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!==
15912 this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;b=b.slice(0);for(var c=0,d=b.length;c<d;c++)b[c].call(this,a)}}}});var H={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,generateUUID:function(){for(var a=[],b=0;256>b;b++)a[b]=(16>b?"0":"")+b.toString(16);return function(){var b=4294967295*Math.random()|0,d=4294967295*Math.random()|0,e=4294967295*Math.random()|0,f=4294967295*Math.random()|0;return(a[b&255]+a[b>>8&255]+a[b>>16&255]+a[b>>24&255]+"-"+a[d&255]+a[d>>8&255]+"-"+a[d>>
15913 16&15|64]+a[d>>24&255]+"-"+a[e&63|128]+a[e>>8&255]+"-"+a[e>>16&255]+a[e>>24&255]+a[f&255]+a[f>>8&255]+a[f>>16&255]+a[f>>24&255]).toUpperCase()}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;
15914 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*H.DEG2RAD},radToDeg:function(a){return a*H.RAD2DEG},isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},ceilPowerOfTwo:function(a){return Math.pow(2,Math.ceil(Math.log(a)/Math.LN2))},floorPowerOfTwo:function(a){return Math.pow(2,Math.floor(Math.log(a)/
15915 Math.LN2))}};Object.defineProperties(z.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(z.prototype,{isVector2:!0,set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+
15916 a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},
15917 addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=
15918 a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},applyMatrix3:function(a){var b=this.x,c=this.y;a=a.elements;this.x=a[0]*b+a[3]*c+a[6];this.y=a[1]*b+a[4]*c+a[7];return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);return this},clamp:function(a,
15919 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 z,b=new z;return function(c,d){a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this},round:function(){this.x=
15920 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},cross:function(a){return this.x*a.y-this.y*a.x},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)+
15921 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+=
15922 (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);
15923 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(I.prototype,{isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,m,q,n,l,u,r,p){var t=this.elements;t[0]=a;t[4]=b;t[8]=c;t[12]=d;t[1]=e;t[5]=f;t[9]=g;t[13]=h;t[2]=k;t[6]=m;t[10]=q;t[14]=n;t[3]=l;t[7]=u;t[11]=r;t[15]=p;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 I).fromArray(this.elements)},
15924 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,
15925 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[3]=0;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[7]=0;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;c[11]=0;c[12]=0;c[13]=0;c[14]=0;c[15]=1;return this}}(),makeRotationFromEuler:function(a){a&&a.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");
15926 var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c);c=Math.sin(c);var g=Math.cos(d);d=Math.sin(d);var h=Math.cos(e);e=Math.sin(e);if("XYZ"===a.order){a=f*h;var k=f*e,m=c*h,q=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=k+m*d;b[5]=a-q*d;b[9]=-c*g;b[2]=q-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"===a.order?(a=g*h,k=g*e,m=d*h,q=d*e,b[0]=a+q*c,b[4]=m*c-k,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=k*c-m,b[6]=q+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,k=g*e,m=d*h,q=d*e,b[0]=a-q*c,b[4]=-f*e,b[8]=m+k*c,b[1]=k+m*c,b[5]=f*h,b[9]=
15927 q-a*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(a=f*h,k=f*e,m=c*h,q=c*e,b[0]=g*h,b[4]=m*d-k,b[8]=a*d+q,b[1]=g*e,b[5]=q*d+a,b[9]=k*d-m,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(a=f*g,k=f*d,m=c*g,q=c*d,b[0]=g*h,b[4]=q-a*e,b[8]=m*e+k,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=k*e+m,b[10]=a-q*e):"XZY"===a.order&&(a=f*g,k=f*d,m=c*g,q=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+q,b[5]=f*h,b[9]=k*e-m,b[2]=m*e-k,b[6]=c*h,b[10]=q*e+a);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(){var a=
15928 new p(0,0,0),b=new p(1,1,1);return function(c){return this.compose(a,c,b)}}(),lookAt:function(){var a=new p,b=new p,c=new p;return function(d,e,f){var g=this.elements;c.subVectors(d,e);0===c.lengthSq()&&(c.z=1);c.normalize();a.crossVectors(f,c);0===a.lengthSq()&&(1===Math.abs(f.z)?c.x+=1E-4:c.z+=1E-4,c.normalize(),a.crossVectors(f,c));a.normalize();b.crossVectors(c,a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==
15929 b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements;b=this.elements;a=c[0];var e=c[4],f=c[8],g=c[12],h=c[1],k=c[5],m=c[9],q=c[13],n=c[2],l=c[6],u=c[10],r=c[14],p=c[3],y=c[7],x=c[11];c=c[15];var w=d[0],B=d[4],E=d[8],P=d[12],N=d[1],z=d[5],A=d[9],D=d[13],C=d[2],
15930 H=d[6],G=d[10],K=d[14],L=d[3],I=d[7],J=d[11];d=d[15];b[0]=a*w+e*N+f*C+g*L;b[4]=a*B+e*z+f*H+g*I;b[8]=a*E+e*A+f*G+g*J;b[12]=a*P+e*D+f*K+g*d;b[1]=h*w+k*N+m*C+q*L;b[5]=h*B+k*z+m*H+q*I;b[9]=h*E+k*A+m*G+q*J;b[13]=h*P+k*D+m*K+q*d;b[2]=n*w+l*N+u*C+r*L;b[6]=n*B+l*z+u*H+r*I;b[10]=n*E+l*A+u*G+r*J;b[14]=n*P+l*D+u*K+r*d;b[3]=p*w+y*N+x*C+c*L;b[7]=p*B+y*z+x*H+c*I;b[11]=p*E+y*A+x*G+c*J;b[15]=p*P+y*D+x*K+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=
15931 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=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],m=a[2],q=a[6],n=a[10],l=a[14];return a[3]*(+e*h*q-d*k*q-e*g*n+c*k*n+d*g*l-c*h*l)+a[7]*(+b*h*l-b*k*n+e*f*n-
15932 d*f*l+d*k*m-e*h*m)+a[11]*(+b*k*q-b*g*l-e*f*q+c*f*l+e*g*m-c*k*m)+a[15]*(-d*g*m-b*h*q+b*g*n+d*f*q-c*f*n+c*h*m)},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=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],
15933 k=d[5],m=d[6],q=d[7],n=d[8],l=d[9],u=d[10],r=d[11],p=d[12],y=d[13],x=d[14];d=d[15];var w=l*x*q-y*u*q+y*m*r-k*x*r-l*m*d+k*u*d,B=p*u*q-n*x*q-p*m*r+h*x*r+n*m*d-h*u*d,E=n*y*q-p*l*q+p*k*r-h*y*r-n*k*d+h*l*d,z=p*l*m-n*y*m-p*k*u+h*y*u+n*k*x-h*l*x,N=a*w+e*B+f*E+g*z;if(0===N){if(!0===b)throw Error("THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0");console.warn("THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0");return this.identity()}b=1/N;c[0]=w*b;c[1]=(y*u*g-l*x*g-y*f*
15934 r+e*x*r+l*f*d-e*u*d)*b;c[2]=(k*x*g-y*m*g+y*f*q-e*x*q-k*f*d+e*m*d)*b;c[3]=(l*m*g-k*u*g-l*f*q+e*u*q+k*f*r-e*m*r)*b;c[4]=B*b;c[5]=(n*x*g-p*u*g+p*f*r-a*x*r-n*f*d+a*u*d)*b;c[6]=(p*m*g-h*x*g-p*f*q+a*x*q+h*f*d-a*m*d)*b;c[7]=(h*u*g-n*m*g+n*f*q-a*u*q-h*f*r+a*m*r)*b;c[8]=E*b;c[9]=(p*l*g-n*y*g-p*e*r+a*y*r+n*e*d-a*l*d)*b;c[10]=(h*y*g-p*k*g+p*e*q-a*y*q-h*e*d+a*k*d)*b;c[11]=(n*k*g-h*l*g-n*e*q+a*l*q+h*e*r-a*k*r)*b;c[12]=z*b;c[13]=(n*y*f-p*l*f+p*e*u-a*y*u-n*e*x+a*l*x)*b;c[14]=(p*k*f-h*y*f-p*e*m+a*y*m+h*e*x-a*k*x)*
15935 b;c[15]=(h*l*f-n*k*f+n*e*m-a*l*m-h*e*u+a*k*u)*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],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=
15936 Math.cos(a);a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},makeRotationY:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},makeRotationZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(a,b){var c=Math.cos(b);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,
15937 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){var d=this.elements,e=b._x,f=b._y,g=b._z,h=b._w,k=e+e,m=f+f,q=g+g;b=e*k;var l=e*m;e*=q;var t=f*m;f*=q;g*=q;k*=h;m*=h;h*=q;q=c.x;var u=c.y;c=c.z;d[0]=(1-(t+g))*q;d[1]=(l+h)*q;d[2]=(e-m)*q;d[3]=0;d[4]=(l-h)*u;d[5]=(1-(b+g))*u;d[6]=(f+k)*u;d[7]=0;d[8]=(e+m)*c;d[9]=(f-k)*c;d[10]=(1-(b+t))*c;d[11]=0;
15938 d[12]=a.x;d[13]=a.y;d[14]=a.z;d[15]=1;return this},decompose:function(){var a=new p,b=new I;return function(c,d,e){var f=this.elements,g=a.set(f[0],f[1],f[2]).length(),h=a.set(f[4],f[5],f[6]).length(),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;f=1/h;var m=1/k;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=m;b.elements[9]*=m;b.elements[10]*=m;d.setFromRotationMatrix(b);
15939 e.x=g;e.y=h;e.z=k;return this}}(),makePerspective:function(a,b,c,d,e,f){void 0===f&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(c-d);g[9]=(c+d)/(c-d);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),m=1/(f-e);g[0]=
15940 2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*m;g[14]=-((f+e)*m);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];
15941 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(fa,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],m=c[d+2];c=c[d+3];d=e[f+0];var q=e[f+1],l=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==q||m!==l){f=1-g;var t=h*d+k*q+m*l+c*e,u=0<=t?1:-1,r=1-t*t;r>Number.EPSILON&&(r=Math.sqrt(r),t=Math.atan2(r,t*u),f=Math.sin(f*t)/r,g=Math.sin(g*
15942 t)/r);u*=g;h=h*f+d*u;k=k*f+q*u;m=m*f+l*u;c=c*f+e*u;f===1-g&&(g=1/Math.sqrt(h*h+k*k+m*m+c*c),h*=g,k*=g,m*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=m;a[b+3]=c}});Object.defineProperties(fa.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=
15943 a;this.onChangeCallback()}}});Object.assign(fa.prototype,{set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback();return this},setFromEuler:function(a,b){if(!a||!a.isEuler)throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=
15944 a._x,d=a._y,e=a._z;a=a.order;var f=Math.cos,g=Math.sin,h=f(c/2),k=f(d/2);f=f(e/2);c=g(c/2);d=g(d/2);e=g(e/2);"XYZ"===a?(this._x=c*k*f+h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f-c*d*e):"YXZ"===a?(this._x=c*k*f+h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f+c*d*e):"ZXY"===a?(this._x=c*k*f-h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f-c*d*e):"ZYX"===a?(this._x=c*k*f-h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f+c*d*e):"YZX"===a?(this._x=c*k*f+
15945 h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f-c*d*e):"XZY"===a&&(this._x=c*k*f-h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,b){b/=2;var c=Math.sin(b);this._x=a.x*c;this._y=a.y*c;this._z=a.z*c;this._w=Math.cos(b);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6];b=b[10];var m=c+f+b;0<m?(c=.5/
15946 Math.sqrt(m+1),this._w=.25/c,this._x=(k-g)*c,this._y=(d-h)*c,this._z=(e-a)*c):c>f&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a=new p,b;return function(c,d){void 0===a&&(a=new p);b=c.dot(d)+1;1E-6>b?(b=0,
15947 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()}}(),angleTo:function(a){return 2*Math.acos(Math.abs(H.clamp(this.dot(a),-1,1)))},rotateTowards:function(a,b){var c=this.angleTo(a);if(0===c)return this;this.slerp(a,Math.min(1,b/c));return this},inverse:function(){return this.conjugate()},conjugate:function(){this._x*=-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*
15948 a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),
15949 this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z;a=a._w;var f=b._x,g=b._y,h=b._z;b=b._w;this._x=c*b+a*f+d*h-e*g;this._y=d*b+a*g+e*f-c*h;this._z=e*b+a*h+c*g-d*f;this._w=a*b-c*f-d*g-e*h;this.onChangeCallback();return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;
15950 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=1-g*g;if(a<=Number.EPSILON)return g=1-b,this._w=g*f+b*this._w,this._x=g*c+b*this._x,this._y=g*d+b*this._y,this._z=g*e+b*this._z,this.normalize();a=Math.sqrt(a);var h=Math.atan2(a,g);g=Math.sin((1-b)*h)/a;b=Math.sin(b*h)/a;this._w=f*g+this._w*b;this._x=c*g+this._x*b;this._y=d*g+this._y*b;this._z=e*g+this._z*b;this.onChangeCallback();return this},equals:function(a){return a._x===
15951 this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(p.prototype,{isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},
15952 setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,
15953 this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=
15954 a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),
15955 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 fa;return function(b){b&&b.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new fa;return function(b,
15956 c){return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,
15957 c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,m=a*d+e*c-f*b;b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-m*-f;this.y=k*a+b*-f+m*-e-h*-g;this.z=m*a+b*-g+h*-f-k*-e;return this},project:function(){var a=new I;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new I;return function(b){a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyMatrix4(a)}}(),transformDirection:function(a){var b=
15958 this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,
15959 b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a=new p,b=new p;return function(c,d){a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=
15960 Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*
15961 a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,
15962 b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){return void 0!==b?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b)):this.crossVectors(this,a)},crossVectors:function(a,b){var c=a.x,d=a.y;a=a.z;var e=b.x,f=b.y;b=b.z;this.x=d*b-a*f;this.y=a*e-c*b;this.z=c*f-d*e;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=
15963 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(H.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},manhattanDistanceTo:function(a){return Math.abs(this.x-
15964 a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){a=a.elements;this.x=a[12];this.y=a[13];this.z=a[14];return this},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),
15965 c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromBufferAttribute:function(a,b,c){void 0!==
15966 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 m=this.elements;m[0]=a;m[1]=d;m[2]=g;m[3]=b;m[4]=e;m[5]=h;m[6]=c;m[7]=f;m[8]=k;return this},identity:function(){this.set(1,0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;
15967 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,a)},premultiply:function(a){return this.multiplyMatrices(a,
15968 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],m=c[2],q=c[5];c=c[8];var l=d[0],t=d[3],u=d[6],r=d[1],p=d[4],y=d[7],x=d[2],w=d[5];d=d[8];b[0]=a*l+e*r+f*x;b[3]=a*t+e*p+f*w;b[6]=a*u+e*y+f*d;b[1]=g*l+h*r+k*x;b[4]=g*t+h*p+k*w;b[7]=g*u+h*y+k*d;b[2]=m*l+q*r+c*x;b[5]=m*t+q*p+c*w;b[8]=m*u+q*y+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[3]*=a;b[6]*=a;b[1]*=a;b[4]*=a;b[7]*=a;b[2]*=a;b[5]*=a;b[8]*=
15969 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],m=c[6],q=c[7];c=c[8];var l=c*h-k*q,t=k*m-c*g,u=q*g-h*m,r=d*l+e*t+f*u;if(0===r){if(!0===b)throw Error("THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0");
15970 console.warn("THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0");return this.identity()}b=1/r;a[0]=l*b;a[1]=(f*q-c*e)*b;a[2]=(k*e-f*h)*b;a[3]=t*b;a[4]=(c*d-f*m)*b;a[5]=(f*g-k*d)*b;a[6]=u*b;a[7]=(e*m-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()},transposeIntoArray:function(a){var b=
15971 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],k=c[7];c[0]=b*d+a*g;c[3]=b*e+a*h;c[6]=
15972 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=this.elements;a[b]=c[0];a[b+1]=c[1];
15973 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 eb={getDataURL:function(a){if(a instanceof HTMLCanvasElement)var b=a;else{"undefined"!==typeof OffscreenCanvas?b=new OffscreenCanvas(a.width,a.height):(b=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),b.width=a.width,b.height=a.height);var c=b.getContext("2d");a instanceof ImageData?c.putImageData(a,0,0):c.drawImage(a,0,0,a.width,a.height)}return 2048<b.width||2048<b.height?b.toDataURL("image/jpeg",
15974 .6):b.toDataURL("image/png")}},Ef=0;T.DEFAULT_IMAGE=void 0;T.DEFAULT_MAPPING=300;T.prototype=Object.assign(Object.create(ya.prototype),{constructor:T,isTexture:!0,updateMatrix:function(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping=a.mapping;this.wrapS=a.wrapS;this.wrapT=
15975 a.wrapT;this.magFilter=a.magFilter;this.minFilter=a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.center.copy(a.center);this.rotation=a.rotation;this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrix.copy(a.matrix);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){var b=
15976 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],format:this.format,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==
15977 this.image){var d=this.image;void 0===d.uuid&&(d.uuid=H.generateUUID());if(!b&&void 0===a.images[d.uuid]){if(Array.isArray(d)){var e=[];for(var f=0,g=d.length;f<g;f++)e.push(eb.getDataURL(d[f]))}else e=eb.getDataURL(d);a.images[d.uuid]={uuid:d.uuid,url:e}}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);
15978 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)%2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}});Object.defineProperty(T.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(V.prototype,{isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=
15979 b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;
15980 case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=
15981 a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=
15982 a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;this.w*=a;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/
15983 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 m=a[10];if(.01>Math.abs(c-e)&&.01>Math.abs(d-h)&&.01>Math.abs(g-k)){if(.1>Math.abs(c+e)&&.1>Math.abs(d+h)&&.1>Math.abs(g+k)&&.1>Math.abs(b+f+m-3))return this.set(1,0,0,0),this;a=Math.PI;
15984 b=(b+1)/2;f=(f+1)/2;m=(m+1)/2;c=(c+e)/4;d=(d+h)/4;g=(g+k)/4;b>f&&b>m?.01>b?(k=0,c=h=.707106781):(k=Math.sqrt(b),h=c/k,c=d/k):f>m?.01>f?(k=.707106781,h=0,c=.707106781):(h=Math.sqrt(f),k=c/h,c=g/h):.01>m?(h=k=.707106781,c=0):(c=Math.sqrt(m),k=d/c,h=g/c);this.set(k,h,c,a);return this}a=Math.sqrt((k-g)*(k-g)+(d-h)*(d-h)+(e-c)*(e-c));.001>Math.abs(a)&&(a=1);this.x=(k-g)/a;this.y=(d-h)/a;this.z=(e-c)/a;this.w=Math.acos((b+f+m-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,
15985 a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new V,b=new V);a.set(c,
15986 c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);
15987 this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*
15988 this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,
15989 b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute().");
15990 this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}});fb.prototype=Object.assign(Object.create(ya.prototype),{constructor:fb,isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();
15991 this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Gb.prototype=Object.create(fb.prototype);Gb.prototype.constructor=Gb;Gb.prototype.isWebGLRenderTargetCube=!0;gb.prototype=Object.create(T.prototype);gb.prototype.constructor=gb;gb.prototype.isDataTexture=!0;Object.assign(Sa.prototype,{isBox3:!0,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b=
15992 Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.length;h<k;h+=3){var m=a[h],q=a[h+1],l=a[h+2];m<b&&(b=m);q<c&&(c=q);l<d&&(d=l);m>e&&(e=m);q>f&&(f=q);l>g&&(g=l)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromBufferAttribute:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;h<k;h++){var m=a.getX(h),l=a.getY(h),n=a.getZ(h);m<b&&(b=m);l<c&&(c=l);n<d&&(d=n);m>e&&(e=m);l>f&&(f=l);n>g&&(g=n)}this.min.set(b,c,d);
15993 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);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},
15994 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){void 0===a&&(console.warn("THREE.Box3: .getCenter() target is now required"),a=new p);return this.isEmpty()?a.set(0,0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){void 0===a&&(console.warn("THREE.Box3: .getSize() target is now required"),
15995 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]),e.applyMatrix4(a.matrixWorld),b.expandByPoint(e);else if(f.isBufferGeometry&&
15996 (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<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&
15997 a.max.z<=this.max.z},getParameter:function(a,b){void 0===b&&(console.warn("THREE.Box3: .getParameter() target is now required"),b=new p);return b.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,
15998 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},intersectsTriangle:function(){function a(a){var e;
15999 var f=0;for(e=a.length-3;f<=e;f+=3){h.fromArray(a,f);var g=m.x*Math.abs(h.x)+m.y*Math.abs(h.y)+m.z*Math.abs(h.z),k=b.dot(h),l=c.dot(h),q=d.dot(h);if(Math.max(-Math.max(k,l,q),Math.min(k,l,q))>g)return!1}return!0}var b=new p,c=new p,d=new p,e=new p,f=new p,g=new p,h=new p,k=new p,m=new p,l=new p;return function(h){if(this.isEmpty())return!1;this.getCenter(k);m.subVectors(this.max,k);b.subVectors(h.a,k);c.subVectors(h.b,k);d.subVectors(h.c,k);e.subVectors(c,b);f.subVectors(d,c);g.subVectors(b,d);h=
16000 [0,-e.z,e.y,0,-f.z,f.y,0,-g.z,g.y,e.z,0,-e.x,f.z,0,-f.x,g.z,0,-g.x,-e.y,e.x,0,-f.y,f.x,0,-g.y,g.x,0];if(!a(h))return!1;h=[1,0,0,0,1,0,0,0,1];if(!a(h))return!1;l.crossVectors(e,f);h=[l.x,l.y,l.z];return a(h)}}(),clampPoint:function(a,b){void 0===b&&(console.warn("THREE.Box3: .clampPoint() target is now required"),b=new p);return b.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=
16001 new p;return function(b){void 0===b&&(console.warn("THREE.Box3: .getBoundingSphere() target is now required"),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(a){if(this.isEmpty())return this;a=a.elements;var b=a[0]*this.min.x,c=a[1]*this.min.x,d=a[2]*this.min.x,e=
16002 a[0]*this.max.x,f=a[1]*this.max.x,g=a[2]*this.max.x,h=a[4]*this.min.y,k=a[5]*this.min.y,m=a[6]*this.min.y,l=a[4]*this.max.y,n=a[5]*this.max.y,t=a[6]*this.max.y,u=a[8]*this.min.z,r=a[9]*this.min.z,p=a[10]*this.min.z,y=a[8]*this.max.z,x=a[9]*this.max.z,w=a[10]*this.max.z;this.min.x=Math.min(b,e)+Math.min(h,l)+Math.min(u,y)+a[12];this.min.y=Math.min(c,f)+Math.min(k,n)+Math.min(r,x)+a[13];this.min.z=Math.min(d,g)+Math.min(m,t)+Math.min(p,w)+a[14];this.max.x=Math.max(b,e)+Math.max(h,l)+Math.max(u,y)+a[12];
16003 this.max.y=Math.max(c,f)+Math.max(k,n)+Math.max(r,x)+a[13];this.max.z=Math.max(d,g)+Math.max(m,t)+Math.max(p,w)+a[14];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 Sa;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=
16004 c=0,f=b.length;e<f;e++)c=Math.max(c,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;
16005 return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(a.distanceToPoint(this.center))<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a);void 0===b&&(console.warn("THREE.Sphere: .clampPoint() target is now required"),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){void 0===
16006 a&&(console.warn("THREE.Sphere: .getBoundingBox() target is now required"),a=new Sa);a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}});Object.assign(Ma.prototype,{set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,
16007 b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a=new p,b=new p;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=
16008 1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){void 0===b&&(console.warn("THREE.Plane: .projectPoint() target is now required"),b=new p);return b.copy(this.normal).multiplyScalar(-this.distanceToPoint(a)).add(a)},intersectLine:function(){var a=
16009 new p;return function(b,c){void 0===c&&(console.warn("THREE.Plane: .intersectLine() target is now required"),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=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)},
16010 intersectsSphere:function(a){return a.intersectsPlane(this)},coplanarPoint:function(a){void 0===a&&(console.warn("THREE.Plane: .coplanarPoint() target is now required"),a=new p);return a.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}}(),translate:function(a){this.constant-=a.dot(this.normal);
16011 return this},equals:function(a){return a.normal.equals(this.normal)&&a.constant===this.constant}});Object.assign(md.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,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],
16012 h=c[5],k=c[6],m=c[7],l=c[8],n=c[9],t=c[10],p=c[11],r=c[12],v=c[13],y=c[14];c=c[15];b[0].setComponents(f-a,m-g,p-l,c-r).normalize();b[1].setComponents(f+a,m+g,p+l,c+r).normalize();b[2].setComponents(f+d,m+h,p+n,c+v).normalize();b[3].setComponents(f-d,m-h,p-n,c-v).normalize();b[4].setComponents(f-e,m-k,p-t,c-y).normalize();b[5].setComponents(f+e,m+k,p+t,c+y).normalize();return this},intersectsObject:function(){var a=new Da;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();
16013 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;return function(b){for(var c=this.planes,d=0;6>d;d++){var e=c[d];
16014 a.x=0<e.normal.x?b.max.x:b.min.x;a.y=0<e.normal.y?b.max.y:b.min.y;a.z=0<e.normal.z?b.max.z:b.min.z;if(0>e.distanceToPoint(a))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}});var S={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",alphatest_fragment:"#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n",
16015 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",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",
16016 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 dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\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.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - 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\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( 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",
16017 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\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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",
16018 clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif\n",
16019 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",
16020 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",
16021 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( sampler2D envMap, 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",
16022 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",
16023 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",
16024 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",
16025 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\tuniform int maxMipLevel;\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",
16026 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_physical_pars_fragment:"#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( envMap, 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( envMap, 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",
16027 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",
16028 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",
16029 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",
16030 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\t#pragma unroll_loop\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\t#pragma unroll_loop\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\t#pragma unroll_loop\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\t#pragma unroll_loop\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",
16031 lights_pars_begin:"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 ltc_1;\tuniform sampler2D ltc_2;\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",
16032 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",
16033 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",
16034 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\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3(    0, 1,    0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), 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",
16035 lights_fragment_begin:"\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\t#pragma unroll_loop\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\t#pragma unroll_loop\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\t#pragma unroll_loop\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\t#pragma unroll_loop\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#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\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#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearCoatRadiance = vec3( 0.0 );\n#endif\n",
16036 lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\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 defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), maxMipLevel );\n\t#ifndef STANDARD\n\t\tclearCoatRadiance += getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), maxMipLevel );\n\t#endif\n#endif\n",
16037 lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n",
16038 logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif\n",map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",
16039 map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n",
16040 metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif",
16041 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",
16042 normal_fragment_begin:"#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",normal_fragment_maps:"#ifdef USE_NORMALMAP\n\t#ifdef OBJECTSPACE_NORMALMAP\n\t\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\t#ifdef FLIP_SIDED\n\t\t\tnormal = - normal;\n\t\t#endif\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tnormal = normalize( normalMatrix * normal );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n",
16043 normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\t#ifdef OBJECTSPACE_NORMALMAP\n\t\tuniform mat3 normalMatrix;\n\t#else\n\t\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\t\tvec2 st0 = dFdx( vUv.st );\n\t\t\tvec2 st1 = dFdy( vUv.st );\n\t\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\t\tvec3 N = normalize( surf_norm );\n\t\t\tmat3 tsn = mat3( S, T, N );\n\t\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\t\tmapN.xy *= normalScale;\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\treturn normalize( tsn * mapN );\n\t\t}\n\t#endif\n#endif\n",
16044 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",
16045 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",
16046 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",
16047 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",
16048 shadowmap_vertex:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\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\t#pragma unroll_loop\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\t#pragma unroll_loop\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",
16049 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\t#pragma unroll_loop\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\t#pragma unroll_loop\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\t#pragma unroll_loop\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",
16050 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",
16051 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",
16052 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",
16053 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",
16054 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",
16055 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",
16056 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( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n",
16057 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",
16058 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",
16059 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",
16060 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",
16061 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",
16062 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",
16063 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",
16064 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",
16065 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_begin>\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",
16066 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_begin>\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",
16067 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_begin>\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_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\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",
16068 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",
16069 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 <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\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_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\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",
16070 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",
16071 normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_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_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n",
16072 normal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_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 ) && ! defined( OBJECTSPACE_NORMALMAP ) )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n",
16073 points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_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\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",
16074 points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_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 <morphtarget_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 <fog_vertex>\n}\n",
16075 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_begin>\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",
16076 sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_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\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
16077 sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * 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\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n"},
16078 Aa={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}},Tg={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,
16079 blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,
16080 darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,
16081 lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,
16082 mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,
16083 rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Object.assign(G.prototype,
16084 {isColor:!0,r:1,g:1,b:1,set:function(a){a&&a.isColor?this.copy(a):"number"===typeof a?this.setHex(a):"string"===typeof a&&this.setStyle(a);return this},setScalar:function(a){this.b=this.g=this.r=a;return this},setHex:function(a){a=Math.floor(a);this.r=(a>>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1<d&&--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,
16085 c,d){b=H.euclideanModulo(b,1);c=H.clamp(c,0,1);d=H.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=
16086 Math.min(255,parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){d=parseFloat(c[1])/
16087 360;var 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=Tg[a],
16088 void 0!==c?this.setHex(c):console.warn("THREE.Color: Unknown color "+a));return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(a){this.r=a.r;this.g=a.g;this.b=a.b;return this},copyGammaToLinear:function(a,b){void 0===b&&(b=2);this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},copyLinearToGamma:function(a,b){void 0===b&&(b=2);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(a){this.copyGammaToLinear(this,
16089 a);return this},convertLinearToGamma:function(a){this.copyLinearToGamma(this,a);return this},copySRGBToLinear:function(){function a(a){return.04045>a?.0773993808*a:Math.pow(.9478672986*a+.0521327014,2.4)}return function(b){this.r=a(b.r);this.g=a(b.g);this.b=a(b.b);return this}}(),copyLinearToSRGB:function(){function a(a){return.0031308>a?12.92*a:1.055*Math.pow(a,.41666)-.055}return function(b){this.r=a(b.r);this.g=a(b.g);this.b=a(b.b);return this}}(),convertSRGBToLinear:function(){this.copySRGBToLinear(this);
16090 return this},convertLinearToSRGB:function(){this.copyLinearToSRGB(this);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){void 0===a&&(console.warn("THREE.Color: .getHSL() target is now required"),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):k/(2-e-f);switch(e){case b:g=(c-
16091 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(){var a={};return function(b,c,d){this.getHSL(a);a.h+=b;a.s+=c;a.l+=d;this.setHSL(a.h,a.s,a.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+=a;this.g+=
16092 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=0);this.r=
16093 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 K={common:{diffuse:{value:new G(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},maxMipLevel:{value:0}},aomap:{aoMap:{value:null},
16094 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 z(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},
16095 fogFar:{value:2E3},fogColor:{value:new G(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},
16096 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 G(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},uvTransform:{value:new ra}},
16097 sprite:{diffuse:{value:new G(15658734)},opacity:{value:1},center:{value:new z(.5,.5)},rotation:{value:0},map:{value:null},uvTransform:{value:new ra}}},nb={basic:{uniforms:Aa.merge([K.common,K.specularmap,K.envmap,K.aomap,K.lightmap,K.fog]),vertexShader:S.meshbasic_vert,fragmentShader:S.meshbasic_frag},lambert:{uniforms:Aa.merge([K.common,K.specularmap,K.envmap,K.aomap,K.lightmap,K.emissivemap,K.fog,K.lights,{emissive:{value:new G(0)}}]),vertexShader:S.meshlambert_vert,fragmentShader:S.meshlambert_frag},
16098 phong:{uniforms:Aa.merge([K.common,K.specularmap,K.envmap,K.aomap,K.lightmap,K.emissivemap,K.bumpmap,K.normalmap,K.displacementmap,K.gradientmap,K.fog,K.lights,{emissive:{value:new G(0)},specular:{value:new G(1118481)},shininess:{value:30}}]),vertexShader:S.meshphong_vert,fragmentShader:S.meshphong_frag},standard:{uniforms:Aa.merge([K.common,K.envmap,K.aomap,K.lightmap,K.emissivemap,K.bumpmap,K.normalmap,K.displacementmap,K.roughnessmap,K.metalnessmap,K.fog,K.lights,{emissive:{value:new G(0)},roughness:{value:.5},
16099 metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:S.meshphysical_vert,fragmentShader:S.meshphysical_frag},points:{uniforms:Aa.merge([K.points,K.fog]),vertexShader:S.points_vert,fragmentShader:S.points_frag},dashed:{uniforms:Aa.merge([K.common,K.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:S.linedashed_vert,fragmentShader:S.linedashed_frag},depth:{uniforms:Aa.merge([K.common,K.displacementmap]),vertexShader:S.depth_vert,fragmentShader:S.depth_frag},normal:{uniforms:Aa.merge([K.common,
16100 K.bumpmap,K.normalmap,K.displacementmap,{opacity:{value:1}}]),vertexShader:S.normal_vert,fragmentShader:S.normal_frag},sprite:{uniforms:Aa.merge([K.sprite,K.fog]),vertexShader:S.sprite_vert,fragmentShader:S.sprite_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:S.cube_vert,fragmentShader:S.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:S.equirect_vert,fragmentShader:S.equirect_frag},distanceRGBA:{uniforms:Aa.merge([K.common,K.displacementmap,
16101 {referencePosition:{value:new p},nearDistance:{value:1},farDistance:{value:1E3}}]),vertexShader:S.distanceRGBA_vert,fragmentShader:S.distanceRGBA_frag},shadow:{uniforms:Aa.merge([K.lights,K.fog,{color:{value:new G(0)},opacity:{value:1}}]),vertexShader:S.shadow_vert,fragmentShader:S.shadow_frag}};nb.physical={uniforms:Aa.merge([nb.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:S.meshphysical_vert,fragmentShader:S.meshphysical_frag};hb.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");
16102 hb.DefaultOrder="XYZ";Object.defineProperties(hb.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(hb.prototype,{isEuler:!0,set:function(a,b,c,d){this._x=a;this._y=b;this._z=
16103 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=H.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],m=e[9],l=e[2],n=e[6];e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-m,e),this._z=
16104 Math.atan2(-f,a)):(this._x=Math.atan2(n,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-l,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(n,-1,1)),.99999>Math.abs(n)?(this._y=Math.atan2(-l,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(l,-1,1)),.99999>Math.abs(l)?(this._x=Math.atan2(n,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===
16105 b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-m,k),this._y=Math.atan2(-l,a)):(this._x=0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(n,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=new I;return function(b,c,d){a.makeRotationFromQuaternion(b);
16106 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 fa;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=[]);
16107 void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new p(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(Rd.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&
16108 a.mask)}});var Gf=0;D.DefaultUp=new p(0,1,0);D.DefaultMatrixAutoUpdate=!0;D.prototype=Object.assign(Object.create(ya.prototype),{constructor:D,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,
16109 !0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new fa;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateOnWorldAxis:function(){var a=new fa;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=
16110 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,
16111 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 I;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new I,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)}}(),
16112 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]);
16113 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){void 0===a&&(console.warn("THREE.Object3D: .getWorldPosition() target is now required"),
16114 a=new p);this.updateMatrixWorld(!0);return a.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var a=new p,b=new p;return function(c){void 0===c&&(console.warn("THREE.Object3D: .getWorldQuaternion() target is now required"),c=new fa);this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldScale:function(){var a=new p,b=new fa;return function(c){void 0===c&&(console.warn("THREE.Object3D: .getWorldScale() target is now required"),c=new p);this.updateMatrixWorld(!0);
16115 this.matrixWorld.decompose(a,b,c);return c}}(),getWorldDirection:function(){var a=new fa;return function(b){void 0===b&&(console.warn("THREE.Object3D: .getWorldDirection() target is now required"),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)}},
16116 traverseAncestors:function(a){var b=this.parent;null!==b&&(a(b),b.traverseAncestors(a))},updateMatrix:function(){this.matrix.compose(this.position,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=
16117 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=[],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:{},shapes:{}},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&&
16118 (f.castShadow=!0);!0===this.receiveShadow&&(f.receiveShadow=!0);!1===this.visible&&(f.visible=!1);!1===this.frustumCulled&&(f.frustumCulled=!1);0!==this.renderOrder&&(f.renderOrder=this.renderOrder);"{}"!==JSON.stringify(this.userData)&&(f.userData=this.userData);f.layers=this.layers.mask;f.matrix=this.matrix.toArray();!1===this.matrixAutoUpdate&&(f.matrixAutoUpdate=!1);if(this.isMesh||this.isLine||this.isPoints){f.geometry=b(a.geometries,this.geometry);var g=this.geometry.parameters;if(void 0!==
16119 g&&void 0!==g.shapes)if(g=g.shapes,Array.isArray(g))for(var h=0,k=g.length;h<k;h++)b(a.shapes,g[h]);else b(a.shapes,g)}if(void 0!==this.material)if(Array.isArray(this.material)){g=[];h=0;for(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);if(d){d=c(a.geometries);h=c(a.materials);k=c(a.textures);
16120 var m=c(a.images);g=c(a.shapes);0<d.length&&(e.geometries=d);0<h.length&&(e.materials=h);0<k.length&&(e.textures=k);0<m.length&&(e.images=m);0<g.length&&(e.shapes=g)}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;
16121 this.matrixWorldNeedsUpdate=a.matrixWorldNeedsUpdate;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}});Na.prototype=Object.assign(Object.create(D.prototype),{constructor:Na,isCamera:!0,copy:function(a,b){D.prototype.copy.call(this,
16122 a,b);this.matrixWorldInverse.copy(a.matrixWorldInverse);this.projectionMatrix.copy(a.projectionMatrix);return this},getWorldDirection:function(){var a=new fa;return function(b){void 0===b&&(console.warn("THREE.Camera: .getWorldDirection() target is now required"),b=new p);this.getWorldQuaternion(a);return b.set(0,0,-1).applyQuaternion(a)}}(),updateMatrixWorld:function(a){D.prototype.updateMatrixWorld.call(this,a);this.matrixWorldInverse.getInverse(this.matrixWorld)},clone:function(){return(new this.constructor).copy(this)}});
16123 Hb.prototype=Object.assign(Object.create(Na.prototype),{constructor:Hb,isOrthographicCamera:!0,copy:function(a,b){Na.prototype.copy.call(this,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=
16124 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()},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+=a;a=d+b;b=d-b;if(null!==this.view&&this.view.enabled){c=this.zoom/(this.view.width/this.view.fullWidth);
16125 b=this.zoom/(this.view.height/this.view.fullHeight);var f=(this.right-this.left)/this.view.width;d=(this.top-this.bottom)/this.view.height;e+=this.view.offsetX/c*f;c=e+this.view.width/c*f;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=D.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;
16126 a.object.far=this.far;null!==this.view&&(a.object.view=Object.assign({},this.view));return a}});Object.assign(Ta.prototype,{clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a=a.a;this.b=a.b;this.c=a.c;this.normal.copy(a.normal);this.color.copy(a.color);this.materialIndex=a.materialIndex;for(var b=0,c=a.vertexNormals.length;b<c;b++)this.vertexNormals[b]=a.vertexNormals[b].clone();b=0;for(c=a.vertexColors.length;b<c;b++)this.vertexColors[b]=a.vertexColors[b].clone();return this}});
16127 var Hf=0;R.prototype=Object.assign(Object.create(ya.prototype),{constructor:R,isGeometry:!0,applyMatrix:function(a){for(var b=(new ra).getNormalMatrix(a),c=0,d=this.vertices.length;c<d;c++)this.vertices[c].applyMatrix4(a);c=0;for(d=this.faces.length;c<d;c++){a=this.faces[c];a.normal.applyMatrix3(b).normalize();for(var e=0,f=a.vertexNormals.length;e<f;e++)a.vertexNormals[e].applyMatrix3(b).normalize()}null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();
16128 this.normalsNeedUpdate=this.verticesNeedUpdate=!0;return this},rotateX:function(){var a=new I;return function(b){a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a=new I;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new I;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new I;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=
16129 new I;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new D;return function(b){a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),fromBufferGeometry:function(a){function b(a,b,d,e){var f=void 0!==g?[l[a].clone(),l[b].clone(),l[d].clone()]:[],q=void 0!==h?[c.colors[a].clone(),c.colors[b].clone(),c.colors[d].clone()]:[];e=new Ta(a,b,d,f,q,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([n[a].clone(),n[b].clone(),n[d].clone()]);void 0!==
16130 m&&c.faceVertexUvs[1].push([t[a].clone(),t[b].clone(),t[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=a.attributes,f=e.position.array,g=void 0!==e.normal?e.normal.array:void 0,h=void 0!==e.color?e.color.array:void 0,k=void 0!==e.uv?e.uv.array:void 0,m=void 0!==e.uv2?e.uv2.array:void 0;void 0!==m&&(this.faceVertexUvs[1]=[]);for(var l=[],n=[],t=[],u=e=0;e<f.length;e+=3,u+=2)c.vertices.push(new p(f[e],f[e+1],f[e+2])),void 0!==g&&l.push(new p(g[e],g[e+1],g[e+2])),void 0!==h&&c.colors.push(new G(h[e],
16131 h[e+1],h[e+2])),void 0!==k&&n.push(new z(k[u],k[u+1])),void 0!==m&&t.push(new z(m[u],m[u+1]));var r=a.groups;if(0<r.length)for(e=0;e<r.length;e++){f=r[e];var v=f.start,y=f.count;u=v;for(v+=y;u<v;u+=3)void 0!==d?b(d[u],d[u+1],d[u+2],f.materialIndex):b(u,u+1,u+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&&
16132 (this.boundingSphere=a.boundingSphere.clone());return this},center:function(){var a=new p;return function(){this.computeBoundingBox();this.boundingBox.getCenter(a).negate();this.translate(a.x,a.y,a.z);return this}}(),normalize:function(){this.computeBoundingSphere();var a=this.boundingSphere.center,b=this.boundingSphere.radius;b=0===b?1:1/b;var c=new I;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=
16133 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===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,
16134 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=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=
16135 !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),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):
16136 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]):d.__originalVertexNormals[e]=d.vertexNormals[e].clone()}var f=new R;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;
16137 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();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],
16138 d.normal=d.__originalFaceNormal,d.vertexNormals=d.__originalVertexNormals},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new Sa);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,m=this.faceVertexUvs[0],l=a.faceVertexUvs[0],
16139 n=this.colors,t=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new ra).getNormalMatrix(b));a=0;for(var p=g.length;a<p;a++){var r=g[a].clone();void 0!==b&&r.applyMatrix4(b);f.push(r)}a=0;for(p=t.length;a<p;a++)n.push(t[a].clone());a=0;for(p=k.length;a<p;a++){g=k[a];var v=g.vertexNormals;t=g.vertexColors;n=new Ta(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++)r=v[b].clone(),void 0!==d&&r.applyMatrix3(d).normalize(),n.vertexNormals.push(r);
16140 n.color.copy(g.color);b=0;for(f=t.length;b<f;b++)r=t[b],n.vertexColors.push(r.clone());n.materialIndex=g.materialIndex+c;h.push(n)}a=0;for(p=l.length;a<p;a++)if(c=l[a],d=[],void 0!==c){b=0;for(f=c.length;b<f;b++)d.push(c[b].clone());m.push(d)}}else console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",a)},mergeMesh:function(a){a&&a.isMesh?(a.matrixAutoUpdate&&a.updateMatrix(),this.merge(a.geometry,a.matrix)):console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",
16141 a)},mergeVertices:function(){var a={},b=[],c=[],d=Math.pow(10,4),e;var f=0;for(e=this.vertices.length;f<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=
16142 this.faceVertexUvs.length;c<e;c++)this.faceVertexUvs[c].splice(d,1);f=this.vertices.length-b.length;this.vertices=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&&
16143 e.length===b&&(g=[]);for(c=0;c<b;c++){var h=a[c]._id;f&&f.push(d[h]);g&&g.push(e[h])}f&&(this.faceVertexUvs[0]=f);g&&(this.faceVertexUvs[1]=g)},toJSON:function(){function a(a,b,c){return c?a|1<<b:a&~(1<<b)}function b(a){var b=a.x.toString()+a.y.toString()+a.z.toString();if(void 0!==m[b])return m[b];m[b]=k.length/3;k.push(a.x,a.y,a.z);return m[b]}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();if(void 0!==n[b])return n[b];n[b]=l.length;l.push(a.getHex());return n[b]}function d(a){var b=
16144 a.x.toString()+a.y.toString();if(void 0!==p[b])return p[b];p[b]=t.length/2;t.push(a.x,a.y);return p[b]}var e={metadata:{version:4.5,type:"Geometry",generator:"Geometry.toJSON"}};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);if(void 0!==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)}h=[];var k=[],m={},l=[],n={},t=[],p={};for(g=0;g<this.faces.length;g++){var r=
16145 this.faces[g],v=void 0!==this.faceVertexUvs[0][g],y=0<r.normal.length(),x=0<r.vertexNormals.length,w=1!==r.color.r||1!==r.color.g||1!==r.color.b,B=0<r.vertexColors.length,E=0;E=a(E,0,0);E=a(E,1,!0);E=a(E,2,!1);E=a(E,3,v);E=a(E,4,y);E=a(E,5,x);E=a(E,6,w);E=a(E,7,B);h.push(E);h.push(r.a,r.b,r.c);h.push(r.materialIndex);v&&(v=this.faceVertexUvs[0][g],h.push(d(v[0]),d(v[1]),d(v[2])));y&&h.push(b(r.normal));x&&(y=r.vertexNormals,h.push(b(y[0]),b(y[1]),b(y[2])));w&&h.push(c(r.color));B&&(r=r.vertexColors,
16146 h.push(c(r[0]),c(r[1]),c(r[2])))}e.data={};e.data.vertices=f;e.data.normals=k;0<l.length&&(e.data.colors=l);0<t.length&&(e.data.uvs=[t]);e.data.faces=h;return e},clone:function(){return(new R).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<
16147 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());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 m=0;for(d=h.length;m<d;m++)k.push(h[m].clone());this.faceVertexUvs[f].push(k)}}m=a.morphTargets;f=0;for(b=m.length;f<b;f++){d={};d.name=m[f].name;if(void 0!==
16148 m[f].vertices)for(d.vertices=[],e=0,c=m[f].vertices.length;e<c;e++)d.vertices.push(m[f].vertices[e].clone());if(void 0!==m[f].normals)for(d.normals=[],e=0,c=m[f].normals.length;e<c;e++)d.normals.push(m[f].normals[e].clone());this.morphTargets.push(d)}m=a.morphNormals;f=0;for(b=m.length;f<b;f++){d={};if(void 0!==m[f].vertexNormals)for(d.vertexNormals=[],e=0,c=m[f].vertexNormals.length;e<c;e++)g=m[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!==
16149 m[f].faceNormals)for(d.faceNormals=[],e=0,c=m[f].faceNormals.length;e<c;e++)d.faceNormals.push(m[f].faceNormals[e].clone());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=
16150 a.elementsNeedUpdate;this.verticesNeedUpdate=a.verticesNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.lineDistancesNeedUpdate=a.lineDistancesNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Object.defineProperty(Q.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(Q.prototype,{isBufferAttribute:!0,onUploadCallback:function(){},
16151 setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/this.itemSize:0;this.array=a;return this},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.name=a.name;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<
16152 e;d++)this.array[a+d]=b.array[c+d];return this},copyArray:function(a){this.array.set(a);return this},copyColorsArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",d),f=new G);b[c++]=f.r;b[c++]=f.g;b[c++]=f.b}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",
16153 d),f=new z);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 V);b[c++]=f.x;b[c++]=f.y;
16154 b[c++]=f.z;b[c++]=f.w}return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},getX:function(a){return this.array[a*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+
16155 3]},setW:function(a,b){this.array[a*this.itemSize+3]=b;return this},setXY:function(a,b,c){a*=this.itemSize;this.array[a+0]=b;this.array[a+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,
16156 this.itemSize)).copy(this)}});oc.prototype=Object.create(Q.prototype);oc.prototype.constructor=oc;pc.prototype=Object.create(Q.prototype);pc.prototype.constructor=pc;qc.prototype=Object.create(Q.prototype);qc.prototype.constructor=qc;rc.prototype=Object.create(Q.prototype);rc.prototype.constructor=rc;ib.prototype=Object.create(Q.prototype);ib.prototype.constructor=ib;sc.prototype=Object.create(Q.prototype);sc.prototype.constructor=sc;jb.prototype=Object.create(Q.prototype);jb.prototype.constructor=
16157 jb;A.prototype=Object.create(Q.prototype);A.prototype.constructor=A;tc.prototype=Object.create(Q.prototype);tc.prototype.constructor=tc;Object.assign(Ee.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,
16158 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 m=0;m<h;m++)k[m]=[];this.morphTargets.position=k}var l=a.morphNormals,n=l.length;if(0<n){var t=[];for(m=0;m<n;m++)t[m]=[];this.morphTargets.normal=t}var p=a.skinIndices,r=a.skinWeights,v=p.length===c.length,y=r.length===c.length;0<c.length&&0===b.length&&console.error("THREE.DirectGeometry: Faceless geometries are not supported.");for(m=0;m<b.length;m++){var x=b[m];this.vertices.push(c[x.a],c[x.b],c[x.c]);
16159 var w=x.vertexNormals;3===w.length?this.normals.push(w[0],w[1],w[2]):(w=x.normal,this.normals.push(w,w,w));w=x.vertexColors;3===w.length?this.colors.push(w[0],w[1],w[2]):(w=x.color,this.colors.push(w,w,w));!0===e&&(w=d[0][m],void 0!==w?this.uvs.push(w[0],w[1],w[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",m),this.uvs.push(new z,new z,new z)));!0===f&&(w=d[1][m],void 0!==w?this.uvs2.push(w[0],w[1],w[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",
16160 m),this.uvs2.push(new z,new z,new z)));for(w=0;w<h;w++){var B=g[w].vertices;k[w].push(B[x.a],B[x.b],B[x.c])}for(w=0;w<n;w++)B=l[w].vertexNormals[m],t[w].push(B.a,B.b,B.c);v&&this.skinIndices.push(p[x.a],p[x.b],p[x.c]);y&&this.skinWeights.push(r[x.a],r[x.b],r[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}});
16161 var If=1;C.prototype=Object.assign(Object.create(ya.prototype),{constructor:C,isBufferGeometry:!0,getIndex:function(){return this.index},setIndex:function(a){Array.isArray(a)?this.index=new (65535<Fe(a)?jb:ib)(a,1):this.index=a},addAttribute:function(a,b,c){if(!(b&&b.isBufferAttribute||b&&b.isInterleavedBufferAttribute))return console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.addAttribute(a,new Q(b,c));if("index"===a)return console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),
16162 this.setIndex(b),this;this.attributes[a]=b;return this},getAttribute:function(a){return this.attributes[a]},removeAttribute:function(a){delete this.attributes[a];return this},addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:void 0!==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;
16163 void 0!==b&&((new ra).getNormalMatrix(a).applyToBufferAttribute(b),b.needsUpdate=!0);null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a=new I;return function(b){a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a=new I;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new I;return function(b){a.makeRotationZ(b);this.applyMatrix(a);
16164 return this}}(),translate:function(){var a=new I;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new I;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new D;return function(b){a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){var a=new p;return function(){this.computeBoundingBox();this.boundingBox.getCenter(a).negate();this.translate(a.x,a.y,a.z);return this}}(),
16165 setFromObject:function(a){var b=a.geometry;if(a.isPoints||a.isLine){a=new A(3*b.vertices.length,3);var c=new A(3*b.colors.length,3);this.addAttribute("position",a.copyVector3sArray(b.vertices));this.addAttribute("color",c.copyColorsArray(b.colors));b.lineDistances&&b.lineDistances.length===b.vertices.length&&(a=new A(b.lineDistances.length,1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&(this.boundingSphere=b.boundingSphere.clone());null!==b.boundingBox&&
16166 (this.boundingBox=b.boundingBox.clone())}else a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);return this},setFromPoints:function(a){for(var b=[],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 A(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=
16167 b.normalsNeedUpdate;c.colorsNeedUpdate=b.colorsNeedUpdate;c.uvsNeedUpdate=b.uvsNeedUpdate;c.groupsNeedUpdate=b.groupsNeedUpdate;b.verticesNeedUpdate=!1;b.normalsNeedUpdate=!1;b.colorsNeedUpdate=!1;b.uvsNeedUpdate=!1;b.groupsNeedUpdate=!1;b=c}!0===b.verticesNeedUpdate&&(c=this.attributes.position,void 0!==c&&(c.copyVector3sArray(b.vertices),c.needsUpdate=!0),b.verticesNeedUpdate=!1);!0===b.normalsNeedUpdate&&(c=this.attributes.normal,void 0!==c&&(c.copyVector3sArray(b.normals),c.needsUpdate=!0),b.normalsNeedUpdate=
16168 !1);!0===b.colorsNeedUpdate&&(c=this.attributes.color,void 0!==c&&(c.copyColorsArray(b.colors),c.needsUpdate=!0),b.colorsNeedUpdate=!1);b.uvsNeedUpdate&&(c=this.attributes.uv,void 0!==c&&(c.copyVector2sArray(b.uvs),c.needsUpdate=!0),b.uvsNeedUpdate=!1);b.lineDistancesNeedUpdate&&(c=this.attributes.lineDistance,void 0!==c&&(c.copyArray(b.lineDistances),c.needsUpdate=!0),b.lineDistancesNeedUpdate=!1);b.groupsNeedUpdate&&(b.computeGroups(a.geometry),this.groups=b.groups,b.groupsNeedUpdate=!1);return this},
16169 fromGeometry:function(a){a.__directGeometry=(new Ee).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},fromDirectGeometry:function(a){var b=new Float32Array(3*a.vertices.length);this.addAttribute("position",(new Q(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new Q(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new Q(b,3)).copyColorsArray(a.colors)));
16170 0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new Q(b,2)).copyVector2sArray(a.uvs)));0<a.uvs2.length&&(b=new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new Q(b,2)).copyVector2sArray(a.uvs2)));this.groups=a.groups;for(var c in a.morphTargets){b=[];for(var d=a.morphTargets[c],e=0,f=d.length;e<f;e++){var g=d[e],h=new A(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new A(4*a.skinIndices.length,4),this.addAttribute("skinIndex",
16171 c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new A(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 Sa);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):this.boundingBox.makeEmpty();
16172 (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 Sa,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);a.getCenter(d);for(var e=0,
16173 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;if(void 0===b.normal)this.addAttribute("normal",
16174 new Q(new Float32Array(d.length),3));else for(var e=b.normal.array,f=0,g=e.length;f<g;f++)e[f]=0;e=b.normal.array;var h=new p,k=new p,m=new p,l=new p,n=new p;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var t=0,u=c.length;t<u;++t){f=c[t];g=f.start;var r=f.count;f=g;for(g+=r;f<g;f+=3){r=3*a[f+0];var v=3*a[f+1];var y=3*a[f+2];h.fromArray(d,r);k.fromArray(d,v);m.fromArray(d,y);l.subVectors(m,k);n.subVectors(h,k);l.cross(n);e[r]+=l.x;e[r+1]+=l.y;e[r+2]+=l.z;e[v]+=l.x;e[v+1]+=l.y;e[v+2]+=
16175 l.z;e[y]+=l.x;e[y+1]+=l.y;e[y+2]+=l.z}}}else for(f=0,g=d.length;f<g;f+=9)h.fromArray(d,f),k.fromArray(d,f+3),m.fromArray(d,f+6),l.subVectors(m,k),n.subVectors(h,k),l.cross(n),e[f]=l.x,e[f+1]=l.y,e[f+2]=l.z,e[f+3]=l.x,e[f+4]=l.y,e[f+5]=l.z,e[f+6]=l.x,e[f+7]=l.y,e[f+8]=l.z;this.normalizeNormals();b.normal.needsUpdate=!0}},merge:function(a,b){if(a&&a.isBufferGeometry){void 0===b&&(b=0,console.warn("THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge."));
16176 var c=this.attributes,d;for(d in c)if(void 0!==a.attributes[d]){var e=c[d].array,f=a.attributes[d],g=f.array,h=0;for(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===
16177 this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),this;var a=new C,b=this.index.array,c=this.attributes,d;for(d in c){var e=c[d],f=e.array,g=e.itemSize,h=new f.constructor(b.length*g),k=0;e=0;for(var m=b.length;e<m;e++){var l=b[e]*g;for(var n=0;n<g;n++)h[k++]=f[l++]}a.addAttribute(d,new Q(h,g))}b=this.groups;e=0;for(m=b.length;e<m;e++)c=b[e],a.addGroup(c.start,c.count,c.materialIndex);return a},toJSON:function(){var a={metadata:{version:4.5,type:"BufferGeometry",
16178 generator:"BufferGeometry.toJSON"}};a.uuid=this.uuid;a.type=this.type;""!==this.name&&(a.name=this.name);0<Object.keys(this.userData).length&&(a.userData=this.userData);if(void 0!==this.parameters){var b=this.parameters;for(e in b)void 0!==b[e]&&(a[e]=b[e]);return a}a.data={attributes:{}};var c=this.index;null!==c&&(b=Array.prototype.slice.call(c.array),a.data.index={type:c.array.constructor.name,array:b});c=this.attributes;for(e in c){var d=c[e];b=Array.prototype.slice.call(d.array);a.data.attributes[e]=
16179 {itemSize:d.itemSize,type:d.array.constructor.name,array:b,normalized:d.normalized}}var e=this.groups;0<e.length&&(a.data.groups=JSON.parse(JSON.stringify(e)));e=this.boundingSphere;null!==e&&(a.data.boundingSphere={center:e.center.toArray(),radius:e.radius});return a},clone:function(){return(new C).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());
16180 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=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;this.userData=a.userData;
16181 return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Ib.prototype=Object.create(R.prototype);Ib.prototype.constructor=Ib;kb.prototype=Object.create(C.prototype);kb.prototype.constructor=kb;uc.prototype=Object.create(R.prototype);uc.prototype.constructor=uc;lb.prototype=Object.create(C.prototype);lb.prototype.constructor=lb;var Kf=0;J.prototype=Object.assign(Object.create(ya.prototype),{constructor:J,isMaterial:!0,onBeforeCompile:function(){},setValues:function(a){if(void 0!==a)for(var b in a){var c=
16182 a[b];if(void 0===c)console.warn("THREE.Material: '"+b+"' parameter is undefined.");else if("shading"===b)console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===c?!0:!1;else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=
16183 a[c];delete d.metadata;b.push(d)}return b}var c=void 0===a||"string"===typeof a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type;""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());void 0!==this.roughness&&(d.roughness=this.roughness);void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());1!==
16184 this.emissiveIntensity&&(d.emissiveIntensity=this.emissiveIntensity);this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);void 0!==this.clearCoat&&(d.clearCoat=this.clearCoat);void 0!==this.clearCoatRoughness&&(d.clearCoatRoughness=this.clearCoatRoughness);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);this.alphaMap&&this.alphaMap.isTexture&&(d.alphaMap=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&
16185 (d.lightMap=this.lightMap.toJSON(a).uuid);this.aoMap&&this.aoMap.isTexture&&(d.aoMap=this.aoMap.toJSON(a).uuid,d.aoMapIntensity=this.aoMapIntensity);this.bumpMap&&this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&&(d.normalMap=this.normalMap.toJSON(a).uuid,d.normalMapType=this.normalMapType,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,
16186 d.displacementScale=this.displacementScale,d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&
16187 (d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity);this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid);void 0!==this.size&&(d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);!0===this.flatShading&&(d.flatShading=this.flatShading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);
16188 !0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0!==this.rotation&&(d.rotation=this.rotation);1!==this.linewidth&&(d.linewidth=this.linewidth);void 0!==this.dashSize&&(d.dashSize=this.dashSize);void 0!==this.gapSize&&(d.gapSize=this.gapSize);void 0!==this.scale&&(d.scale=this.scale);!0===this.dithering&&(d.dithering=!0);0<this.alphaTest&&(d.alphaTest=this.alphaTest);!0===this.premultipliedAlpha&&(d.premultipliedAlpha=
16189 this.premultipliedAlpha);!0===this.wireframe&&(d.wireframe=this.wireframe);1<this.wireframeLinewidth&&(d.wireframeLinewidth=this.wireframeLinewidth);"round"!==this.wireframeLinecap&&(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),
16190 a=b(a.images),0<c.length&&(d.textures=c),0<a.length&&(d.images=a));return d},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.fog=a.fog;this.lights=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=
16191 a.blendDstAlpha;this.blendEquationAlpha=a.blendEquationAlpha;this.depthFunc=a.depthFunc;this.depthTest=a.depthTest;this.depthWrite=a.depthWrite;this.colorWrite=a.colorWrite;this.precision=a.precision;this.polygonOffset=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));
16192 this.clipShadows=a.clipShadows;this.clipIntersection=a.clipIntersection;var b=a.clippingPlanes,c=null;if(null!==b){var d=b.length;c=Array(d);for(var e=0;e!==d;++e)c[e]=b[e].clone()}this.clippingPlanes=c;this.shadowSide=a.shadowSide;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});da.prototype=Object.create(J.prototype);da.prototype.constructor=da;da.prototype.isMeshBasicMaterial=!0;da.prototype.copy=function(a){J.prototype.copy.call(this,a);this.color.copy(a.color);this.map=
16193 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=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=
16194 a.morphTargets;return this};ta.prototype=Object.create(J.prototype);ta.prototype.constructor=ta;ta.prototype.isShaderMaterial=!0;ta.prototype.copy=function(a){J.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=a.vertexShader;this.uniforms=Aa.clone(a.uniforms);this.defines=Object.assign({},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;
16195 this.morphNormals=a.morphNormals;this.extensions=a.extensions;return this};ta.prototype.toJSON=function(a){a=J.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};Object.assign(mb.prototype,{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,
16196 b){void 0===b&&(console.warn("THREE.Ray: .at() target is now required"),b=new p);return b.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,b){void 0===b&&(console.warn("THREE.Ray: .closestPointToPoint() target is now required"),b=new p);b.subVectors(a,this.origin);a=b.dot(this.direction);
16197 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=new p,b=new p,c=new p;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);
16198 b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a);var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),l=-c.dot(b),n=c.lengthSq(),t=Math.abs(1-k*k);if(0<t){d=k*l-m;e=k*m-l;var p=h*t;0<=d?e>=-p?e<=p?(h=1/t,d*=h,e*=h,k=d*(d+k*e+2*m)+e*(k*d+e+2*l)+n):(e=h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+n):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+n):e<=-p?(d=Math.max(0,-(-k*h+m)),e=0<d?-h:Math.min(Math.max(-h,-l),h),k=-d*d+e*(e+2*l)+n):e<=p?(d=0,e=Math.min(Math.max(-h,-l),h),k=
16199 e*(e+2*l)+n):(d=Math.max(0,-(k*h+m)),e=0<d?h:Math.min(Math.max(-h,-l),h),k=-d*d+e*(e+2*l)+n)}else e=0<k?-h:h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*l)+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;b=Math.sqrt(b-e);e=d-b;d+=b;return 0>e&&0>d?null:0>e?this.at(d,
16200 c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){a=this.distanceToPlane(a);return null===a?null:this.at(a,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,
16201 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;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=
16202 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;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)}}(),
16203 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(ja,{getNormal:function(){var a=new p;return function(b,c,d,e){void 0===e&&(console.warn("THREE.Triangle: .getNormal() target is now required"),e=new p);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)}}(),getBarycoord:function(){var a=
16204 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 m=d*k-e*e;void 0===h&&(console.warn("THREE.Triangle: .getBarycoord() target is now required"),h=new p);if(0===m)return h.set(-2,-1,-1);m=1/m;k=(k*f-e*g)*m;d=(d*g-e*f)*m;return h.set(1-k-d,d,k)}}(),containsPoint:function(){var a=new p;return function(b,c,d,e){ja.getBarycoord(b,c,d,e,a);return 0<=a.x&&0<=a.y&&1>=a.x+a.y}}()});Object.assign(ja.prototype,
16205 {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},getArea:function(){var a=new p,b=new p;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),getMidpoint:function(a){void 0===
16206 a&&(console.warn("THREE.Triangle: .getMidpoint() target is now required"),a=new p);return a.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},getNormal:function(a){return ja.getNormal(this.a,this.b,this.c,a)},getPlane:function(a){void 0===a&&(console.warn("THREE.Triangle: .getPlane() target is now required"),a=new p);return a.setFromCoplanarPoints(this.a,this.b,this.c)},getBarycoord:function(a,b){return ja.getBarycoord(a,this.a,this.b,this.c,b)},containsPoint:function(a){return ja.containsPoint(a,
16207 this.a,this.b,this.c)},intersectsBox:function(a){return a.intersectsTriangle(this)},closestPointToPoint:function(){var a=new p,b=new p,c=new p,d=new p,e=new p,f=new p;return function(g,h){void 0===h&&(console.warn("THREE.Triangle: .closestPointToPoint() target is now required"),h=new p);var k=this.a,m=this.b,l=this.c;a.subVectors(m,k);b.subVectors(l,k);d.subVectors(g,k);var n=a.dot(d),t=b.dot(d);if(0>=n&&0>=t)return h.copy(k);e.subVectors(g,m);var u=a.dot(e),r=b.dot(e);if(0<=u&&r<=u)return h.copy(m);
16208 var v=n*r-u*t;if(0>=v&&0<=n&&0>=u)return m=n/(n-u),h.copy(k).addScaledVector(a,m);f.subVectors(g,l);g=a.dot(f);var y=b.dot(f);if(0<=y&&g<=y)return h.copy(l);n=g*t-n*y;if(0>=n&&0<=t&&0>=y)return v=t/(t-y),h.copy(k).addScaledVector(b,v);t=u*y-g*r;if(0>=t&&0<=r-u&&0<=g-y)return c.subVectors(l,m),v=(r-u)/(r-u+(g-y)),h.copy(m).addScaledVector(c,v);l=1/(t+n+v);m=n*l;v*=l;return h.copy(k).addScaledVector(a,m).addScaledVector(b,v)}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}});
16209 la.prototype=Object.assign(Object.create(D.prototype),{constructor:la,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){D.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=
16210 Object.keys(a);if(0<b.length){var c=a[b[0]];if(void 0!==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,
16211 c,d,e,f,g){ja.getBarycoord(a,b,c,d,v);e.multiplyScalar(v.x);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,m,l,n,q,p){g.fromBufferAttribute(m,n);h.fromBufferAttribute(m,q);k.fromBufferAttribute(m,
16212 p);if(c=b(c,d,e,f,g,h,k,y))l&&(t.fromBufferAttribute(l,n),u.fromBufferAttribute(l,q),r.fromBufferAttribute(l,p),c.uv=a(y,g,h,k,t,u,r)),l=new Ta(n,q,p),ja.getNormal(g,h,k,l.normal),c.face=l;return c}var d=new I,e=new mb,f=new Da,g=new p,h=new p,k=new p,m=new p,l=new p,n=new p,t=new z,u=new z,r=new z,v=new p,y=new p,x=new p;return function(q,p){var v=this.geometry,w=this.material,x=this.matrixWorld;if(void 0!==w&&(null===v.boundingSphere&&v.computeBoundingSphere(),f.copy(v.boundingSphere),f.applyMatrix4(x),
16213 !1!==q.ray.intersectsSphere(f)&&(d.getInverse(x),e.copy(q.ray).applyMatrix4(d),null===v.boundingBox||!1!==e.intersectsBox(v.boundingBox))))if(v.isBufferGeometry){var z=v.index,B=v.attributes.position,A=v.attributes.uv,D=v.groups;v=v.drawRange;var C;if(null!==z)if(Array.isArray(w)){var H=0;for(C=D.length;H<C;H++){var G=D[H];var K=w[G.materialIndex];x=Math.max(G.start,v.start);var L=Math.min(G.start+G.count,v.start+v.count);for(G=x;G<L;G+=3){x=z.getX(G);var I=z.getX(G+1);var J=z.getX(G+2);if(x=c(this,
16214 K,q,e,B,A,x,I,J))x.faceIndex=Math.floor(G/3),p.push(x)}}}else for(x=Math.max(0,v.start),L=Math.min(z.count,v.start+v.count),H=x,C=L;H<C;H+=3){if(x=z.getX(H),I=z.getX(H+1),J=z.getX(H+2),x=c(this,w,q,e,B,A,x,I,J))x.faceIndex=Math.floor(H/3),p.push(x)}else if(void 0!==B)if(Array.isArray(w))for(H=0,C=D.length;H<C;H++)for(G=D[H],K=w[G.materialIndex],x=Math.max(G.start,v.start),L=Math.min(G.start+G.count,v.start+v.count),G=x;G<L;G+=3){if(x=G,I=G+1,J=G+2,x=c(this,K,q,e,B,A,x,I,J))x.faceIndex=Math.floor(G/
16215 3),p.push(x)}else for(x=Math.max(0,v.start),L=Math.min(B.count,v.start+v.count),H=x,C=L;H<C;H+=3)if(x=H,I=H+1,J=H+2,x=c(this,w,q,e,B,A,x,I,J))x.faceIndex=Math.floor(H/3),p.push(x)}else if(v.isGeometry)for(B=Array.isArray(w),A=v.vertices,D=v.faces,x=v.faceVertexUvs[0],0<x.length&&(z=x),G=0,L=D.length;G<L;G++)if(I=D[G],x=B?w[I.materialIndex]:w,void 0!==x){H=A[I.a];C=A[I.b];K=A[I.c];if(!0===x.morphTargets){J=v.morphTargets;var R=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var Q=
16216 0,S=J.length;Q<S;Q++){var T=R[Q];if(0!==T){var V=J[Q].vertices;g.addScaledVector(m.subVectors(V[I.a],H),T);h.addScaledVector(l.subVectors(V[I.b],C),T);k.addScaledVector(n.subVectors(V[I.c],K),T)}}g.add(H);h.add(C);k.add(K);H=g;C=h;K=k}if(x=b(this,x,q,e,H,C,K,y))z&&z[G]&&(J=z[G],t.copy(J[0]),u.copy(J[1]),r.copy(J[2]),x.uv=a(y,H,C,K,t,u,r)),x.face=I,x.faceIndex=G,p.push(x)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});Ua.prototype=Object.create(T.prototype);
16217 Ua.prototype.constructor=Ua;Ua.prototype.isCubeTexture=!0;Object.defineProperty(Ua.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var Me=new T,Ne=new Ua,Ge=[],Ie=[],Le=new Float32Array(16),Ke=new Float32Array(9),Je=new Float32Array(4);Re.prototype.updateCache=function(a){var b=this.cache;a instanceof Float32Array&&b.length!==a.length&&(this.cache=new Float32Array(a.length));qa(b,a)};Se.prototype.setValue=function(a,b,c){for(var d=this.seq,e=0,f=d.length;e!==
16218 f;++e){var g=d[e];g.setValue(a,b[g.id],c)}};var Vd=/([\w\d_]+)(\])?(\[|\.)?/g;Za.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};Za.prototype.setOptional=function(a,b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};Za.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)}};Za.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 yg=
16219 0,Hg=0;$a.prototype=Object.create(J.prototype);$a.prototype.constructor=$a;$a.prototype.isMeshDepthMaterial=!0;$a.prototype.copy=function(a){J.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=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};
16220 ab.prototype=Object.create(J.prototype);ab.prototype.constructor=ab;ab.prototype.isMeshDistanceMaterial=!0;ab.prototype.copy=function(a){J.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=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;
16221 return this};Kb.prototype=Object.assign(Object.create(D.prototype),{constructor:Kb,isGroup:!0});Z.prototype=Object.assign(Object.create(Na.prototype),{constructor:Z,isPerspectiveCamera:!0,copy:function(a,b){Na.prototype.copy.call(this,a,b);this.fov=a.fov;this.zoom=a.zoom;this.near=a.near;this.far=a.far;this.focus=a.focus;this.aspect=a.aspect;this.view=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()/
16222 a;this.fov=2*H.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*H.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*H.RAD2DEG*Math.atan(Math.tan(.5*H.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,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,
16223 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()},updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*H.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=
16224 f.fullWidth,h=f.fullHeight;e+=f.offsetX*d/g;b-=f.offsetY*c/h;d*=f.width/g;c*=f.height/h}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=D.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=this.near;a.object.far=this.far;a.object.focus=this.focus;a.object.aspect=this.aspect;null!==this.view&&(a.object.view=Object.assign({},this.view));a.object.filmGauge=this.filmGauge;a.object.filmOffset=
16225 this.filmOffset;return a}});yc.prototype=Object.assign(Object.create(Z.prototype),{constructor:yc,isArrayCamera:!0});Lb.prototype.isFogExp2=!0;Lb.prototype.clone=function(){return new Lb(this.color,this.density)};Lb.prototype.toJSON=function(){return{type:"FogExp2",color:this.color.getHex(),density:this.density}};Mb.prototype.isFog=!0;Mb.prototype.clone=function(){return new Mb(this.color,this.near,this.far)};Mb.prototype.toJSON=function(){return{type:"Fog",color:this.color.getHex(),near:this.near,
16226 far:this.far}};qd.prototype=Object.assign(Object.create(D.prototype),{constructor:qd,copy:function(a,b){D.prototype.copy.call(this,a,b);null!==a.background&&(this.background=a.background.clone());null!==a.fog&&(this.fog=a.fog.clone());null!==a.overrideMaterial&&(this.overrideMaterial=a.overrideMaterial.clone());this.autoUpdate=a.autoUpdate;this.matrixAutoUpdate=a.matrixAutoUpdate;return this},toJSON:function(a){var b=D.prototype.toJSON.call(this,a);null!==this.background&&(b.object.background=this.background.toJSON(a));
16227 null!==this.fog&&(b.object.fog=this.fog.toJSON());return b}});Object.defineProperty(ob.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ob.prototype,{isInterleavedBuffer:!0,onUploadCallback:function(){},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;return this},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=
16228 new a.array.constructor(a.array);this.count=a.count;this.stride=a.stride;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.stride;c*=b.stride;for(var d=0,e=this.stride;d<e;d++)this.array[a+d]=b.array[c+d];return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},clone:function(){return(new this.constructor).copy(this)},onUpload:function(a){this.onUploadCallback=a;return this}});Object.defineProperties(zc.prototype,{count:{get:function(){return this.data.count}},
16229 array:{get:function(){return this.data.array}}});Object.assign(zc.prototype,{isInterleavedBufferAttribute:!0,setX:function(a,b){this.data.array[a*this.data.stride+this.offset]=b;return this},setY:function(a,b){this.data.array[a*this.data.stride+this.offset+1]=b;return this},setZ:function(a,b){this.data.array[a*this.data.stride+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+
16230 this.offset]},getY:function(a){return this.data.array[a*this.data.stride+this.offset+1]},getZ:function(a){return this.data.array[a*this.data.stride+this.offset+2]},getW:function(a){return this.data.array[a*this.data.stride+this.offset+3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+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,
16231 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}});cb.prototype=Object.create(J.prototype);cb.prototype.constructor=cb;cb.prototype.isSpriteMaterial=!0;cb.prototype.copy=function(a){J.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};var Nb;Ac.prototype=Object.assign(Object.create(D.prototype),{constructor:Ac,isSprite:!0,raycast:function(){function a(a,
16232 b,c,d,h,k){e.subVectors(a,c).addScalar(.5).multiply(d);void 0!==h?(f.x=k*e.x-h*e.y,f.y=h*e.x+k*e.y):f.copy(e);a.copy(b);a.x+=f.x;a.y+=f.y;a.applyMatrix4(g)}var b=new p,c=new p,d=new p,e=new z,f=new z,g=new I,h=new p,k=new p,m=new p;return function(e,f){c.setFromMatrixScale(this.matrixWorld);g.getInverse(this.modelViewMatrix).premultiply(this.matrixWorld);d.setFromMatrixPosition(this.modelViewMatrix);var l=this.material.rotation;if(0!==l){var n=Math.cos(l);var q=Math.sin(l)}l=this.center;a(h.set(-.5,
16233 -.5,0),d,l,c,q,n);a(k.set(.5,-.5,0),d,l,c,q,n);a(m.set(.5,.5,0),d,l,c,q,n);var p=e.ray.intersectTriangle(h,k,m,!1,b);if(null===p&&(a(k.set(-.5,.5,0),d,l,c,q,n),p=e.ray.intersectTriangle(h,m,k,!1,b),null===p))return;q=e.ray.origin.distanceTo(b);q<e.near||q>e.far||f.push({distance:q,point:b.clone(),face:null,object:this})}}(),clone:function(){return(new this.constructor(this.material)).copy(this)},copy:function(a){D.prototype.copy.call(this,a);void 0!==a.center&&this.center.copy(a.center);return this}});
16234 Bc.prototype=Object.assign(Object.create(D.prototype),{constructor:Bc,copy:function(a){D.prototype.copy.call(this,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-
16235 1].object},raycast:function(){var a=new p;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=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;
16236 for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=D.prototype.toJSON.call(this,a);a.object.levels=[];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(Cc.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<b;a++){var c=new I;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<
16237 b;c++)(a=this.bones[c])&&a.matrixWorld.getInverse(this.boneInverses[c]);c=0;for(b=this.bones.length;c<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 I,b=new I;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:
16238 b,d[g]),a.toArray(e,16*g);void 0!==f&&(f.needsUpdate=!0)}}(),clone:function(){return new Cc(this.bones,this.boneInverses)},getBoneByName:function(a){for(var b=0,c=this.bones.length;b<c;b++){var d=this.bones[b];if(d.name===a)return d}}});rd.prototype=Object.assign(Object.create(D.prototype),{constructor:rd,isBone:!0});sd.prototype=Object.assign(Object.create(la.prototype),{constructor:sd,isSkinnedMesh:!0,initBones:function(){var a=[],b;if(this.geometry&&void 0!==this.geometry.bones){var c=0;for(b=
16239 this.geometry.bones.length;c<b;c++){var d=this.geometry.bones[c];var e=new rd;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<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(),
16240 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=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){b=new V;var d=this.geometry.attributes.skinWeight;for(a=0;a<d.count;a++)b.x=d.getX(a),
16241 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){la.prototype.updateMatrixWorld.call(this,a);"attached"===this.bindMode?this.bindMatrixInverse.getInverse(this.matrixWorld):"detached"===this.bindMode?this.bindMatrixInverse.getInverse(this.bindMatrix):console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)},clone:function(){return(new this.constructor(this.geometry,
16242 this.material)).copy(this)}});Y.prototype=Object.create(J.prototype);Y.prototype.constructor=Y;Y.prototype.isLineBasicMaterial=!0;Y.prototype.copy=function(a){J.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;return this};sa.prototype=Object.assign(Object.create(D.prototype),{constructor:sa,isLine:!0,computeLineDistances:function(){var a=new p,b=new p;return function(){var c=this.geometry;if(c.isBufferGeometry)if(null===
16243 c.index){for(var d=c.attributes.position,e=[0],f=1,g=d.count;f<g;f++)a.fromBufferAttribute(d,f-1),b.fromBufferAttribute(d,f),e[f]=e[f-1],e[f]+=a.distanceTo(b);c.addAttribute("lineDistance",new A(e,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");else if(c.isGeometry)for(d=c.vertices,e=c.lineDistances,e[0]=0,f=1,g=d.length;f<g;f++)e[f]=e[f-1],e[f]+=d[f-1].distanceTo(d[f]);return this}}(),raycast:function(){var a=new I,b=new mb,c=
16244 new Da;return function(d,e){var f=d.linePrecision;f*=f;var 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,m=new p;h=new p;var l=new p,n=this&&this.isLineSegments?2:1;if(g.isBufferGeometry){var t=g.index,u=g.attributes.position.array;if(null!==t){t=t.array;g=0;for(var r=t.length-1;g<r;g+=n){var v=t[g+1];k.fromArray(u,3*t[g]);
16245 m.fromArray(u,3*v);v=b.distanceSqToSegment(k,m,l,h);v>f||(l.applyMatrix4(this.matrixWorld),v=d.ray.origin.distanceTo(l),v<d.near||v>d.far||e.push({distance:v,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}else for(g=0,r=u.length/3-1;g<r;g+=n)k.fromArray(u,3*g),m.fromArray(u,3*g+3),v=b.distanceSqToSegment(k,m,l,h),v>f||(l.applyMatrix4(this.matrixWorld),v=d.ray.origin.distanceTo(l),v<d.near||v>d.far||e.push({distance:v,point:h.clone().applyMatrix4(this.matrixWorld),
16246 index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(k=g.vertices,m=k.length,g=0;g<m-1;g+=n)v=b.distanceSqToSegment(k[g],k[g+1],l,h),v>f||(l.applyMatrix4(this.matrixWorld),v=d.ray.origin.distanceTo(l),v<d.near||v>d.far||e.push({distance:v,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});W.prototype=Object.assign(Object.create(sa.prototype),
16247 {constructor:W,isLineSegments:!0,computeLineDistances:function(){var a=new p,b=new p;return function(){var c=this.geometry;if(c.isBufferGeometry)if(null===c.index){for(var d=c.attributes.position,e=[],f=0,g=d.count;f<g;f+=2)a.fromBufferAttribute(d,f),b.fromBufferAttribute(d,f+1),e[f]=0===f?0:e[f-1],e[f+1]=e[f]+a.distanceTo(b);c.addAttribute("lineDistance",new A(e,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");else if(c.isGeometry)for(d=
16248 c.vertices,e=c.lineDistances,f=0,g=d.length;f<g;f+=2)a.copy(d[f]),b.copy(d[f+1]),e[f]=0===f?0:e[f-1],e[f+1]=e[f]+a.distanceTo(b);return this}}()});td.prototype=Object.assign(Object.create(sa.prototype),{constructor:td,isLineLoop:!0});Ea.prototype=Object.create(J.prototype);Ea.prototype.constructor=Ea;Ea.prototype.isPointsMaterial=!0;Ea.prototype.copy=function(a){J.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;this.morphTargets=
16249 a.morphTargets;return this};Ob.prototype=Object.assign(Object.create(D.prototype),{constructor:Ob,isPoints:!0,raycast:function(){var a=new I,b=new mb,c=new Da;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);f<l&&(b.closestPointToPoint(a,n),n.applyMatrix4(k),a=d.ray.origin.distanceTo(n),a<d.near||a>d.far||e.push({distance:a,distanceToRay:Math.sqrt(f),point:n.clone(),index:c,face:null,object:g}))}var g=this,h=this.geometry,k=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&
16250 h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);c.radius+=m;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);m/=(this.scale.x+this.scale.y+this.scale.z)/3;var l=m*m;m=new p;var n=new p;if(h.isBufferGeometry){var t=h.index;h=h.attributes.position.array;if(null!==t){var u=t.array;t=0;for(var r=u.length;t<r;t++){var v=u[t];m.fromArray(h,3*v);f(m,v)}}else for(t=0,u=h.length/3;t<u;t++)m.fromArray(h,3*t),f(m,t)}else for(m=h.vertices,t=0,u=m.length;t<
16251 u;t++)f(m[t],t)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});$d.prototype=Object.assign(Object.create(T.prototype),{constructor:$d,isVideoTexture:!0,update:function(){var a=this.image;a.readyState>=a.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}});Pb.prototype=Object.create(T.prototype);Pb.prototype.constructor=Pb;Pb.prototype.isCompressedTexture=!0;Dc.prototype=Object.create(T.prototype);Dc.prototype.constructor=Dc;Dc.prototype.isCanvasTexture=!0;Ec.prototype=
16252 Object.create(T.prototype);Ec.prototype.constructor=Ec;Ec.prototype.isDepthTexture=!0;Qb.prototype=Object.create(C.prototype);Qb.prototype.constructor=Qb;Fc.prototype=Object.create(R.prototype);Fc.prototype.constructor=Fc;Rb.prototype=Object.create(C.prototype);Rb.prototype.constructor=Rb;Gc.prototype=Object.create(R.prototype);Gc.prototype.constructor=Gc;na.prototype=Object.create(C.prototype);na.prototype.constructor=na;Hc.prototype=Object.create(R.prototype);Hc.prototype.constructor=Hc;Sb.prototype=
16253 Object.create(na.prototype);Sb.prototype.constructor=Sb;Ic.prototype=Object.create(R.prototype);Ic.prototype.constructor=Ic;pb.prototype=Object.create(na.prototype);pb.prototype.constructor=pb;Jc.prototype=Object.create(R.prototype);Jc.prototype.constructor=Jc;Tb.prototype=Object.create(na.prototype);Tb.prototype.constructor=Tb;Kc.prototype=Object.create(R.prototype);Kc.prototype.constructor=Kc;Ub.prototype=Object.create(na.prototype);Ub.prototype.constructor=Ub;Lc.prototype=Object.create(R.prototype);
16254 Lc.prototype.constructor=Lc;Vb.prototype=Object.create(C.prototype);Vb.prototype.constructor=Vb;Mc.prototype=Object.create(R.prototype);Mc.prototype.constructor=Mc;Wb.prototype=Object.create(C.prototype);Wb.prototype.constructor=Wb;Nc.prototype=Object.create(R.prototype);Nc.prototype.constructor=Nc;Xb.prototype=Object.create(C.prototype);Xb.prototype.constructor=Xb;var Ug={triangulate:function(a,b,c){c=c||2;var d=b&&b.length,e=d?b[0]*c:a.length,f=bf(a,0,e,c,!0),g=[];if(!f)return g;var h;if(d){var k=
16255 c;d=[];var m;var l=0;for(m=b.length;l<m;l++){var n=b[l]*k;var t=l<m-1?b[l+1]*k:a.length;n=bf(a,n,t,k,!1);n===n.next&&(n.steiner=!0);d.push(Pg(n))}d.sort(Ng);for(l=0;l<d.length;l++){b=d[l];k=f;if(k=Og(b,k))b=ef(k,b),Pc(b,b.next);f=Pc(f,f.next)}}if(a.length>80*c){var p=h=a[0];var r=d=a[1];for(k=c;k<e;k+=c)l=a[k],b=a[k+1],l<p&&(p=l),b<r&&(r=b),l>h&&(h=l),b>d&&(d=b);h=Math.max(h-p,d-r);h=0!==h?1/h:0}Qc(f,g,c,p,r,h);return g}},Va={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-
16256 a[e].x*a[d].y;return.5*c},isClockWise:function(a){return 0>Va.area(a)},triangulateShape:function(a,b){var c=[],d=[],e=[];ff(a);gf(c,a);var f=a.length;b.forEach(ff);for(a=0;a<b.length;a++)d.push(f),f+=b[a].length,gf(c,b[a]);b=Ug.triangulate(c,d);for(a=0;a<b.length;a+=3)e.push(b.slice(a,a+3));return e}};rb.prototype=Object.create(R.prototype);rb.prototype.constructor=rb;rb.prototype.toJSON=function(){var a=R.prototype.toJSON.call(this);return hf(this.parameters.shapes,this.parameters.options,a)};Oa.prototype=
16257 Object.create(C.prototype);Oa.prototype.constructor=Oa;Oa.prototype.toJSON=function(){var a=C.prototype.toJSON.call(this);return hf(this.parameters.shapes,this.parameters.options,a)};var Qg={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 z(b[3*c],b[3*c+1]),new z(a,d),new z(f,e)]},generateSideWallUV:function(a,b,c,d,e,f){a=b[3*c];var g=b[3*c+1];c=b[3*c+2];var h=b[3*d],k=b[3*d+1];d=b[3*d+2];var m=b[3*e],l=b[3*e+1];e=b[3*e+2];var n=b[3*f],t=b[3*f+1];b=b[3*f+
16258 2];return.01>Math.abs(g-k)?[new z(a,1-c),new z(h,1-d),new z(m,1-e),new z(n,1-b)]:[new z(g,1-c),new z(k,1-d),new z(l,1-e),new z(t,1-b)]}};Sc.prototype=Object.create(R.prototype);Sc.prototype.constructor=Sc;Yb.prototype=Object.create(Oa.prototype);Yb.prototype.constructor=Yb;Tc.prototype=Object.create(R.prototype);Tc.prototype.constructor=Tc;sb.prototype=Object.create(C.prototype);sb.prototype.constructor=sb;Uc.prototype=Object.create(R.prototype);Uc.prototype.constructor=Uc;Zb.prototype=Object.create(C.prototype);
16259 Zb.prototype.constructor=Zb;Vc.prototype=Object.create(R.prototype);Vc.prototype.constructor=Vc;$b.prototype=Object.create(C.prototype);$b.prototype.constructor=$b;tb.prototype=Object.create(R.prototype);tb.prototype.constructor=tb;tb.prototype.toJSON=function(){var a=R.prototype.toJSON.call(this);return jf(this.parameters.shapes,a)};ub.prototype=Object.create(C.prototype);ub.prototype.constructor=ub;ub.prototype.toJSON=function(){var a=C.prototype.toJSON.call(this);return jf(this.parameters.shapes,
16260 a)};ac.prototype=Object.create(C.prototype);ac.prototype.constructor=ac;vb.prototype=Object.create(R.prototype);vb.prototype.constructor=vb;Wa.prototype=Object.create(C.prototype);Wa.prototype.constructor=Wa;Wc.prototype=Object.create(vb.prototype);Wc.prototype.constructor=Wc;Xc.prototype=Object.create(Wa.prototype);Xc.prototype.constructor=Xc;Yc.prototype=Object.create(R.prototype);Yc.prototype.constructor=Yc;bc.prototype=Object.create(C.prototype);bc.prototype.constructor=bc;var xa=Object.freeze({WireframeGeometry:Qb,
16261 ParametricGeometry:Fc,ParametricBufferGeometry:Rb,TetrahedronGeometry:Hc,TetrahedronBufferGeometry:Sb,OctahedronGeometry:Ic,OctahedronBufferGeometry:pb,IcosahedronGeometry:Jc,IcosahedronBufferGeometry:Tb,DodecahedronGeometry:Kc,DodecahedronBufferGeometry:Ub,PolyhedronGeometry:Gc,PolyhedronBufferGeometry:na,TubeGeometry:Lc,TubeBufferGeometry:Vb,TorusKnotGeometry:Mc,TorusKnotBufferGeometry:Wb,TorusGeometry:Nc,TorusBufferGeometry:Xb,TextGeometry:Sc,TextBufferGeometry:Yb,SphereGeometry:Tc,SphereBufferGeometry:sb,
16262 RingGeometry:Uc,RingBufferGeometry:Zb,PlaneGeometry:uc,PlaneBufferGeometry:lb,LatheGeometry:Vc,LatheBufferGeometry:$b,ShapeGeometry:tb,ShapeBufferGeometry:ub,ExtrudeGeometry:rb,ExtrudeBufferGeometry:Oa,EdgesGeometry:ac,ConeGeometry:Wc,ConeBufferGeometry:Xc,CylinderGeometry:vb,CylinderBufferGeometry:Wa,CircleGeometry:Yc,CircleBufferGeometry:bc,BoxGeometry:Ib,BoxBufferGeometry:kb});wb.prototype=Object.create(J.prototype);wb.prototype.constructor=wb;wb.prototype.isShadowMaterial=!0;wb.prototype.copy=
16263 function(a){J.prototype.copy.call(this,a);this.color.copy(a.color);return this};cc.prototype=Object.create(ta.prototype);cc.prototype.constructor=cc;cc.prototype.isRawShaderMaterial=!0;Pa.prototype=Object.create(J.prototype);Pa.prototype.constructor=Pa;Pa.prototype.isMeshStandardMaterial=!0;Pa.prototype.copy=function(a){J.prototype.copy.call(this,a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=
16264 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.normalMapType=a.normalMapType;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;this.metalnessMap=
16265 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};xb.prototype=Object.create(Pa.prototype);xb.prototype.constructor=xb;xb.prototype.isMeshPhysicalMaterial=
16266 !0;xb.prototype.copy=function(a){Pa.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Fa.prototype=Object.create(J.prototype);Fa.prototype.constructor=Fa;Fa.prototype.isMeshPhongMaterial=!0;Fa.prototype.copy=function(a){J.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=
16267 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.normalMapType=a.normalMapType;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;
16268 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};yb.prototype=Object.create(Fa.prototype);yb.prototype.constructor=yb;yb.prototype.isMeshToonMaterial=!0;yb.prototype.copy=function(a){Fa.prototype.copy.call(this,
16269 a);this.gradientMap=a.gradientMap;return this};zb.prototype=Object.create(J.prototype);zb.prototype.constructor=zb;zb.prototype.isMeshNormalMaterial=!0;zb.prototype.copy=function(a){J.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalMapType=a.normalMapType;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;
16270 this.wireframeLinewidth=a.wireframeLinewidth;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};Ab.prototype=Object.create(J.prototype);Ab.prototype.constructor=Ab;Ab.prototype.isMeshLambertMaterial=!0;Ab.prototype.copy=function(a){J.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);
16271 this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};
16272 Bb.prototype=Object.create(Y.prototype);Bb.prototype.constructor=Bb;Bb.prototype.isLineDashedMaterial=!0;Bb.prototype.copy=function(a){Y.prototype.copy.call(this,a);this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var Vg=Object.freeze({ShadowMaterial:wb,SpriteMaterial:cb,RawShaderMaterial:cc,ShaderMaterial:ta,PointsMaterial:Ea,MeshPhysicalMaterial:xb,MeshStandardMaterial:Pa,MeshPhongMaterial:Fa,MeshToonMaterial:yb,MeshNormalMaterial:zb,MeshLambertMaterial:Ab,MeshDepthMaterial:$a,
16273 MeshDistanceMaterial:ab,MeshBasicMaterial:da,LineDashedMaterial:Bb,LineBasicMaterial:Y,Material:J}),Fb={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={}}},ka=new ce,Ya={};Object.assign(Ga.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=Fb.get(a);if(void 0!==f)return e.manager.itemStart(a),
16274 setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;if(void 0!==Ya[a])Ya[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":var m=new Uint8Array(g.length);for(h=0;h<g.length;h++)m[h]=g.charCodeAt(h);var l="blob"===k?new Blob([m.buffer],{type:c}):m.buffer;break;case "document":l=
16275 (new DOMParser).parseFromString(g,c);break;case "json":l=JSON.parse(g);break;default:l=g}window.setTimeout(function(){b&&b(l);e.manager.itemEnd(a)},0)}catch(t){window.setTimeout(function(){d&&d(t);e.manager.itemEnd(a);e.manager.itemError(a)},0)}}else{Ya[a]=[];Ya[a].push({onLoad:b,onProgress:c,onError:d});var n=new XMLHttpRequest;n.open("GET",a,!0);n.addEventListener("load",function(b){var c=this.response;Fb.add(a,c);var d=Ya[a];delete Ya[a];if(200===this.status||0===this.status){0===this.status&&
16276 console.warn("THREE.FileLoader: HTTP Status 0 received.");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{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=Ya[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=Ya[a];delete Ya[a];for(var d=0,f=c.length;d<f;d++){var g=c[d];if(g.onError)g.onError(b)}e.manager.itemEnd(a);
16277 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=a;return this},setWithCredentials:function(a){this.withCredentials=
16278 a;return this},setMimeType:function(a){this.mimeType=a;return this},setRequestHeader:function(a){this.requestHeader=a;return this}});Object.assign(kf.prototype,{load:function(a,b,c,d){function e(e){k.load(a[e],function(a){a=f._parser(a,!0);g[e]={width:a.width,height:a.height,format:a.format,mipmaps:a.mipmaps};m+=1;6===m&&(1===a.mipmapCount&&(h.minFilter=1006),h.format=a.format,h.needsUpdate=!0,b&&b(h))},c,d)}var f=this,g=[],h=new Pb;h.image=g;var k=new Ga(this.manager);k.setPath(this.path);k.setResponseType("arraybuffer");
16279 if(Array.isArray(a))for(var m=0,l=0,n=a.length;l<n;++l)e(l);else k.load(a,function(a){a=f._parser(a,!0);if(a.isCubemap)for(var c=a.mipmaps.length/a.mipmapCount,d=0;d<c;d++){g[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)g[d].mipmaps.push(a.mipmaps[d*a.mipmapCount+e]),g[d].format=a.format,g[d].width=a.width,g[d].height=a.height}else h.image.width=a.width,h.image.height=a.height,h.mipmaps=a.mipmaps;1===a.mipmapCount&&(h.minFilter=1006);h.format=a.format;h.needsUpdate=!0;b&&b(h)},c,d);return h},setPath:function(a){this.path=
16280 a;return this}});Object.assign(de.prototype,{load:function(a,b,c,d){var e=this,f=new gb,g=new Ga(this.manager);g.setResponseType("arraybuffer");g.load(a,function(a){if(a=e._parser(a))void 0!==a.image?f.image=a.image:void 0!==a.data&&(f.image.width=a.width,f.image.height=a.height,f.image.data=a.data),f.wrapS=void 0!==a.wrapS?a.wrapS:1001,f.wrapT=void 0!==a.wrapT?a.wrapT:1001,f.magFilter=void 0!==a.magFilter?a.magFilter:1006,f.minFilter=void 0!==a.minFilter?a.minFilter:1008,f.anisotropy=void 0!==a.anisotropy?
16281 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(Zc.prototype,{crossOrigin:"anonymous",load:function(a,b,c,d){function e(){k.removeEventListener("load",e,!1);k.removeEventListener("error",f,!1);Fb.add(a,this);b&&b(this);g.manager.itemEnd(a)}function f(b){k.removeEventListener("load",e,!1);k.removeEventListener("error",f,!1);
16282 d&&d(b);g.manager.itemEnd(a);g.manager.itemError(a)}void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);a=this.manager.resolveURL(a);var g=this,h=Fb.get(a);if(void 0!==h)return g.manager.itemStart(a),setTimeout(function(){b&&b(h);g.manager.itemEnd(a)},0),h;var k=document.createElementNS("http://www.w3.org/1999/xhtml","img");k.addEventListener("load",e,!1);k.addEventListener("error",f,!1);"data:"!==a.substr(0,5)&&void 0!==this.crossOrigin&&(k.crossOrigin=this.crossOrigin);g.manager.itemStart(a);
16283 k.src=a;return k},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(ee.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 Zc(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=
16284 a;return this}});Object.assign(vd.prototype,{crossOrigin:"anonymous",load:function(a,b,c,d){var e=new T,f=new Zc(this.manager);f.setCrossOrigin(this.crossOrigin);f.setPath(this.path);f.load(a,function(c){e.image=c;c=0<a.search(/\.(jpg|jpeg)$/)||0===a.search(/^data:image\/jpeg/);e.format=c?1022:1023;e.needsUpdate=!0;void 0!==b&&b(e)},c,d);return e},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(L.prototype,{getPoint:function(){console.warn("THREE.Curve: .getPoint() not implemented.");
16285 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/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;
16286 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,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=
16287 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=[],g=new p,h=new I,k;for(k=0;k<=a;k++){var m=k/a;d[k]=this.getTangentAt(m);d[k].normalize()}e[0]=new p;f[0]=new p;k=Number.MAX_VALUE;m=Math.abs(d[0].x);var l=Math.abs(d[0].y),n=Math.abs(d[0].z);m<=k&&(k=m,c.set(1,0,0));l<=k&&(k=l,c.set(0,1,0));n<=k&&c.set(0,
16288 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(H.clamp(d[k-1].dot(d[k]),-1,1)),e[k].applyMatrix4(h.makeRotationAxis(g,c))),f[k].crossVectors(d[k],e[k]);if(!0===b)for(c=Math.acos(H.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],
16289 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},toJSON:function(){var a={metadata:{version:4.5,type:"Curve",generator:"Curve.toJSON"}};a.arcLengthDivisions=this.arcLengthDivisions;a.type=this.type;return a},fromJSON:function(a){this.arcLengthDivisions=a.arcLengthDivisions;return this}});za.prototype=Object.create(L.prototype);za.prototype.constructor=
16290 za;za.prototype.isEllipseCurve=!0;za.prototype.getPoint=function(a,b){b=b||new z;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,
16291 f)};za.prototype.copy=function(a){L.prototype.copy.call(this,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};za.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.aX=this.aX;a.aY=this.aY;a.xRadius=this.xRadius;a.yRadius=this.yRadius;a.aStartAngle=this.aStartAngle;a.aEndAngle=this.aEndAngle;a.aClockwise=this.aClockwise;a.aRotation=
16292 this.aRotation;return a};za.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,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};dc.prototype=Object.create(za.prototype);dc.prototype.constructor=dc;dc.prototype.isArcCurve=!0;var Od=new p,Ae=new fe,Be=new fe,Ce=new fe;ca.prototype=Object.create(L.prototype);ca.prototype.constructor=ca;ca.prototype.isCatmullRomCurve3=
16293 !0;ca.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)/d)+1)*d:0===a&&e===d-1&&(e=d-2,a=1);if(this.closed||0<e)var f=c[(e-1)%d];else Od.subVectors(c[0],c[1]).add(c[0]),f=Od;var g=c[e%d];var h=c[(e+1)%d];this.closed||e+2<d?c=c[(e+2)%d]:(Od.subVectors(c[d-1],c[d-2]).add(c[d-1]),c=Od);if("centripetal"===this.curveType||"chordal"===this.curveType){var k="chordal"===this.curveType?.5:.25;
16294 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);Ae.initNonuniformCatmullRom(f.x,g.x,h.x,c.x,d,e,k);Be.initNonuniformCatmullRom(f.y,g.y,h.y,c.y,d,e,k);Ce.initNonuniformCatmullRom(f.z,g.z,h.z,c.z,d,e,k)}else"catmullrom"===this.curveType&&(Ae.initCatmullRom(f.x,g.x,h.x,c.x,this.tension),Be.initCatmullRom(f.y,g.y,h.y,c.y,this.tension),Ce.initCatmullRom(f.z,g.z,h.z,c.z,this.tension));b.set(Ae.calc(a),
16295 Be.calc(a),Ce.calc(a));return b};ca.prototype.copy=function(a){L.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};ca.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.points=[];for(var b=0,c=this.points.length;b<c;b++)a.points.push(this.points[b].toArray());a.closed=this.closed;a.curveType=this.curveType;a.tension=this.tension;return a};
16296 ca.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.points=[];for(var b=0,c=a.points.length;b<c;b++){var d=a.points[b];this.points.push((new p).fromArray(d))}this.closed=a.closed;this.curveType=a.curveType;this.tension=a.tension;return this};Ha.prototype=Object.create(L.prototype);Ha.prototype.constructor=Ha;Ha.prototype.isCubicBezierCurve=!0;Ha.prototype.getPoint=function(a,b){b=b||new z;var c=this.v0,d=this.v1,e=this.v2,f=this.v3;b.set(ad(a,c.x,d.x,e.x,f.x),ad(a,c.y,d.y,e.y,
16297 f.y));return b};Ha.prototype.copy=function(a){L.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};Ha.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v0=this.v0.toArray();a.v1=this.v1.toArray();a.v2=this.v2.toArray();a.v3=this.v3.toArray();return a};Ha.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v0.fromArray(a.v0);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);this.v3.fromArray(a.v3);return this};
16298 Qa.prototype=Object.create(L.prototype);Qa.prototype.constructor=Qa;Qa.prototype.isCubicBezierCurve3=!0;Qa.prototype.getPoint=function(a,b){b=b||new p;var c=this.v0,d=this.v1,e=this.v2,f=this.v3;b.set(ad(a,c.x,d.x,e.x,f.x),ad(a,c.y,d.y,e.y,f.y),ad(a,c.z,d.z,e.z,f.z));return b};Qa.prototype.copy=function(a){L.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};Qa.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v0=this.v0.toArray();
16299 a.v1=this.v1.toArray();a.v2=this.v2.toArray();a.v3=this.v3.toArray();return a};Qa.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v0.fromArray(a.v0);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);this.v3.fromArray(a.v3);return this};va.prototype=Object.create(L.prototype);va.prototype.constructor=va;va.prototype.isLineCurve=!0;va.prototype.getPoint=function(a,b){b=b||new z;1===a?b.copy(this.v2):(b.copy(this.v2).sub(this.v1),b.multiplyScalar(a).add(this.v1));return b};va.prototype.getPointAt=
16300 function(a,b){return this.getPoint(a,b)};va.prototype.getTangent=function(){return this.v2.clone().sub(this.v1).normalize()};va.prototype.copy=function(a){L.prototype.copy.call(this,a);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};va.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v1=this.v1.toArray();a.v2=this.v2.toArray();return a};va.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);return this};Ia.prototype=
16301 Object.create(L.prototype);Ia.prototype.constructor=Ia;Ia.prototype.isLineCurve3=!0;Ia.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};Ia.prototype.getPointAt=function(a,b){return this.getPoint(a,b)};Ia.prototype.copy=function(a){L.prototype.copy.call(this,a);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};Ia.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v1=this.v1.toArray();a.v2=this.v2.toArray();
16302 return a};Ia.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);return this};Ja.prototype=Object.create(L.prototype);Ja.prototype.constructor=Ja;Ja.prototype.isQuadraticBezierCurve=!0;Ja.prototype.getPoint=function(a,b){b=b||new z;var c=this.v0,d=this.v1,e=this.v2;b.set($c(a,c.x,d.x,e.x),$c(a,c.y,d.y,e.y));return b};Ja.prototype.copy=function(a){L.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};
16303 Ja.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v0=this.v0.toArray();a.v1=this.v1.toArray();a.v2=this.v2.toArray();return a};Ja.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v0.fromArray(a.v0);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);return this};Ra.prototype=Object.create(L.prototype);Ra.prototype.constructor=Ra;Ra.prototype.isQuadraticBezierCurve3=!0;Ra.prototype.getPoint=function(a,b){b=b||new p;var c=this.v0,d=this.v1,e=this.v2;b.set($c(a,c.x,
16304 d.x,e.x),$c(a,c.y,d.y,e.y),$c(a,c.z,d.z,e.z));return b};Ra.prototype.copy=function(a){L.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};Ra.prototype.toJSON=function(){var a=L.prototype.toJSON.call(this);a.v0=this.v0.toArray();a.v1=this.v1.toArray();a.v2=this.v2.toArray();return a};Ra.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.v0.fromArray(a.v0);this.v1.fromArray(a.v1);this.v2.fromArray(a.v2);return this};Ka.prototype=Object.create(L.prototype);
16305 Ka.prototype.constructor=Ka;Ka.prototype.isSplineCurve=!0;Ka.prototype.getPoint=function(a,b){b=b||new z;var c=this.points,d=(c.length-1)*a;a=Math.floor(d);d-=a;var 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(lf(d,e.x,f.x,g.x,c.x),lf(d,e.y,f.y,g.y,c.y));return b};Ka.prototype.copy=function(a){L.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};Ka.prototype.toJSON=function(){var a=
16306 L.prototype.toJSON.call(this);a.points=[];for(var b=0,c=this.points.length;b<c;b++)a.points.push(this.points[b].toArray());return a};Ka.prototype.fromJSON=function(a){L.prototype.fromJSON.call(this,a);this.points=[];for(var b=0,c=a.points.length;b<c;b++){var d=a.points[b];this.points.push((new z).fromArray(d))}return this};var Af=Object.freeze({ArcCurve:dc,CatmullRomCurve3:ca,CubicBezierCurve:Ha,CubicBezierCurve3:Qa,EllipseCurve:za,LineCurve:va,LineCurve3:Ia,QuadraticBezierCurve:Ja,QuadraticBezierCurve3:Ra,
16307 SplineCurve:Ka});Xa.prototype=Object.assign(Object.create(L.prototype),{constructor:Xa,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 va(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();
16308 return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=!0;this.cacheLengths=null;this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;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=
16309 a||12;for(var b=[],c,d=0,e=this.curves;d<e.length;d++){var f=e[d];f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&(f.isLineCurve||f.isLineCurve3)?1:f&&f.isSplineCurve?a*f.points.length:a);for(var 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){L.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},
16310 toJSON:function(){var a=L.prototype.toJSON.call(this);a.autoClose=this.autoClose;a.curves=[];for(var b=0,c=this.curves.length;b<c;b++)a.curves.push(this.curves[b].toJSON());return a},fromJSON:function(a){L.prototype.fromJSON.call(this,a);this.autoClose=a.autoClose;this.curves=[];for(var b=0,c=a.curves.length;b<c;b++){var d=a.curves[b];this.curves.push((new Af[d.type]).fromJSON(d))}return this}});La.prototype=Object.assign(Object.create(Xa.prototype),{constructor:La,setFromPoints:function(a){this.moveTo(a[0].x,
16311 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 va(this.currentPoint.clone(),new z(a,b));this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,b,c,d){a=new Ja(this.currentPoint.clone(),new z(a,b),new z(c,d));this.curves.push(a);this.currentPoint.set(c,d)},bezierCurveTo:function(a,b,c,d,e,f){a=new Ha(this.currentPoint.clone(),new z(a,b),new z(c,d),new z(e,f));this.curves.push(a);
16312 this.currentPoint.set(e,f)},splineThru:function(a){var b=[this.currentPoint.clone()].concat(a);b=new Ka(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,e,f,g,h){a=new za(a,b,c,d,e,f,g,h);0<this.curves.length&&
16313 (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){Xa.prototype.copy.call(this,a);this.currentPoint.copy(a.currentPoint);return this},toJSON:function(){var a=Xa.prototype.toJSON.call(this);a.currentPoint=this.currentPoint.toArray();return a},fromJSON:function(a){Xa.prototype.fromJSON.call(this,a);this.currentPoint.fromArray(a.currentPoint);return this}});db.prototype=Object.assign(Object.create(La.prototype),
16314 {constructor:db,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),holes:this.getPointsHoles(a)}},copy:function(a){La.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},toJSON:function(){var a=La.prototype.toJSON.call(this);a.uuid=this.uuid;a.holes=[];for(var b=0,c=this.holes.length;b<c;b++)a.holes.push(this.holes[b].toJSON());
16315 return a},fromJSON:function(a){La.prototype.fromJSON.call(this,a);this.uuid=a.uuid;this.holes=[];for(var b=0,c=a.holes.length;b<c;b++){var d=a.holes[b];this.holes.push((new La).fromJSON(d))}return this}});X.prototype=Object.assign(Object.create(D.prototype),{constructor:X,isLight:!0,copy:function(a){D.prototype.copy.call(this,a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=D.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();a.object.intensity=
16316 this.intensity;void 0!==this.groundColor&&(a.object.groundColor=this.groundColor.getHex());void 0!==this.distance&&(a.object.distance=this.distance);void 0!==this.angle&&(a.object.angle=this.angle);void 0!==this.decay&&(a.object.decay=this.decay);void 0!==this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&(a.object.shadow=this.shadow.toJSON());return a}});wd.prototype=Object.assign(Object.create(X.prototype),{constructor:wd,isHemisphereLight:!0,copy:function(a){X.prototype.copy.call(this,
16317 a);this.groundColor.copy(a.groundColor);return this}});Object.assign(Cb.prototype,{copy:function(a){this.camera=a.camera.clone();this.bias=a.bias;this.radius=a.radius;this.mapSize.copy(a.mapSize);return this},clone:function(){return(new this.constructor).copy(this)},toJSON:function(){var a={};0!==this.bias&&(a.bias=this.bias);1!==this.radius&&(a.radius=this.radius);if(512!==this.mapSize.x||512!==this.mapSize.y)a.mapSize=this.mapSize.toArray();a.camera=this.camera.toJSON(!1).object;delete a.camera.matrix;
16318 return a}});xd.prototype=Object.assign(Object.create(Cb.prototype),{constructor:xd,isSpotLightShadow:!0,update:function(a){var b=this.camera,c=2*H.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()}});yd.prototype=Object.assign(Object.create(X.prototype),{constructor:yd,isSpotLight:!0,copy:function(a){X.prototype.copy.call(this,a);this.distance=a.distance;this.angle=a.angle;this.penumbra=
16319 a.penumbra;this.decay=a.decay;this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});zd.prototype=Object.assign(Object.create(X.prototype),{constructor:zd,isPointLight:!0,copy:function(a){X.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();return this}});Ad.prototype=Object.assign(Object.create(Cb.prototype),{constructor:Ad});Bd.prototype=Object.assign(Object.create(X.prototype),{constructor:Bd,isDirectionalLight:!0,copy:function(a){X.prototype.copy.call(this,
16320 a);this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});Cd.prototype=Object.assign(Object.create(X.prototype),{constructor:Cd,isAmbientLight:!0});Dd.prototype=Object.assign(Object.create(X.prototype),{constructor:Dd,isRectAreaLight:!0,copy:function(a){X.prototype.copy.call(this,a);this.width=a.width;this.height=a.height;return this},toJSON:function(a){a=X.prototype.toJSON.call(this,a);a.object.width=this.width;a.object.height=this.height;return a}});var ia={arraySlice:function(a,
16321 b,c){return ia.isTypedArray(a)?new a.constructor(a.subarray(b,void 0!==c?c:a.length)):a.slice(b,c)},convertArray:function(a,b,c){return!a||!c&&a.constructor===b?a:"number"===typeof b.BYTES_PER_ELEMENT?new b(a):Array.prototype.slice.call(a)},isTypedArray:function(a){return ArrayBuffer.isView(a)&&!(a instanceof DataView)},getKeyframeOrder:function(a){for(var b=a.length,c=Array(b),d=0;d!==b;++d)c[d]=d;c.sort(function(b,c){return a[b]-a[c]});return c},sortedArray:function(a,b,c){for(var d=a.length,e=
16322 new a.constructor(d),f=0,g=0;g!==d;++f)for(var h=c[f]*b,k=0;k!==b;++k)e[g++]=a[h+k];return e},flattenJSON:function(a,b,c,d){for(var e=1,f=a[0];void 0!==f&&void 0===f[d];)f=a[e++];if(void 0!==f){var g=f[d];if(void 0!==g)if(Array.isArray(g)){do g=f[d],void 0!==g&&(b.push(f.time),c.push.apply(c,g)),f=a[e++];while(void 0!==f)}else if(void 0!==g.toArray){do g=f[d],void 0!==g&&(b.push(f.time),g.toArray(c,c.length)),f=a[e++];while(void 0!==f)}else{do g=f[d],void 0!==g&&(b.push(f.time),c.push(g)),f=a[e++];
16323 while(void 0!==f)}}}};Object.assign(wa.prototype,{evaluate:function(a){var b=this.parameterPositions,c=this._cachedIndex,d=b[c],e=b[c-1];a:{b:{c:{d:if(!(a<d)){for(var f=c+2;;){if(void 0===d){if(a<e)break d;this._cachedIndex=c=b.length;return this.afterEnd_(c-1,a,e)}if(c===f)break;e=d;d=b[++c];if(a<d)break b}d=b.length;break c}if(a>=e)break a;else{f=b[1];a<f&&(c=2,e=f);for(f=c-2;;){if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(c===f)break;d=e;e=b[--c-1];if(a>=e)break b}d=c;c=
16324 0}}for(;c<d;)e=c+d>>>1,a<b[e]?d=e:c=e+1;d=b[c];e=b[c-1];if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(void 0===d)return this._cachedIndex=c=b.length,this.afterEnd_(c-1,e,a)}this._cachedIndex=c;this.intervalChanged_(c,e,d)}return this.interpolate_(c,e,a,d)},settings:null,DefaultSettings_:{},getSettings_:function(){return this.settings||this.DefaultSettings_},copySampleValue_:function(a){var b=this.resultBuffer,c=this.sampleValues,d=this.valueSize;a*=d;for(var e=0;e!==d;++e)b[e]=
16325 c[a+e];return b},interpolate_:function(){throw Error("call to abstract method");},intervalChanged_:function(){}});Object.assign(wa.prototype,{beforeStart_:wa.prototype.copySampleValue_,afterEnd_:wa.prototype.copySampleValue_});Ed.prototype=Object.assign(Object.create(wa.prototype),{constructor:Ed,DefaultSettings_:{endingStart:2400,endingEnd:2400},intervalChanged_:function(a,b,c){var d=this.parameterPositions,e=a-2,f=a+1,g=d[e],h=d[f];if(void 0===g)switch(this.getSettings_().endingStart){case 2401:e=
16326 a;g=2*b-c;break;case 2402:e=d.length-2;g=b+d[e]-d[e+1];break;default:e=a,g=c}if(void 0===h)switch(this.getSettings_().endingEnd){case 2401:f=a;h=2*c-b;break;case 2402:f=1;h=c+d[1]-d[0];break;default:f=a-1,h=b}a=.5*(c-b);d=this.valueSize;this._weightPrev=a/(b-g);this._weightNext=a/(h-c);this._offsetPrev=e*d;this._offsetNext=f*d},interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g,k=this._offsetPrev,m=this._offsetNext,l=this._weightPrev,n=this._weightNext,
16327 p=(c-b)/(d-b);c=p*p;d=c*p;b=-l*d+2*l*c-l*p;l=(1+l)*d+(-1.5-2*l)*c+(-.5+l)*p+1;p=(-1-n)*d+(1.5+n)*c+.5*p;n=n*d-n*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+l*f[h+c]+p*f[a+c]+n*f[m+c];return e}});bd.prototype=Object.assign(Object.create(wa.prototype),{constructor:bd,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g;b=(c-b)/(d-b);c=1-b;for(d=0;d!==g;++d)e[d]=f[h+d]*c+f[a+d]*b;return e}});Fd.prototype=Object.assign(Object.create(wa.prototype),{constructor:Fd,
16328 interpolate_:function(a){return this.copySampleValue_(a-1)}});Object.assign(oa,{toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=b.toJSON(a);else{b={name:a.name,times:ia.convertArray(a.times,Array),values:ia.convertArray(a.values,Array)};var c=a.getInterpolation();c!==a.DefaultInterpolation&&(b.interpolation=c)}b.type=a.ValueTypeName;return b}});Object.assign(oa.prototype,{constructor:oa,TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new Fd(this.times,
16329 this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new bd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new Ed(this.times,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+
16330 " 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.KeyframeTrack:",b);return this}this.createInterpolant=b;return this},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/
16331 this.times.length},shift:function(a){if(0!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]+=a;return this},scale:function(a){if(1!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]*=a;return this},trim:function(a,b){for(var c=this.times,d=c.length,e=0,f=d-1;e!==d&&c[e]<a;)++e;for(;-1!==f&&c[f]>b;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,1),e=f-1),a=this.getValueSize(),this.times=ia.arraySlice(c,e,f),this.values=ia.arraySlice(this.values,e*a,f*a);return this},validate:function(){var a=
16332 !0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),a=!1);var c=this.times;b=this.values;var d=c.length;0===d&&(console.error("THREE.KeyframeTrack: Track is empty.",this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("THREE.KeyframeTrack: Out of order keys.",this,f,g,e);a=!1;break}e=
16333 g}if(void 0!==b&&ia.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,f,d);a=!1;break}return a},optimize:function(){for(var a=this.times,b=this.values,c=this.getValueSize(),d=2302===this.getInterpolation(),e=1,f=a.length-1,g=1;g<f;++g){var h=!1,k=a[g];if(k!==a[g+1]&&(1!==g||k!==k[0]))if(d)h=!0;else{var m=g*c,l=m-c,n=m+c;for(k=0;k!==c;++k){var p=b[m+k];if(p!==b[l+k]||p!==b[n+k]){h=!0;break}}}if(h){if(g!==e)for(a[e]=
16334 a[g],h=g*c,m=e*c,k=0;k!==c;++k)b[m+k]=b[h+k];++e}}if(0<f){a[e]=a[f];h=f*c;m=e*c;for(k=0;k!==c;++k)b[m+k]=b[h+k];++e}e!==a.length&&(this.times=ia.arraySlice(a,0,e),this.values=ia.arraySlice(b,0,e*c));return this}});Gd.prototype=Object.assign(Object.create(oa.prototype),{constructor:Gd,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Hd.prototype=Object.assign(Object.create(oa.prototype),{constructor:Hd,
16335 ValueTypeName:"color"});ec.prototype=Object.assign(Object.create(oa.prototype),{constructor:ec,ValueTypeName:"number"});Id.prototype=Object.assign(Object.create(wa.prototype),{constructor:Id,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)fa.slerpFlat(e,0,f,a-g,f,a,b);return e}});cd.prototype=Object.assign(Object.create(oa.prototype),{constructor:cd,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new Id(this.times,
16336 this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});Jd.prototype=Object.assign(Object.create(oa.prototype),{constructor:Jd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});fc.prototype=Object.assign(Object.create(oa.prototype),{constructor:fc,ValueTypeName:"vector"});Object.assign(Ca,{parse:function(a){for(var b=[],c=a.tracks,d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(Sg(c[e]).scale(d));
16337 return new Ca(a.name,a.duration,b)},toJSON:function(a){var b=[],c=a.tracks;a={name:a.name,duration:a.duration,tracks:b,uuid:a.uuid};for(var d=0,e=c.length;d!==e;++d)b.push(oa.toJSON(c[d]));return a},CreateFromMorphTargetSequence:function(a,b,c,d){for(var e=b.length,f=[],g=0;g<e;g++){var h=[],k=[];h.push((g+e-1)%e,g,(g+1)%e);k.push(0,1,0);var m=ia.getKeyframeOrder(h);h=ia.sortedArray(h,1,m);k=ia.sortedArray(k,1,m);d||0!==h[0]||(h.push(e),k.push(k[0]));f.push((new ec(".morphTargetInfluences["+b[g].name+
16338 "]",h,k)).scale(1/c))}return new Ca(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,b,c){for(var d={},e=/^([\w-]*?)([\d]+)$/,f=0,g=a.length;f<g;f++){var h=a[f],k=h.name.match(e);if(k&&1<k.length){var m=k[1];(k=d[m])||(d[m]=k=[]);k.push(h)}}a=[];for(m in d)a.push(Ca.CreateFromMorphTargetSequence(m,d[m],b,c));return a},parseAnimation:function(a,
16339 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=[];ia.flattenJSON(c,f,g,d);0!==f.length&&e.push(new a(b,f,g))}},d=[],e=a.name||"default",f=a.length||-1,g=a.fps||30;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){f={};for(var m=0;m<k.length;m++)if(k[m].morphTargets)for(var l=0;l<k[m].morphTargets.length;l++)f[k[m].morphTargets[l]]=-1;for(var n in f){var p=
16340 [],u=[];for(l=0;l!==k[m].morphTargets.length;++l){var r=k[m];p.push(r.time);u.push(r.morphTarget===n?1:0)}d.push(new ec(".morphTargetInfluence["+n+"]",p,u))}f=f.length*(g||1)}else m=".bones["+b[h].name+"]",c(fc,m+".position",k,"pos",d),c(cd,m+".quaternion",k,"rot",d),c(fc,m+".scale",k,"scl",d)}return 0===d.length?null:new Ca(e,f,d)}});Object.assign(Ca.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=
16341 a;return this},trim:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].trim(0,this.duration);return this},validate:function(){for(var a=!0,b=0;b<this.tracks.length;b++)a=a&&this.tracks[b].validate();return a},optimize:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].optimize();return this}});Object.assign(Kd.prototype,{load:function(a,b,c,d){var e=this;(new Ga(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===
16342 c[a]&&console.warn("THREE.MaterialLoader: Undefined texture",a);return c[a]}var c=this.textures,d=new Vg[a.type];void 0!==a.uuid&&(d.uuid=a.uuid);void 0!==a.name&&(d.name=a.name);void 0!==a.color&&d.color.setHex(a.color);void 0!==a.roughness&&(d.roughness=a.roughness);void 0!==a.metalness&&(d.metalness=a.metalness);void 0!==a.emissive&&d.emissive.setHex(a.emissive);void 0!==a.specular&&d.specular.setHex(a.specular);void 0!==a.shininess&&(d.shininess=a.shininess);void 0!==a.clearCoat&&(d.clearCoat=
16343 a.clearCoat);void 0!==a.clearCoatRoughness&&(d.clearCoatRoughness=a.clearCoatRoughness);void 0!==a.uniforms&&(d.uniforms=a.uniforms);void 0!==a.vertexShader&&(d.vertexShader=a.vertexShader);void 0!==a.fragmentShader&&(d.fragmentShader=a.fragmentShader);void 0!==a.vertexColors&&(d.vertexColors=a.vertexColors);void 0!==a.fog&&(d.fog=a.fog);void 0!==a.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=
16344 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!==a.wireframeLinewidth&&(d.wireframeLinewidth=a.wireframeLinewidth);void 0!==a.wireframeLinecap&&(d.wireframeLinecap=a.wireframeLinecap);void 0!==a.wireframeLinejoin&&(d.wireframeLinejoin=
16345 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.polygonOffset&&(d.polygonOffset=a.polygonOffset);void 0!==a.polygonOffsetFactor&&(d.polygonOffsetFactor=a.polygonOffsetFactor);void 0!==a.polygonOffsetUnits&&(d.polygonOffsetUnits=a.polygonOffsetUnits);void 0!==a.skinning&&(d.skinning=a.skinning);void 0!==a.morphTargets&&
16346 (d.morphTargets=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);
16347 void 0!==a.normalMap&&(d.normalMap=b(a.normalMap));void 0!==a.normalMapType&&(d.normalMapType=a.normalMapType);if(void 0!==a.normalScale){var e=a.normalScale;!1===Array.isArray(e)&&(e=[e,e]);d.normalScale=(new z).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!==
16348 a.metalnessMap&&(d.metalnessMap=b(a.metalnessMap));void 0!==a.emissiveMap&&(d.emissiveMap=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!==
16349 a.aoMapIntensity&&(d.aoMapIntensity=a.aoMapIntensity);void 0!==a.gradientMap&&(d.gradientMap=b(a.gradientMap));return d}});Object.assign(ge.prototype,{load:function(a,b,c,d){var e=this;(new Ga(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},parse:function(a){var b=new C,c=a.data.index;void 0!==c&&(c=new Bf[c.type](c.array),b.setIndex(new Q(c,1)));var d=a.data.attributes;for(f in d){var e=d[f];c=new Bf[e.type](e.array);b.addAttribute(f,new Q(c,e.itemSize,e.normalized))}var f=a.data.groups||
16350 a.data.drawcalls||a.data.offsets;if(void 0!==f)for(c=0,d=f.length;c!==d;++c)e=f[c],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 Bf={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:"undefined"!==typeof Uint8ClampedArray?Uint8ClampedArray:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,
16351 Float64Array:Float64Array};gc.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;c<d;c+=2){var e=b[c+1];if(b[c].test(a))return e}return null}};Object.assign(gc.prototype,{crossOrigin:"anonymous",onLoadStart:function(){},onLoadProgress:function(){},onLoadComplete:function(){},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,
16352 AdditiveBlending:2,SubtractiveBlending:3,MultiplyBlending:4,CustomBlending:5},b=new G,c=new vd,d=new Kd;return function(e,f,g){function h(a,b,d,e,h){a=f+a;var m=gc.Handlers.get(a);null!==m?a=m.load(a):(c.setCrossOrigin(g),a=c.load(a));void 0!==b&&(a.repeat.fromArray(b),1!==b[0]&&(a.wrapS=1E3),1!==b[1]&&(a.wrapT=1E3));void 0!==d&&a.offset.fromArray(d);void 0!==e&&("repeat"===e[0]&&(a.wrapS=1E3),"mirror"===e[0]&&(a.wrapS=1002),"repeat"===e[1]&&(a.wrapT=1E3),"mirror"===e[1]&&(a.wrapT=1002));void 0!==
16353 h&&(a.anisotropy=h);b=H.generateUUID();k[b]=a;return b}var k={},m={uuid:H.generateUUID(),type:"MeshLambertMaterial"},l;for(l in e){var n=e[l];switch(l){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":m.name=n;break;case "blending":m.blending=a[n];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",l,"is no longer supported.");break;case "colorDiffuse":m.color=b.fromArray(n).getHex();break;case "colorSpecular":m.specular=
16354 b.fromArray(n).getHex();break;case "colorEmissive":m.emissive=b.fromArray(n).getHex();break;case "specularCoef":m.shininess=n;break;case "shading":"basic"===n.toLowerCase()&&(m.type="MeshBasicMaterial");"phong"===n.toLowerCase()&&(m.type="MeshPhongMaterial");"standard"===n.toLowerCase()&&(m.type="MeshStandardMaterial");break;case "mapDiffuse":m.map=h(n,e.mapDiffuseRepeat,e.mapDiffuseOffset,e.mapDiffuseWrap,e.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;
16355 case "mapEmissive":m.emissiveMap=h(n,e.mapEmissiveRepeat,e.mapEmissiveOffset,e.mapEmissiveWrap,e.mapEmissiveAnisotropy);break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":m.lightMap=h(n,e.mapLightRepeat,e.mapLightOffset,e.mapLightWrap,e.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;case "mapAO":m.aoMap=h(n,e.mapAORepeat,e.mapAOOffset,e.mapAOWrap,
16356 e.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;case "mapBump":m.bumpMap=h(n,e.mapBumpRepeat,e.mapBumpOffset,e.mapBumpWrap,e.mapBumpAnisotropy);break;case "mapBumpScale":m.bumpScale=n;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":m.normalMap=h(n,e.mapNormalRepeat,e.mapNormalOffset,e.mapNormalWrap,e.mapNormalAnisotropy);break;case "mapNormalFactor":m.normalScale=n;break;
16357 case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":m.specularMap=h(n,e.mapSpecularRepeat,e.mapSpecularOffset,e.mapSpecularWrap,e.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":m.metalnessMap=h(n,e.mapMetalnessRepeat,e.mapMetalnessOffset,e.mapMetalnessWrap,e.mapMetalnessAnisotropy);break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;
16358 case "mapRoughness":m.roughnessMap=h(n,e.mapRoughnessRepeat,e.mapRoughnessOffset,e.mapRoughnessWrap,e.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":m.alphaMap=h(n,e.mapAlphaRepeat,e.mapAlphaOffset,e.mapAlphaWrap,e.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;case "flipSided":m.side=1;break;case "doubleSided":m.side=
16359 2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");m.opacity=n;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":m[l]=n;break;case "vertexColors":!0===n&&(m.vertexColors=2);"face"===n&&(m.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",l,n)}}"MeshBasicMaterial"===m.type&&delete m.emissive;"MeshPhongMaterial"!==
16360 m.type&&delete m.specular;1>m.opacity&&(m.transparent=!0);d.setTextures(k);return d.parse(m)}}()});var De={decodeText:function(a){if("undefined"!==typeof TextDecoder)return(new TextDecoder).decode(a);for(var b="",c=0,d=a.length;c<d;c++)b+=String.fromCharCode(a[c]);return decodeURIComponent(escape(b))},extractUrlBase:function(a){var b=a.lastIndexOf("/");return-1===b?"./":a.substr(0,b+1)}};Object.assign(he.prototype,{crossOrigin:"anonymous",load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===
16361 typeof this.texturePath?this.texturePath:De.extractUrlBase(a),g=new Ga(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&&"object"===d.toLowerCase())){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.ObjectLoader instead.");return}c=e.parse(c,f);b(c.geometry,c.materials)},c,d)},setCrossOrigin:function(a){this.crossOrigin=a;return this},setTexturePath:function(a){this.texturePath=a;return this},
16362 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 R,d=a,e,f,g,h=d.faces;var k=d.vertices;var m=d.normals,l=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 u=0;for(g=k.length;u<g;)e=new p,e.x=k[u++]*n,e.y=k[u++]*n,e.z=k[u++]*n,c.vertices.push(e);u=0;for(g=h.length;u<g;){k=h[u++];var r=k&1;var v=k&2;e=k&8;var y=k&16;var x=k&32;n=k&64;k&=128;if(r){r=
16363 new Ta;r.a=h[u];r.b=h[u+1];r.c=h[u+3];var w=new Ta;w.a=h[u+1];w.b=h[u+2];w.c=h[u+3];u+=4;v&&(v=h[u++],r.materialIndex=v,w.materialIndex=v);v=c.faces.length;if(e)for(e=0;e<t;e++){var B=d.uvs[e];c.faceVertexUvs[e][v]=[];c.faceVertexUvs[e][v+1]=[];for(f=0;4>f;f++){var E=h[u++];var A=B[2*E];E=B[2*E+1];A=new z(A,E);2!==f&&c.faceVertexUvs[e][v].push(A);0!==f&&c.faceVertexUvs[e][v+1].push(A)}}y&&(y=3*h[u++],r.normal.set(m[y++],m[y++],m[y]),w.normal.copy(r.normal));if(x)for(e=0;4>e;e++)y=3*h[u++],x=new p(m[y++],
16364 m[y++],m[y]),2!==e&&r.vertexNormals.push(x),0!==e&&w.vertexNormals.push(x);n&&(n=h[u++],n=l[n],r.color.setHex(n),w.color.setHex(n));if(k)for(e=0;4>e;e++)n=h[u++],n=l[n],2!==e&&r.vertexColors.push(new G(n)),0!==e&&w.vertexColors.push(new G(n));c.faces.push(r);c.faces.push(w)}else{r=new Ta;r.a=h[u++];r.b=h[u++];r.c=h[u++];v&&(v=h[u++],r.materialIndex=v);v=c.faces.length;if(e)for(e=0;e<t;e++)for(B=d.uvs[e],c.faceVertexUvs[e][v]=[],f=0;3>f;f++)E=h[u++],A=B[2*E],E=B[2*E+1],A=new z(A,E),c.faceVertexUvs[e][v].push(A);
16365 y&&(y=3*h[u++],r.normal.set(m[y++],m[y++],m[y]));if(x)for(e=0;3>e;e++)y=3*h[u++],x=new p(m[y++],m[y++],m[y]),r.vertexNormals.push(x);n&&(n=h[u++],r.color.setHex(l[n]));if(k)for(e=0;3>e;e++)n=h[u++],r.vertexColors.push(new G(l[n]));c.faces.push(r)}}d=a;u=void 0!==d.influencesPerVertex?d.influencesPerVertex:2;if(d.skinWeights)for(g=0,h=d.skinWeights.length;g<h;g+=u)c.skinWeights.push(new V(d.skinWeights[g],1<u?d.skinWeights[g+1]:0,2<u?d.skinWeights[g+2]:0,3<u?d.skinWeights[g+3]:0));if(d.skinIndices)for(g=
16366 0,h=d.skinIndices.length;g<h;g+=u)c.skinIndices.push(new V(d.skinIndices[g],1<u?d.skinIndices[g+1]:0,2<u?d.skinIndices[g+2]:0,3<u?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 ("+c.skinWeights.length+") should match.");g=a;h=g.scale;if(void 0!==g.morphTargets)for(d=
16367 0,u=g.morphTargets.length;d<u;d++)for(c.morphTargets[d]={},c.morphTargets[d].name=g.morphTargets[d].name,c.morphTargets[d].vertices=[],m=c.morphTargets[d].vertices,l=g.morphTargets[d].vertices,t=0,k=l.length;t<k;t+=3)n=new p,n.x=l[t]*h,n.y=l[t+1]*h,n.z=l[t+2]*h,m.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.'),h=c.faces,g=g.morphColors[0].colors,d=0,u=h.length;d<u;d++)h[d].color.fromArray(g,
16368 3*d);g=a;d=[];u=[];void 0!==g.animation&&u.push(g.animation);void 0!==g.animations&&(g.animations.length?u=u.concat(g.animations):u.push(g.animations));for(g=0;g<u.length;g++)(h=Ca.parseAnimation(u[g],c.bones))&&d.push(h);c.morphTargets&&(u=Ca.CreateClipsFromMorphTargetSequences(c.morphTargets,10),d=d.concat(u));0<d.length&&(c.animations=d);c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===a.materials.length)return{geometry:c};a=gc.prototype.initMaterials(a.materials,b,
16369 this.crossOrigin);return{geometry:c,materials:a}}}()});Object.assign(mf.prototype,{crossOrigin:"anonymous",load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new Ga(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()?console.error("THREE.ObjectLoader: Can't load "+
16370 a+". Use THREE.JSONLoader instead."):e.parse(f,b)},c,d)},setTexturePath:function(a){this.texturePath=a;return this},setCrossOrigin:function(a){this.crossOrigin=a;return this},parse:function(a,b){var c=this.parseShape(a.shapes);c=this.parseGeometries(a.geometries,c);var d=this.parseImages(a.images,function(){void 0!==b&&b(e)});d=this.parseTextures(a.textures,d);d=this.parseMaterials(a.materials,d);var e=this.parseObject(a.object,c,d);a.animations&&(e.animations=this.parseAnimations(a.animations));
16371 void 0!==a.images&&0!==a.images.length||void 0===b||b(e);return e},parseShape:function(a){var b={};if(void 0!==a)for(var c=0,d=a.length;c<d;c++){var e=(new db).fromJSON(a[c]);b[e.uuid]=e}return b},parseGeometries:function(a,b){var c={};if(void 0!==a)for(var d=new he,e=new ge,f=0,g=a.length;f<g;f++){var h=a[f];switch(h.type){case "PlaneGeometry":case "PlaneBufferGeometry":var k=new xa[h.type](h.width,h.height,h.widthSegments,h.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":k=
16372 new xa[h.type](h.width,h.height,h.depth,h.widthSegments,h.heightSegments,h.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":k=new xa[h.type](h.radius,h.segments,h.thetaStart,h.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":k=new xa[h.type](h.radiusTop,h.radiusBottom,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":k=new xa[h.type](h.radius,h.height,h.radialSegments,
16373 h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "SphereGeometry":case "SphereBufferGeometry":k=new xa[h.type](h.radius,h.widthSegments,h.heightSegments,h.phiStart,h.phiLength,h.thetaStart,h.thetaLength);break;case "DodecahedronGeometry":case "DodecahedronBufferGeometry":case "IcosahedronGeometry":case "IcosahedronBufferGeometry":case "OctahedronGeometry":case "OctahedronBufferGeometry":case "TetrahedronGeometry":case "TetrahedronBufferGeometry":k=new xa[h.type](h.radius,h.detail);
16374 break;case "RingGeometry":case "RingBufferGeometry":k=new xa[h.type](h.innerRadius,h.outerRadius,h.thetaSegments,h.phiSegments,h.thetaStart,h.thetaLength);break;case "TorusGeometry":case "TorusBufferGeometry":k=new xa[h.type](h.radius,h.tube,h.radialSegments,h.tubularSegments,h.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":k=new xa[h.type](h.radius,h.tube,h.tubularSegments,h.radialSegments,h.p,h.q);break;case "LatheGeometry":case "LatheBufferGeometry":k=new xa[h.type](h.points,
16375 h.segments,h.phiStart,h.phiLength);break;case "PolyhedronGeometry":case "PolyhedronBufferGeometry":k=new xa[h.type](h.vertices,h.indices,h.radius,h.details);break;case "ShapeGeometry":case "ShapeBufferGeometry":k=[];for(var m=0,l=h.shapes.length;m<l;m++){var n=b[h.shapes[m]];k.push(n)}k=new xa[h.type](k,h.curveSegments);break;case "ExtrudeGeometry":case "ExtrudeBufferGeometry":k=[];m=0;for(l=h.shapes.length;m<l;m++)n=b[h.shapes[m]],k.push(n);m=h.options.extrudePath;void 0!==m&&(h.options.extrudePath=
16376 (new Af[m.type]).fromJSON(m));k=new xa[h.type](k,h.options);break;case "BufferGeometry":k=e.parse(h);break;case "Geometry":k=d.parse(h,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+h.type+'"');continue}k.uuid=h.uuid;void 0!==h.name&&(k.name=h.name);!0===k.isBufferGeometry&&void 0!==h.userData&&(k.userData=h.userData);c[h.uuid]=k}return c},parseMaterials:function(a,b){var c={};if(void 0!==a){var d=new Kd;d.setTextures(b);b=0;for(var e=a.length;b<
16377 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]=g}else c[f.uuid]=d.parse(f)}}return c},parseAnimations:function(a){for(var b=[],c=0;c<a.length;c++){var d=a[c],e=Ca.parse(d);void 0!==d.uuid&&(e.uuid=d.uuid);b.push(e)}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={};
16378 if(void 0!==a&&0<a.length){b=new ce(b);var f=new Zc(b);f.setCrossOrigin(this.crossOrigin);b=0;for(var g=a.length;b<g;b++){var h=a[b],k=h.url;if(Array.isArray(k)){e[h.uuid]=[];for(var m=0,l=k.length;m<l;m++){var n=k[m];n=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(n)?n:d.texturePath+n;e[h.uuid].push(c(n))}}else n=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(h.url)?h.url:d.texturePath+h.url,e[h.uuid]=c(n)}}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.",
16379 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=Array.isArray(b[g.image])?new Ua(b[g.image]):new T(b[g.image]);h.needsUpdate=!0;h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);void 0!==g.mapping&&(h.mapping=c(g.mapping,Wg));void 0!==g.offset&&h.offset.fromArray(g.offset);void 0!==g.repeat&&h.repeat.fromArray(g.repeat);
16380 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],Cf),h.wrapT=c(g.wrap[1],Cf));void 0!==g.format&&(h.format=g.format);void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,Df));void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,Df));void 0!==g.anisotropy&&(h.anisotropy=g.anisotropy);void 0!==g.flipY&&(h.flipY=g.flipY);d[g.uuid]=h}return d},parseObject:function(a,b,c){function d(a){void 0===b[a]&&console.warn("THREE.ObjectLoader: Undefined geometry",
16381 a);return b[a]}function e(a){if(void 0!==a){if(Array.isArray(a)){for(var b=[],d=0,e=a.length;d<e;d++){var f=a[d];void 0===c[f]&&console.warn("THREE.ObjectLoader: Undefined material",f);b.push(c[f])}return b}void 0===c[a]&&console.warn("THREE.ObjectLoader: Undefined material",a);return c[a]}}switch(a.type){case "Scene":var f=new qd;void 0!==a.background&&Number.isInteger(a.background)&&(f.background=new G(a.background));void 0!==a.fog&&("Fog"===a.fog.type?f.fog=new Mb(a.fog.color,a.fog.near,a.fog.far):
16382 "FogExp2"===a.fog.type&&(f.fog=new Lb(a.fog.color,a.fog.density)));break;case "PerspectiveCamera":f=new Z(a.fov,a.aspect,a.near,a.far);void 0!==a.focus&&(f.focus=a.focus);void 0!==a.zoom&&(f.zoom=a.zoom);void 0!==a.filmGauge&&(f.filmGauge=a.filmGauge);void 0!==a.filmOffset&&(f.filmOffset=a.filmOffset);void 0!==a.view&&(f.view=Object.assign({},a.view));break;case "OrthographicCamera":f=new Hb(a.left,a.right,a.top,a.bottom,a.near,a.far);void 0!==a.zoom&&(f.zoom=a.zoom);void 0!==a.view&&(f.view=Object.assign({},
16383 a.view));break;case "AmbientLight":f=new Cd(a.color,a.intensity);break;case "DirectionalLight":f=new Bd(a.color,a.intensity);break;case "PointLight":f=new zd(a.color,a.intensity,a.distance,a.decay);break;case "RectAreaLight":f=new Dd(a.color,a.intensity,a.width,a.height);break;case "SpotLight":f=new yd(a.color,a.intensity,a.distance,a.angle,a.penumbra,a.decay);break;case "HemisphereLight":f=new wd(a.color,a.groundColor,a.intensity);break;case "SkinnedMesh":console.warn("THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.");
16384 case "Mesh":f=d(a.geometry);var g=e(a.material);f=f.bones&&0<f.bones.length?new sd(f,g):new la(f,g);break;case "LOD":f=new Bc;break;case "Line":f=new sa(d(a.geometry),e(a.material),a.mode);break;case "LineLoop":f=new td(d(a.geometry),e(a.material));break;case "LineSegments":f=new W(d(a.geometry),e(a.material));break;case "PointCloud":case "Points":f=new Ob(d(a.geometry),e(a.material));break;case "Sprite":f=new Ac(e(a.material));break;case "Group":f=new Kb;break;default:f=new D}f.uuid=a.uuid;void 0!==
16385 a.name&&(f.name=a.name);void 0!==a.matrix?(f.matrix.fromArray(a.matrix),void 0!==a.matrixAutoUpdate&&(f.matrixAutoUpdate=a.matrixAutoUpdate),f.matrixAutoUpdate&&f.matrix.decompose(f.position,f.quaternion,f.scale)):(void 0!==a.position&&f.position.fromArray(a.position),void 0!==a.rotation&&f.rotation.fromArray(a.rotation),void 0!==a.quaternion&&f.quaternion.fromArray(a.quaternion),void 0!==a.scale&&f.scale.fromArray(a.scale));void 0!==a.castShadow&&(f.castShadow=a.castShadow);void 0!==a.receiveShadow&&
16386 (f.receiveShadow=a.receiveShadow);a.shadow&&(void 0!==a.shadow.bias&&(f.shadow.bias=a.shadow.bias),void 0!==a.shadow.radius&&(f.shadow.radius=a.shadow.radius),void 0!==a.shadow.mapSize&&f.shadow.mapSize.fromArray(a.shadow.mapSize),void 0!==a.shadow.camera&&(f.shadow.camera=this.parseObject(a.shadow.camera)));void 0!==a.visible&&(f.visible=a.visible);void 0!==a.frustumCulled&&(f.frustumCulled=a.frustumCulled);void 0!==a.renderOrder&&(f.renderOrder=a.renderOrder);void 0!==a.userData&&(f.userData=a.userData);
16387 void 0!==a.layers&&(f.layers.mask=a.layers);if(void 0!==a.children){g=a.children;for(var h=0;h<g.length;h++)f.add(this.parseObject(g[h],b,c))}if("LOD"===a.type)for(a=a.levels,g=0;g<a.length;g++){h=a[g];var k=f.getObjectByProperty("uuid",h.object);void 0!==k&&f.addLevel(k,h.distance)}return f}});var Wg={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,
16388 CubeUVRefractionMapping:307},Cf={RepeatWrapping:1E3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},Df={NearestFilter:1003,NearestMipMapNearestFilter:1004,NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008};ie.prototype={constructor:ie,setOptions:function(a){this.options=a;return this},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=Fb.get(a);if(void 0!==f)return e.manager.itemStart(a),
16389 setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;fetch(a).then(function(a){return a.blob()}).then(function(a){return createImageBitmap(a,e.options)}).then(function(c){Fb.add(a,c);b&&b(c);e.manager.itemEnd(a)}).catch(function(b){d&&d(b);e.manager.itemEnd(a);e.manager.itemError(a)})},setCrossOrigin:function(){return this},setPath:function(a){this.path=a;return this}};Object.assign(je.prototype,{moveTo:function(a,b){this.currentPath=new La;this.subPaths.push(this.currentPath);this.currentPath.moveTo(a,
16390 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,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 db;f.curves=e.curves;b.push(f)}return b}function d(a,b){for(var c=b.length,d=!1,e=c-1,f=0;f<c;e=f++){var g=b[e],h=b[f],k=h.x-g.x,m=h.y-g.y;if(Math.abs(m)>
16391 Number.EPSILON){if(0>m&&(g=b[f],k=-k,h=b[e],m=-m),!(a.y<g.y||a.y>h.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=m*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=Va.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 db;h.curves=g.curves;b.push(h);return b}var k=!e(f[0].getPoints());k=a?!k:k;h=[];var m=[],l=[],n=0;m[n]=void 0;l[n]=[];for(var p=
16392 0,u=f.length;p<u;p++){g=f[p];var r=g.getPoints();var v=e(r);(v=a?!v:v)?(!k&&m[n]&&n++,m[n]={s:new db,p:r},m[n].s.curves=g.curves,k&&n++,l[n]=[]):l[n].push({h:g,p:r[0]})}if(!m[0])return c(f);if(1<m.length){p=!1;a=[];e=0;for(f=m.length;e<f;e++)h[e]=[];e=0;for(f=m.length;e<f;e++)for(g=l[e],v=0;v<g.length;v++){k=g[v];n=!0;for(r=0;r<m.length;r++)d(k.p,m[r].p)&&(e!==r&&a.push({froms:e,tos:r,hole:v}),n?(n=!1,h[r].push(k)):p=!0);n&&h[e].push(k)}0<a.length&&(p||(l=h))}p=0;for(e=m.length;p<e;p++)for(h=m[p].s,
16393 b.push(h),a=l[p],f=0,g=a.length;f<g;f++)h.holes.push(a[f].h);return b}});Object.assign(ke.prototype,{isFont:!0,generateShapes:function(a,b){void 0===b&&(b=100);var c=[],d=b;b=this.data;var e=Array.from?Array.from(a):String(a).split("");d/=b.resolution;var f=(b.boundingBox.yMax-b.boundingBox.yMin+b.underlineThickness)*d;a=[];for(var g=0,h=0,k=0;k<e.length;k++){var m=e[k];if("\n"===m)g=0,h-=f;else{var l=d;var n=g,p=h;if(m=b.glyphs[m]||b.glyphs["?"]){var u=new je;if(m.o)for(var r=m._cachedOutline||(m._cachedOutline=
16394 m.o.split(" ")),v=0,y=r.length;v<y;)switch(r[v++]){case "m":var x=r[v++]*l+n;var w=r[v++]*l+p;u.moveTo(x,w);break;case "l":x=r[v++]*l+n;w=r[v++]*l+p;u.lineTo(x,w);break;case "q":var z=r[v++]*l+n;var A=r[v++]*l+p;var C=r[v++]*l+n;var D=r[v++]*l+p;u.quadraticCurveTo(C,D,z,A);break;case "b":z=r[v++]*l+n,A=r[v++]*l+p,C=r[v++]*l+n,D=r[v++]*l+p,x=r[v++]*l+n,w=r[v++]*l+p,u.bezierCurveTo(C,D,x,w,z,A)}l={offsetX:m.ha*l,path:u}}else l=void 0;g+=l.offsetX;a.push(l.path)}}b=0;for(e=a.length;b<e;b++)Array.prototype.push.apply(c,
16395 a[b].toShapes());return c}});Object.assign(nf.prototype,{load:function(a,b,c,d){var e=this,f=new Ga(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 ke(a)},setPath:function(a){this.path=a;return this}});var Pd,ne={getContext:function(){void 0===Pd&&(Pd=new (window.AudioContext||
16396 window.webkitAudioContext));return Pd},setContext:function(a){Pd=a}};Object.assign(le.prototype,{load:function(a,b,c,d){var e=new Ga(this.manager);e.setResponseType("arraybuffer");e.load(a,function(a){a=a.slice(0);ne.getContext().decodeAudioData(a,function(a){b(a)})},c,d)}});Object.assign(of.prototype,{update:function(){var a,b,c,d,e,f,g,h,k=new I,l=new I;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=
16397 m.focus;c=m.fov;d=m.aspect*this.aspect;e=m.near;f=m.far;g=m.zoom;var n=m.projectionMatrix.clone();h=this.eyeSep/2;var p=h*e/b,q=e*Math.tan(H.DEG2RAD*c*.5)/g;l.elements[12]=-h;k.elements[12]=h;var r=-q*d+p;var v=q*d+p;n.elements[0]=2*e/(v-r);n.elements[8]=(v+r)/(v-r);this.cameraL.projectionMatrix.copy(n);r=-q*d-p;v=q*d-p;n.elements[0]=2*e/(v-r);n.elements[8]=(v+r)/(v-r);this.cameraR.projectionMatrix.copy(n)}this.cameraL.matrixWorld.copy(m.matrixWorld).multiply(l);this.cameraR.matrixWorld.copy(m.matrixWorld).multiply(k)}}()});
16398 dd.prototype=Object.create(D.prototype);dd.prototype.constructor=dd;me.prototype=Object.assign(Object.create(D.prototype),{constructor:me,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);return this},getFilter:function(){return this.filter},setFilter:function(a){null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):
16399 this.gain.disconnect(this.context.destination);this.filter=a;this.gain.connect(this.filter);this.filter.connect(this.context.destination);return this},getMasterVolume:function(){return this.gain.gain.value},setMasterVolume:function(a){this.gain.gain.setTargetAtTime(a,this.context.currentTime,.01);return this},updateMatrixWorld:function(){var a=new p,b=new fa,c=new p,d=new p;return function(e){D.prototype.updateMatrixWorld.call(this,e);e=this.context.listener;var f=this.up;this.matrixWorld.decompose(a,
16400 b,c);d.set(0,0,-1).applyQuaternion(b);e.positionX?(e.positionX.setValueAtTime(a.x,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,
16401 this.context.currentTime)):(e.setPosition(a.x,a.y,a.z),e.setOrientation(d.x,d.y,d.z,f.x,f.y,f.z))}}()});hc.prototype=Object.assign(Object.create(D.prototype),{constructor:hc,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setMediaElementSource:function(a){this.hasPlaybackControl=!1;this.sourceType="mediaNode";this.source=this.context.createMediaElementSource(a);this.connect();return this},
16402 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.");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;
16403 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.source.onended=null,this.offset+=(this.context.currentTime-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(),
16404 this.source.onended=null,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());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]);
16405 this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this},getFilters:function(){return this.filters},setFilters:function(a){a||(a=[]);!0===this.isPlaying?(this.disconnect(),this.filters=a,this.connect()):this.filters=a;return this},getFilter:function(){return this.getFilters()[0]},setFilter:function(a){return this.setFilters(a?[a]:[])},setPlaybackRate:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
16406 else return this.playbackRate=a,!0===this.isPlaying&&this.source.playbackRate.setValueAtTime(this.playbackRate,this.context.currentTime),this},getPlaybackRate:function(){return this.playbackRate},onEnded:function(){this.isPlaying=!1},getLoop:function(){return!1===this.hasPlaybackControl?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop},setLoop:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.loop=
16407 a,!0===this.isPlaying&&(this.source.loop=this.loop),this},getVolume:function(){return this.gain.gain.value},setVolume:function(a){this.gain.gain.setTargetAtTime(a,this.context.currentTime,.01);return this}});oe.prototype=Object.assign(Object.create(hc.prototype),{constructor:oe,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=a;return this},getRolloffFactor:function(){return this.panner.rolloffFactor},
16408 setRolloffFactor:function(a){this.panner.rolloffFactor=a;return this},getDistanceModel:function(){return this.panner.distanceModel},setDistanceModel:function(a){this.panner.distanceModel=a;return this},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(a){this.panner.maxDistance=a;return this},setDirectionalCone:function(a,b,c){this.panner.coneInnerAngle=a;this.panner.coneOuterAngle=b;this.panner.coneOuterGain=c;return this},updateMatrixWorld:function(){var a=new p,
16409 b=new fa,c=new p,d=new p;return function(e){D.prototype.updateMatrixWorld.call(this,e);e=this.panner;this.matrixWorld.decompose(a,b,c);d.set(0,0,1).applyQuaternion(b);e.setPosition(a.x,a.y,a.z);e.setOrientation(d.x,d.y,d.z)}}()});Object.assign(pe.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(qe.prototype,{accumulate:function(a,
16410 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=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);d=b;for(var 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,
16411 c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d){fa.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(pf.prototype,{getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];void 0!==c&&c.getValue(a,
16412 b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].unbind()}});Object.assign(pa,{Composite:pf,create:function(a,b,c){return a&&a.isAnimationObjectGroup?new pa.Composite(a,b,c):new pa(a,b,c)},sanitizeNodeName:function(){var a=
16413 /[\[\]\.:\/]/g;return function(b){return b.replace(/\s/g,"_").replace(a,"")}}(),parseTrackName:function(){var a="[^"+"\\[\\]\\.:\\/".replace("\\.","")+"]",b=/((?:WC+[\/:])*)/.source.replace("WC","[^\\[\\]\\.:\\/]");a=/(WCOD+)?/.source.replace("WCOD",a);var c=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC","[^\\[\\]\\.:\\/]"),d=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC","[^\\[\\]\\.:\\/]"),e=new RegExp("^"+b+a+c+d+"$"),f=["material","materials","bones"];return function(a){var b=e.exec(a);if(!b)throw Error("PropertyBinding: Cannot parse trackName: "+
16414 a);b={nodeName:b[2],objectName:b[3],objectIndex:b[4],propertyName:b[5],propertyIndex:b[6]};var c=b.nodeName&&b.nodeName.lastIndexOf(".");if(void 0!==c&&-1!==c){var d=b.nodeName.substring(c+1);-1!==f.indexOf(d)&&(b.nodeName=b.nodeName.substring(0,c),b.objectName=d)}if(null===b.propertyName||0===b.propertyName.length)throw Error("PropertyBinding: can not parse propertyName from trackName: "+a);return b}}(),findNode:function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;
16415 if(a.skeleton){var c=a.skeleton.getBoneByName(b);if(void 0!==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(pa.prototype,{_getValue_unavailable:function(){},_setValue_unavailable:function(){},BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},GetterByBindingType:[function(a,
16416 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]=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=
16417 !0}],[function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.needsUpdate=!0},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.needsUpdate=!0},function(a,
16418 b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty.fromArray(a,b)},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.matrixWorldNeedsUpdate=!0}]],getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=this.node,b=this.parsedPath,c=b.objectName,
16419 d=b.propertyName,e=b.propertyIndex;a||(this.node=a=pa.findNode(this.rootNode,b.nodeName)||this.rootNode);this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(a){if(c){var f=b.objectIndex;switch(c){case "materials":if(!a.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!a.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",
16420 this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}a=a.skeleton.bones;for(c=0;c<a.length;c++)if(a[c].name===f){f=c;break}break;default:if(void 0===a[c]){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}a=a[c]}if(void 0!==f){if(void 0===a[f]){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",
16421 this,a);return}a=a[f]}}f=a[d];if(void 0===f)console.error("THREE.PropertyBinding: Trying to update property for track: "+b.nodeName+"."+d+" but it wasn't found.",a);else{b=this.Versioning.None;void 0!==a.needsUpdate?(b=this.Versioning.NeedsUpdate,this.targetObject=a):void 0!==a.matrixWorldNeedsUpdate&&(b=this.Versioning.MatrixWorldNeedsUpdate,this.targetObject=a);c=this.BindingType.Direct;if(void 0!==e){if("morphTargetInfluences"===d){if(!a.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",
16422 this);return}if(a.geometry.isBufferGeometry){if(!a.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}for(c=0;c<this.node.geometry.morphAttributes.position.length;c++)if(a.geometry.morphAttributes.position[c].name===e){e=c;break}}else{if(!a.geometry.morphTargets){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.",
16423 this);return}for(c=0;c<this.node.geometry.morphTargets.length;c++)if(a.geometry.morphTargets[c].name===e){e=c;break}}}c=this.BindingType.ArrayElement;this.resolvedProperty=f;this.propertyIndex=e}else void 0!==f.fromArray&&void 0!==f.toArray?(c=this.BindingType.HasFromToArray,this.resolvedProperty=f):Array.isArray(f)?(c=this.BindingType.EntireArray,this.resolvedProperty=f):this.propertyName=d;this.getValue=this.GetterByBindingType[c];this.setValue=this.SetterByBindingTypeAndVersioning[c][b]}}else console.error("THREE.PropertyBinding: Trying to update node for track: "+
16424 this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}});Object.assign(pa.prototype,{_getValue_unbound:pa.prototype.getValue,_setValue_unbound:pa.prototype.setValue});Object.assign(qf.prototype,{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=void 0,l=0,p=arguments.length;l!==
16425 p;++l){var n=arguments[l],t=n.uuid,u=d[t];if(void 0===u){u=b++;d[t]=u;a.push(n);t=0;for(var r=h;t!==r;++t)g[t].push(new pa(n,e[t],f[t]))}else if(u<c){k=a[u];var v=--c;r=a[v];d[r.uuid]=u;a[u]=r;d[t]=v;a[v]=n;t=0;for(r=h;t!==r;++t){var y=g[t],x=y[u];y[u]=y[v];void 0===x&&(x=new pa(n,e[t],f[t]));y[v]=x}}else a[u]!==k&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=
16426 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 p=b++,n=a[p];c[n.uuid]=l;a[l]=n;c[k]=p;a[p]=h;h=0;for(k=e;h!==k;++h){n=d[h];var t=n[l];n[l]=n[p];n[p]=t}}}this.nCachedObjects_=b},uncache:function(){for(var a=this._objects,b=a.length,c=this.nCachedObjects_,d=this._indicesByUUID,e=this._bindings,f=e.length,g=0,h=arguments.length;g!==h;++g){var k=
16427 arguments[g].uuid,l=d[k];if(void 0!==l)if(delete d[k],l<c){k=--c;var p=a[k],n=--b,t=a[n];d[p.uuid]=l;a[l]=p;d[t.uuid]=k;a[k]=t;a.pop();p=0;for(t=f;p!==t;++p){var u=e[p],r=u[n];u[l]=u[k];u[k]=r;u.pop()}}else for(n=--b,t=a[n],d[t.uuid]=l,a[l]=t,a.pop(),p=0,t=f;p!==t;++p)u=e[p],u[l]=u[n],u.pop()}this.nCachedObjects_=c},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_,
16428 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 pa(h[c],a,b);return l},unsubscribe_:function(a){var b=this._bindingsIndicesByPath,c=b[a];if(void 0!==c){var d=this._paths,e=this._parsedPaths,f=this._bindings,g=f.length-1,h=f[g];b[a[g]]=c;f[c]=h;f.pop();e[c]=e[g];e.pop();d[c]=d[g];d.pop()}}});Object.assign(rf.prototype,{play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},
16429 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)},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;
16430 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);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;
16431 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},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,
16432 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=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||
16433 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;e=this._propertyBindings;for(var 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){b=this.weight;var c=this._weightInterpolant;if(null!==c){var d=c.evaluate(a)[0];
16434 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){b=this.timeScale;var c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0];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,c=this._clip.duration,d=this.loop,e=this._loopCount,f=2202===d;if(0===a)return-1===
16435 e?b:f&&1===(e&1)?c-b:b;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{-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,f)):this._setEndings(0===this.repetitions,!0,f));if(b>=c||0>b){d=Math.floor(b/c);b-=c*d;e+=Math.abs(d);var g=this.repetitions-e;0>=g?(this.clampWhenFinished?this.paused=!0:
16436 this.enabled=!1,b=0<a?c:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:0<a?1:-1})):(1===g?(a=0>a,this._setEndings(a,!a,f)):this._setEndings(!1,!1,f),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:d}))}if(f&&1===(e&1))return this.time=b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:
16437 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}});re.prototype=Object.assign(Object.create(ya.prototype),{constructor:re,_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===
16438 k&&(k={},h[g]=k);for(h=0;h!==e;++h){var l=d[h],p=l.name,n=k[p];if(void 0===n){n=f[h];if(void 0!==n){null===n._cacheIndex&&(++n.referenceCount,this._addInactiveBinding(n,g,p));continue}n=new qe(pa.create(c,p,b&&b._propertyBindings[h].binding.parsedPath),l.ValueTypeName,l.getValueSize());++n.referenceCount;this._addInactiveBinding(n,g,p)}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,
16439 d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=
16440 [];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},
16441 _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);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;b=a._clip.uuid;
16442 c=this._actionsByClip;d=c[b];var 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;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,
16443 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]=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;var e=this._bindingsByRootAndName,
16444 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=--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++,
16445 c=a[b];void 0===c&&(c=new bd(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;b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1),clipAction:function(a,b){var c=b||this._root,d=c.uuid;c="string"===typeof a?Ca.findByName(c,a):a;a=null!==c?c.uuid:a;var e=
16446 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 rf(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?Ca.findByName(c,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,
16447 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;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,
16448 d=c[a];if(void 0!==d){d=d.knownActions;for(var e=0,f=d.length;e!==f;++e){var g=d[e];this._deactivateAction(g);var h=g._cacheIndex,k=b[b.length-1];g._cacheIndex=null;g._byClipCacheIndex=null;k._cacheIndex=h;b[h]=k;b.pop();this._removeInactiveBindingsForAction(g)}delete c[a]}},uncacheRoot:function(a){a=a.uuid;var b=this._actionsByClip;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=
16449 d[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){a=this.existingAction(a,b);null!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}});Ld.prototype.clone=function(){return new Ld(void 0===this.value.clone?this.value:this.value.clone())};se.prototype=Object.assign(Object.create(C.prototype),{constructor:se,isInstancedBufferGeometry:!0,copy:function(a){C.prototype.copy.call(this,a);this.maxInstancedCount=a.maxInstancedCount;return this},clone:function(){return(new this.constructor).copy(this)}});
16450 te.prototype=Object.assign(Object.create(ob.prototype),{constructor:te,isInstancedInterleavedBuffer:!0,copy:function(a){ob.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});ue.prototype=Object.assign(Object.create(Q.prototype),{constructor:ue,isInstancedBufferAttribute:!0,copy:function(a){Q.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});Object.assign(sf.prototype,{linePrecision:1,set:function(a,b){this.ray.set(a,b)},setFromCamera:function(a,
16451 b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):b&&b.isOrthographicCamera?(this.ray.origin.set(a.x,a.y,(b.near+b.far)/(b.near-b.far)).unproject(b),this.ray.direction.set(0,0,-1).transformDirection(b.matrixWorld)):console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b,c){c=c||[];ve(a,this,c,b);c.sort(tf);return c},intersectObjects:function(a,b,c){c=c||
16452 [];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++)ve(a[d],this,c,b);c.sort(tf);return c}});Object.assign(uf.prototype,{start:function(){this.oldTime=this.startTime=("undefined"===typeof performance?Date:performance).now();this.elapsedTime=0;this.running=!0},stop:function(){this.getElapsedTime();this.autoStart=this.running=!1},getElapsedTime:function(){this.getDelta();return this.elapsedTime},getDelta:function(){var a=
16453 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(vf.prototype,{set:function(a,b,c){this.radius=a;this.phi=b;this.theta=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.phi=a.phi;this.theta=a.theta;return this},makeSafe:function(){this.phi=Math.max(1E-6,Math.min(Math.PI-
16454 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(H.clamp(a.y/this.radius,-1,1)));return this}});Object.assign(wf.prototype,{set:function(a,b,c){this.radius=a;this.theta=b;this.y=c;return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.radius=a.radius;this.theta=a.theta;this.y=a.y;return this},setFromVector3:function(a){this.radius=Math.sqrt(a.x*
16455 a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}});Object.assign(we.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 z;return function(b,c){c=a.copy(c).multiplyScalar(.5);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);
16456 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){void 0===a&&(console.warn("THREE.Box2: .getCenter() target is now required"),a=new z);return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){void 0===a&&(console.warn("THREE.Box2: .getSize() target is now required"),a=new z);return this.isEmpty()?
16457 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<=this.max.y},getParameter:function(a,
16458 b){void 0===b&&(console.warn("THREE.Box2: .getParameter() target is now required"),b=new z);return b.set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.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){void 0===b&&(console.warn("THREE.Box2: .clampPoint() target is now required"),b=new z);return b.copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new z;
16459 return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(xe.prototype,{set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},
16460 copy:function(a){this.start.copy(a.start);this.end.copy(a.end);return this},getCenter:function(a){void 0===a&&(console.warn("THREE.Line3: .getCenter() target is now required"),a=new p);return a.addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){void 0===a&&(console.warn("THREE.Line3: .delta() target is now required"),a=new p);return a.subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},
16461 at:function(a,b){void 0===b&&(console.warn("THREE.Line3: .at() target is now required"),b=new p);return this.delta(b).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new p,b=new p;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);c=b.dot(b);c=b.dot(a)/c;d&&(c=H.clamp(c,0,1));return c}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);void 0===c&&(console.warn("THREE.Line3: .closestPointToPoint() target is now required"),
16462 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)}});ed.prototype=Object.create(D.prototype);ed.prototype.constructor=ed;ed.prototype.isImmediateRenderObject=!0;fd.prototype=Object.create(W.prototype);fd.prototype.constructor=fd;fd.prototype.update=function(){var a=new p,b=new p,c=new ra;return function(){var d=["a","b",
16463 "c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g&&g.isGeometry)for(var h=g.vertices,k=g.faces,l=g=0,p=k.length;l<p;l++)for(var n=k[l],t=0,u=n.vertexNormals.length;t<u;t++){var r=n.vertexNormals[t];a.copy(h[n[d[t]]]).applyMatrix4(e);b.copy(r).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);f.setXYZ(g,a.x,a.y,a.z);g+=1;f.setXYZ(g,b.x,b.y,b.z);g+=1}else if(g&&g.isBufferGeometry)for(d=
16464 g.attributes.position,h=g.attributes.normal,t=g=0,u=d.count;t<u;t++)a.set(d.getX(t),d.getY(t),d.getZ(t)).applyMatrix4(e),b.set(h.getX(t),h.getY(t),h.getZ(t)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),f.setXYZ(g,a.x,a.y,a.z),g+=1,f.setXYZ(g,b.x,b.y,b.z),g+=1;f.needsUpdate=!0}}();ic.prototype=Object.create(D.prototype);ic.prototype.constructor=ic;ic.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};ic.prototype.update=function(){var a=new p,
16465 b=new p;return function(){this.light.updateMatrixWorld();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)}}();jc.prototype=Object.create(W.prototype);jc.prototype.constructor=jc;jc.prototype.updateMatrixWorld=
16466 function(){var a=new p,b=new I,c=new I;return function(d){var e=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;D.prototype.updateMatrixWorld.call(this,d)}}();
16467 kc.prototype=Object.create(la.prototype);kc.prototype.constructor=kc;kc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};kc.prototype.update=function(){void 0!==this.color?this.material.color.set(this.color):this.material.color.copy(this.light.color)};lc.prototype=Object.create(D.prototype);lc.prototype.constructor=lc;lc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};lc.prototype.update=function(){var a=.5*this.light.width,
16468 b=.5*this.light.height,c=this.line.geometry.attributes.position,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)};mc.prototype=Object.create(D.prototype);mc.prototype.constructor=mc;mc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};mc.prototype.update=
16469 function(){var a=new p,b=new G,c=new G;return function(){var d=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())}}();gd.prototype=Object.create(W.prototype);gd.prototype.constructor=gd;Md.prototype=Object.create(W.prototype);
16470 Md.prototype.constructor=Md;hd.prototype=Object.create(W.prototype);hd.prototype.constructor=hd;hd.prototype.update=function(){var a=new p,b=new p,c=new ra;return function(){this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);var d=this.object.matrixWorld,e=this.geometry.attributes.position,f=this.object.geometry,g=f.vertices;f=f.faces;for(var h=0,k=0,l=f.length;k<l;k++){var p=f[k],n=p.normal;a.copy(g[p.a]).add(g[p.b]).add(g[p.c]).divideScalar(3).applyMatrix4(d);b.copy(n).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);
16471 e.setXYZ(h,a.x,a.y,a.z);h+=1;e.setXYZ(h,b.x,b.y,b.z);h+=1}e.needsUpdate=!0}}();nc.prototype=Object.create(D.prototype);nc.prototype.constructor=nc;nc.prototype.dispose=function(){this.lightPlane.geometry.dispose();this.lightPlane.material.dispose();this.targetLine.geometry.dispose();this.targetLine.material.dispose()};nc.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,
16472 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()}}();id.prototype=Object.create(W.prototype);id.prototype.constructor=id;id.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"),
16473 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 Na;return function(){b=this.geometry;c=this.pointMap;e.projectionMatrix.copy(this.camera.projectionMatrix);a("c",0,0,-1);a("t",0,0,1);a("n1",-1,-1,-1);a("n2",1,-1,-1);a("n3",-1,1,-1);a("n4",1,1,-1);a("f1",-1,-1,1);a("f2",1,-1,1);a("f3",-1,1,1);a("f4",1,1,1);a("u1",.7,1.1,-1);a("u2",-.7,1.1,-1);a("u3",0,2,-1);a("cf1",-1,0,1);a("cf2",1,0,1);a("cf3",0,-1,1);a("cf4",0,1,1);a("cn1",-1,0,-1);a("cn2",1,0,-1);a("cn3",0,-1,-1);a("cn4",
16474 0,1,-1);b.getAttribute("position").needsUpdate=!0}}();Db.prototype=Object.create(W.prototype);Db.prototype.constructor=Db;Db.prototype.update=function(){var a=new Sa;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]=
16475 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};jd.prototype=Object.create(W.prototype);jd.prototype.constructor=jd;jd.prototype.updateMatrixWorld=function(a){var b=this.box;b.isEmpty()||(b.getCenter(this.position),b.getSize(this.scale),this.scale.multiplyScalar(.5),D.prototype.updateMatrixWorld.call(this,
16476 a))};kd.prototype=Object.create(sa.prototype);kd.prototype.constructor=kd;kd.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.children[0].material.side=0>b?1:0;this.lookAt(this.plane.normal);D.prototype.updateMatrixWorld.call(this,a)};var Nd,ye;Eb.prototype=Object.create(D.prototype);Eb.prototype.constructor=Eb;Eb.prototype.setDirection=function(){var a=new p,b;return function(c){.99999<c.y?this.quaternion.set(0,
16477 0,0,1):-.99999>c.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,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)};ld.prototype=Object.create(W.prototype);
16478 ld.prototype.constructor=ld;L.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");a.prototype=Object.create(L.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};Object.assign(Xa.prototype,{createPointsGeometry:function(a){console.warn("THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");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.");
16479 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 R,c=0,d=a.length;c<d;c++){var e=a[c];b.vertices.push(new p(e.x,e.y,e.z||0))}return b}});Object.assign(La.prototype,{fromPoints:function(a){console.warn("THREE.Path: .fromPoints() has been renamed to .setFromPoints().");this.setFromPoints(a)}});yf.prototype=Object.create(ca.prototype);
16480 zf.prototype=Object.create(ca.prototype);ze.prototype=Object.create(ca.prototype);Object.assign(ze.prototype,{initFromArray:function(){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},reparametrizeByArcLength:function(){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});gd.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};
16481 jc.prototype.update=function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")};Object.assign(gc.prototype,{extractUrlBase:function(a){console.warn("THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.");return De.extractUrlBase(a)}});Object.assign(we.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");
16482 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(Sa.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");
16483 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)}});xe.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");
16484 return this.getCenter(a)};Object.assign(H,{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 H.floorPowerOfTwo(a)},nextPowerOfTwo:function(a){console.warn("THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().");return H.ceilPowerOfTwo(a)}});Object.assign(ra.prototype,{flattenToArrayOffset:function(a,
16485 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.");
16486 return this.applyToBufferAttribute(a)},applyToVector3Array:function(){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")}});Object.assign(I.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;
16487 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.");
16488 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.");
16489 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.");
16490 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)}});Ma.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)};
16491 fa.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(mb.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)},
16492 isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});Object.assign(ja.prototype,{area:function(){console.warn("THREE.Triangle: .area() has been renamed to .getArea().");return this.getArea()},barycoordFromPoint:function(a,b){console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().");return this.getBarycoord(a,b)},midpoint:function(a){console.warn("THREE.Triangle: .midpoint() has been renamed to .getMidpoint().");
16493 return this.getMidpoint(a)},normal:function(a){console.warn("THREE.Triangle: .normal() has been renamed to .getNormal().");return this.getNormal(a)},plane:function(a){console.warn("THREE.Triangle: .plane() has been renamed to .getPlane().");return this.getPlane(a)}});Object.assign(ja,{barycoordFromPoint:function(a,b,c,d,e){console.warn("THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().");return ja.getBarycoord(a,b,c,d,e)},normal:function(a,b,c,d){console.warn("THREE.Triangle: .normal() has been renamed to .getNormal().");
16494 return ja.getNormal(a,b,c,d)}});Object.assign(db.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 rb(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new tb(this,a)}});Object.assign(z.prototype,
16495 {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()}});Object.assign(p.prototype,
16496 {setEulerFromRotationMatrix:function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},setEulerFromQuaternion:function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},getPositionFromMatrix:function(a){console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().");return this.setFromMatrixPosition(a)},getScaleFromMatrix:function(a){console.warn("THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().");
16497 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,b,c){console.warn("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,
16498 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(V.prototype,{fromAttribute:function(a,b,c){console.warn("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,
16499 b,c)},lengthManhattan:function(){console.warn("THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});Object.assign(R.prototype,{computeTangents:function(){console.error("THREE.Geometry: .computeTangents() has been removed.")},computeLineDistances:function(){console.error("THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.")}});Object.assign(D.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");
16500 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)},getWorldRotation:function(){console.error("THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.")}});Object.defineProperties(D.prototype,
16501 {eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(a){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});
16502 Object.defineProperties(Bc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(Cc.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")},set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});Object.defineProperty(L.prototype,"__arcLengthDivisions",{get:function(){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");
16503 return this.arcLengthDivisions},set:function(a){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");this.arcLengthDivisions=a}});Z.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup.");void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};Object.defineProperties(X.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.");
16504 this.shadow.camera.fov=a}},shadowCameraLeft:{set:function(a){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left.");this.shadow.camera.left=a}},shadowCameraRight:{set:function(a){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right.");this.shadow.camera.right=a}},shadowCameraTop:{set:function(a){console.warn("THREE.Light: .shadowCameraTop is now .shadow.camera.top.");this.shadow.camera.top=a}},shadowCameraBottom:{set:function(a){console.warn("THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.");
16505 this.shadow.camera.bottom=a}},shadowCameraNear:{set:function(a){console.warn("THREE.Light: .shadowCameraNear is now .shadow.camera.near.");this.shadow.camera.near=a}},shadowCameraFar:{set:function(a){console.warn("THREE.Light: .shadowCameraFar is now .shadow.camera.far.");this.shadow.camera.far=a}},shadowCameraVisible:{set:function(){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.");
16506 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.");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(Q.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");
16507 return this.array.length}},copyIndicesArray:function(){console.error("THREE.BufferAttribute: .copyIndicesArray() has been removed.")}});Object.assign(C.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,b,c){void 0!==c&&console.warn("THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.");console.warn("THREE.BufferGeometry: .addDrawCall() is now .addGroup().");this.addGroup(a,b)},
16508 clearDrawCalls:function(){console.warn("THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().");this.clearGroups()},computeTangents:function(){console.warn("THREE.BufferGeometry: .computeTangents() has been removed.")},computeOffsets:function(){console.warn("THREE.BufferGeometry: .computeOffsets() has been removed.")}});Object.defineProperties(C.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.");
16509 return this.groups}}});Object.assign(Oa.prototype,{getArrays:function(){console.error("THREE.ExtrudeBufferGeometry: .getArrays() has been removed.")},addShapeList:function(){console.error("THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.")},addShape:function(){console.error("THREE.ExtrudeBufferGeometry: .addShape() has been removed.")}});Object.defineProperties(Ld.prototype,{dynamic:{set:function(){console.warn("THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.")}},
16510 onUpdate:{value:function(){console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.");return this}}});Object.defineProperties(J.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE.Material: .wrapRGB has been removed.");return new G}},shading:{get:function(){console.error("THREE."+this.type+
16511 ": .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.");this.flatShading=1===a}}});Object.defineProperties(Fa.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")}}});
16512 Object.defineProperties(ta.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});Object.assign(Zd.prototype,{animate:function(a){console.warn("THREE.WebGLRenderer: .animate() is now .setAnimationLoop().");this.setAnimationLoop(a)},getCurrentRenderTarget:function(){console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().");
16513 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.");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' ).");
16514 return this.extensions.get("OES_texture_float")},supportsHalfFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' ).");return this.extensions.get("OES_texture_half_float")},supportsStandardDerivatives:function(){console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' ).");return this.extensions.get("OES_standard_derivatives")},supportsCompressedTextureS3TC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' ).");
16515 return this.extensions.get("WEBGL_compressed_texture_s3tc")},supportsCompressedTexturePVRTC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' ).");return this.extensions.get("WEBGL_compressed_texture_pvrtc")},supportsBlendMinMax:function(){console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' ).");return this.extensions.get("EXT_blend_minmax")},supportsVertexTextures:function(){console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.");
16516 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.")},
16517 addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")},setFaceCulling:function(){console.warn("THREE.WebGLRenderer: .setFaceCulling() has been removed.")}});Object.defineProperties(Zd.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.");
16518 this.shadowMap.enabled=a}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.");this.shadowMap.type=a}},shadowMapCullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.")}}});Object.defineProperties(Ze.prototype,
16519 {cullFace:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.")}},renderReverseSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.")}},
16520 renderSingleSided:{get:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.")},set:function(){console.warn("THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.")}}});Object.defineProperties(fb.prototype,{wrapS:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");return this.texture.wrapS},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");
16521 this.texture.wrapS=a}},wrapT:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");return this.texture.wrapT},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");this.texture.wrapT=a}},magFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");return this.texture.magFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");this.texture.magFilter=
16522 a}},minFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");return this.texture.minFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");this.texture.minFilter=a}},anisotropy:{get:function(){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");return this.texture.anisotropy},set:function(a){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");this.texture.anisotropy=
16523 a}},offset:{get:function(){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");return this.texture.offset},set:function(a){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");this.texture.offset=a}},repeat:{get:function(){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");return this.texture.repeat},set:function(a){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");this.texture.repeat=a}},format:{get:function(){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");
16524 return this.texture.format},set:function(a){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");this.texture.format=a}},type:{get:function(){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");return this.texture.type},set:function(a){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");this.texture.type=a}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},
16525 set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});Object.defineProperties(af.prototype,{standing:{set:function(){console.warn("THREE.WebVRManager: .standing has been removed.")}}});hc.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new le).load(a,function(a){b.setBuffer(a)});return this};pe.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");
16526 return this.getFrequencyData()};dd.prototype.updateCubeMap=function(a,b){console.warn("THREE.CubeCamera: .updateCubeMap() is now .update().");return this.update(a,b)};eb.crossOrigin=void 0;eb.loadTexture=function(a,b,c,d){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");var e=new vd;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a};eb.loadTextureCube=function(a,b,c,d){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");
16527 var e=new ee;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a};eb.loadCompressedTexture=function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")};eb.loadCompressedTextureCube=function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")};l.WebGLRenderTargetCube=Gb;l.WebGLRenderTarget=fb;l.WebGLRenderer=Zd;l.ShaderLib=nb;l.UniformsLib=K;l.UniformsUtils=
16528 Aa;l.ShaderChunk=S;l.FogExp2=Lb;l.Fog=Mb;l.Scene=qd;l.Sprite=Ac;l.LOD=Bc;l.SkinnedMesh=sd;l.Skeleton=Cc;l.Bone=rd;l.Mesh=la;l.LineSegments=W;l.LineLoop=td;l.Line=sa;l.Points=Ob;l.Group=Kb;l.VideoTexture=$d;l.DataTexture=gb;l.CompressedTexture=Pb;l.CubeTexture=Ua;l.CanvasTexture=Dc;l.DepthTexture=Ec;l.Texture=T;l.CompressedTextureLoader=kf;l.DataTextureLoader=de;l.CubeTextureLoader=ee;l.TextureLoader=vd;l.ObjectLoader=mf;l.MaterialLoader=Kd;l.BufferGeometryLoader=ge;l.DefaultLoadingManager=ka;l.LoadingManager=
16529 ce;l.JSONLoader=he;l.ImageLoader=Zc;l.ImageBitmapLoader=ie;l.FontLoader=nf;l.FileLoader=Ga;l.Loader=gc;l.LoaderUtils=De;l.Cache=Fb;l.AudioLoader=le;l.SpotLightShadow=xd;l.SpotLight=yd;l.PointLight=zd;l.RectAreaLight=Dd;l.HemisphereLight=wd;l.DirectionalLightShadow=Ad;l.DirectionalLight=Bd;l.AmbientLight=Cd;l.LightShadow=Cb;l.Light=X;l.StereoCamera=of;l.PerspectiveCamera=Z;l.OrthographicCamera=Hb;l.CubeCamera=dd;l.ArrayCamera=yc;l.Camera=Na;l.AudioListener=me;l.PositionalAudio=oe;l.AudioContext=ne;
16530 l.AudioAnalyser=pe;l.Audio=hc;l.VectorKeyframeTrack=fc;l.StringKeyframeTrack=Jd;l.QuaternionKeyframeTrack=cd;l.NumberKeyframeTrack=ec;l.ColorKeyframeTrack=Hd;l.BooleanKeyframeTrack=Gd;l.PropertyMixer=qe;l.PropertyBinding=pa;l.KeyframeTrack=oa;l.AnimationUtils=ia;l.AnimationObjectGroup=qf;l.AnimationMixer=re;l.AnimationClip=Ca;l.Uniform=Ld;l.InstancedBufferGeometry=se;l.BufferGeometry=C;l.Geometry=R;l.InterleavedBufferAttribute=zc;l.InstancedInterleavedBuffer=te;l.InterleavedBuffer=ob;l.InstancedBufferAttribute=
16531 ue;l.Face3=Ta;l.Object3D=D;l.Raycaster=sf;l.Layers=Rd;l.EventDispatcher=ya;l.Clock=uf;l.QuaternionLinearInterpolant=Id;l.LinearInterpolant=bd;l.DiscreteInterpolant=Fd;l.CubicInterpolant=Ed;l.Interpolant=wa;l.Triangle=ja;l.Math=H;l.Spherical=vf;l.Cylindrical=wf;l.Plane=Ma;l.Frustum=md;l.Sphere=Da;l.Ray=mb;l.Matrix4=I;l.Matrix3=ra;l.Box3=Sa;l.Box2=we;l.Line3=xe;l.Euler=hb;l.Vector4=V;l.Vector3=p;l.Vector2=z;l.Quaternion=fa;l.Color=G;l.ImmediateRenderObject=ed;l.VertexNormalsHelper=fd;l.SpotLightHelper=
16532 ic;l.SkeletonHelper=jc;l.PointLightHelper=kc;l.RectAreaLightHelper=lc;l.HemisphereLightHelper=mc;l.GridHelper=gd;l.PolarGridHelper=Md;l.FaceNormalsHelper=hd;l.DirectionalLightHelper=nc;l.CameraHelper=id;l.BoxHelper=Db;l.Box3Helper=jd;l.PlaneHelper=kd;l.ArrowHelper=Eb;l.AxesHelper=ld;l.Shape=db;l.Path=La;l.ShapePath=je;l.Font=ke;l.CurvePath=Xa;l.Curve=L;l.ImageUtils=eb;l.ShapeUtils=Va;l.WebGLUtils=$e;l.WireframeGeometry=Qb;l.ParametricGeometry=Fc;l.ParametricBufferGeometry=Rb;l.TetrahedronGeometry=
16533 Hc;l.TetrahedronBufferGeometry=Sb;l.OctahedronGeometry=Ic;l.OctahedronBufferGeometry=pb;l.IcosahedronGeometry=Jc;l.IcosahedronBufferGeometry=Tb;l.DodecahedronGeometry=Kc;l.DodecahedronBufferGeometry=Ub;l.PolyhedronGeometry=Gc;l.PolyhedronBufferGeometry=na;l.TubeGeometry=Lc;l.TubeBufferGeometry=Vb;l.TorusKnotGeometry=Mc;l.TorusKnotBufferGeometry=Wb;l.TorusGeometry=Nc;l.TorusBufferGeometry=Xb;l.TextGeometry=Sc;l.TextBufferGeometry=Yb;l.SphereGeometry=Tc;l.SphereBufferGeometry=sb;l.RingGeometry=Uc;l.RingBufferGeometry=
16534 Zb;l.PlaneGeometry=uc;l.PlaneBufferGeometry=lb;l.LatheGeometry=Vc;l.LatheBufferGeometry=$b;l.ShapeGeometry=tb;l.ShapeBufferGeometry=ub;l.ExtrudeGeometry=rb;l.ExtrudeBufferGeometry=Oa;l.EdgesGeometry=ac;l.ConeGeometry=Wc;l.ConeBufferGeometry=Xc;l.CylinderGeometry=vb;l.CylinderBufferGeometry=Wa;l.CircleGeometry=Yc;l.CircleBufferGeometry=bc;l.BoxGeometry=Ib;l.BoxBufferGeometry=kb;l.ShadowMaterial=wb;l.SpriteMaterial=cb;l.RawShaderMaterial=cc;l.ShaderMaterial=ta;l.PointsMaterial=Ea;l.MeshPhysicalMaterial=
16535 xb;l.MeshStandardMaterial=Pa;l.MeshPhongMaterial=Fa;l.MeshToonMaterial=yb;l.MeshNormalMaterial=zb;l.MeshLambertMaterial=Ab;l.MeshDepthMaterial=$a;l.MeshDistanceMaterial=ab;l.MeshBasicMaterial=da;l.LineDashedMaterial=Bb;l.LineBasicMaterial=Y;l.Material=J;l.Float64BufferAttribute=tc;l.Float32BufferAttribute=A;l.Uint32BufferAttribute=jb;l.Int32BufferAttribute=sc;l.Uint16BufferAttribute=ib;l.Int16BufferAttribute=rc;l.Uint8ClampedBufferAttribute=qc;l.Uint8BufferAttribute=pc;l.Int8BufferAttribute=oc;l.BufferAttribute=
16536 Q;l.ArcCurve=dc;l.CatmullRomCurve3=ca;l.CubicBezierCurve=Ha;l.CubicBezierCurve3=Qa;l.EllipseCurve=za;l.LineCurve=va;l.LineCurve3=Ia;l.QuadraticBezierCurve=Ja;l.QuadraticBezierCurve3=Ra;l.SplineCurve=Ka;l.REVISION="95";l.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};l.CullFaceNone=0;l.CullFaceBack=1;l.CullFaceFront=2;l.CullFaceFrontBack=3;l.FrontFaceDirectionCW=0;l.FrontFaceDirectionCCW=1;l.BasicShadowMap=0;l.PCFShadowMap=1;l.PCFSoftShadowMap=2;l.FrontSide=0;l.BackSide=1;l.DoubleSide=2;l.FlatShading=1;l.SmoothShading=
16537 2;l.NoColors=0;l.FaceColors=1;l.VertexColors=2;l.NoBlending=0;l.NormalBlending=1;l.AdditiveBlending=2;l.SubtractiveBlending=3;l.MultiplyBlending=4;l.CustomBlending=5;l.AddEquation=100;l.SubtractEquation=101;l.ReverseSubtractEquation=102;l.MinEquation=103;l.MaxEquation=104;l.ZeroFactor=200;l.OneFactor=201;l.SrcColorFactor=202;l.OneMinusSrcColorFactor=203;l.SrcAlphaFactor=204;l.OneMinusSrcAlphaFactor=205;l.DstAlphaFactor=206;l.OneMinusDstAlphaFactor=207;l.DstColorFactor=208;l.OneMinusDstColorFactor=
16538 209;l.SrcAlphaSaturateFactor=210;l.NeverDepth=0;l.AlwaysDepth=1;l.LessDepth=2;l.LessEqualDepth=3;l.EqualDepth=4;l.GreaterEqualDepth=5;l.GreaterDepth=6;l.NotEqualDepth=7;l.MultiplyOperation=0;l.MixOperation=1;l.AddOperation=2;l.NoToneMapping=0;l.LinearToneMapping=1;l.ReinhardToneMapping=2;l.Uncharted2ToneMapping=3;l.CineonToneMapping=4;l.UVMapping=300;l.CubeReflectionMapping=301;l.CubeRefractionMapping=302;l.EquirectangularReflectionMapping=303;l.EquirectangularRefractionMapping=304;l.SphericalReflectionMapping=
16539 305;l.CubeUVReflectionMapping=306;l.CubeUVRefractionMapping=307;l.RepeatWrapping=1E3;l.ClampToEdgeWrapping=1001;l.MirroredRepeatWrapping=1002;l.NearestFilter=1003;l.NearestMipMapNearestFilter=1004;l.NearestMipMapLinearFilter=1005;l.LinearFilter=1006;l.LinearMipMapNearestFilter=1007;l.LinearMipMapLinearFilter=1008;l.UnsignedByteType=1009;l.ByteType=1010;l.ShortType=1011;l.UnsignedShortType=1012;l.IntType=1013;l.UnsignedIntType=1014;l.FloatType=1015;l.HalfFloatType=1016;l.UnsignedShort4444Type=1017;
16540 l.UnsignedShort5551Type=1018;l.UnsignedShort565Type=1019;l.UnsignedInt248Type=1020;l.AlphaFormat=1021;l.RGBFormat=1022;l.RGBAFormat=1023;l.LuminanceFormat=1024;l.LuminanceAlphaFormat=1025;l.RGBEFormat=1023;l.DepthFormat=1026;l.DepthStencilFormat=1027;l.RGB_S3TC_DXT1_Format=33776;l.RGBA_S3TC_DXT1_Format=33777;l.RGBA_S3TC_DXT3_Format=33778;l.RGBA_S3TC_DXT5_Format=33779;l.RGB_PVRTC_4BPPV1_Format=35840;l.RGB_PVRTC_2BPPV1_Format=35841;l.RGBA_PVRTC_4BPPV1_Format=35842;l.RGBA_PVRTC_2BPPV1_Format=35843;l.RGB_ETC1_Format=
16541 36196;l.RGBA_ASTC_4x4_Format=37808;l.RGBA_ASTC_5x4_Format=37809;l.RGBA_ASTC_5x5_Format=37810;l.RGBA_ASTC_6x5_Format=37811;l.RGBA_ASTC_6x6_Format=37812;l.RGBA_ASTC_8x5_Format=37813;l.RGBA_ASTC_8x6_Format=37814;l.RGBA_ASTC_8x8_Format=37815;l.RGBA_ASTC_10x5_Format=37816;l.RGBA_ASTC_10x6_Format=37817;l.RGBA_ASTC_10x8_Format=37818;l.RGBA_ASTC_10x10_Format=37819;l.RGBA_ASTC_12x10_Format=37820;l.RGBA_ASTC_12x12_Format=37821;l.LoopOnce=2200;l.LoopRepeat=2201;l.LoopPingPong=2202;l.InterpolateDiscrete=2300;
16542 l.InterpolateLinear=2301;l.InterpolateSmooth=2302;l.ZeroCurvatureEnding=2400;l.ZeroSlopeEnding=2401;l.WrapAroundEnding=2402;l.TrianglesDrawMode=0;l.TriangleStripDrawMode=1;l.TriangleFanDrawMode=2;l.LinearEncoding=3E3;l.sRGBEncoding=3001;l.GammaEncoding=3007;l.RGBEEncoding=3002;l.LogLuvEncoding=3003;l.RGBM7Encoding=3004;l.RGBM16Encoding=3005;l.RGBDEncoding=3006;l.BasicDepthPacking=3200;l.RGBADepthPacking=3201;l.TangentSpaceNormalMap=0;l.ObjectSpaceNormalMap=1;l.CubeGeometry=Ib;l.Face4=function(a,b,
16543 c,d,e,f,g){console.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead.");return new Ta(a,b,c,e,f,g)};l.LineStrip=0;l.LinePieces=1;l.MeshFaceMaterial=function(a){console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead.");return a};l.MultiMaterial=function(a){void 0===a&&(a=[]);console.warn("THREE.MultiMaterial has been removed. Use an Array instead.");a.isMultiMaterial=!0;a.materials=a;a.clone=function(){return a.slice()};return a};l.PointCloud=function(a,
16544 b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Ob(a,b)};l.Particle=function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");return new Ac(a)};l.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Ob(a,b)};l.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");return new Ea(a)};l.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");
16545 return new Ea(a)};l.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");return new Ea(a)};l.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new p(a,b,c)};l.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");return(new Q(a,b)).setDynamic(!0)};l.Int8Attribute=function(a,
16546 b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");return new oc(a,b)};l.Uint8Attribute=function(a,b){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new pc(a,b)};l.Uint8ClampedAttribute=function(a,b){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new qc(a,b)};l.Int16Attribute=function(a,b){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");
16547 return new rc(a,b)};l.Uint16Attribute=function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");return new ib(a,b)};l.Int32Attribute=function(a,b){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new sc(a,b)};l.Uint32Attribute=function(a,b){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");return new jb(a,b)};l.Float32Attribute=
16548 function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");return new A(a,b)};l.Float64Attribute=function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new tc(a,b)};l.ClosedSplineCurve3=yf;l.SplineCurve3=zf;l.Spline=ze;l.AxisHelper=function(a){console.warn("THREE.AxisHelper has been renamed to THREE.AxesHelper.");return new ld(a)};l.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");
16549 return new Db(a,b)};l.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new W(new ac(a.geometry),new Y({color:void 0!==b?b:16777215}))};l.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new W(new Qb(a.geometry),new Y({color:void 0!==b?b:16777215}))};l.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new Ga(a)};
16550 l.BinaryTextureLoader=function(a){console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.");return new de(a)};l.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();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.");
16551 return a.center()}};l.Projector=function(){console.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js.");this.projectVector=function(a,b){console.warn("THREE.Projector: .projectVector() is now vector.project().");a.project(b)};this.unprojectVector=function(a,b){console.warn("THREE.Projector: .unprojectVector() is now vector.unproject().");a.unproject(b)};this.pickingRay=function(){console.error("THREE.Projector: .pickingRay() is now raycaster.setFromCamera().")}};l.CanvasRenderer=
16552 function(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");this.clear=function(){};this.render=function(){};this.setClearColor=function(){};this.setSize=function(){}};l.SceneUtils={createMultiMaterialObject:function(){console.error("THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js")},detach:function(){console.error("THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js")},
16553 attach:function(){console.error("THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js")}};l.LensFlare=function(){console.error("THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js")};Object.defineProperty(l,"__esModule",{value:!0})});
16554
16555 },{}],226:[function(require,module,exports){
16556 'use strict';
16557
16558 module.exports = TinyQueue;
16559
16560 function TinyQueue(data, compare) {
16561     if (!(this instanceof TinyQueue)) return new TinyQueue(data, compare);
16562
16563     this.data = data || [];
16564     this.length = this.data.length;
16565     this.compare = compare || defaultCompare;
16566
16567     if (this.length > 0) {
16568         for (var i = (this.length >> 1); i >= 0; i--) this._down(i);
16569     }
16570 }
16571
16572 function defaultCompare(a, b) {
16573     return a < b ? -1 : a > b ? 1 : 0;
16574 }
16575
16576 TinyQueue.prototype = {
16577
16578     push: function (item) {
16579         this.data.push(item);
16580         this.length++;
16581         this._up(this.length - 1);
16582     },
16583
16584     pop: function () {
16585         if (this.length === 0) return undefined;
16586         var top = this.data[0];
16587         this.length--;
16588         if (this.length > 0) {
16589             this.data[0] = this.data[this.length];
16590             this._down(0);
16591         }
16592         this.data.pop();
16593         return top;
16594     },
16595
16596     peek: function () {
16597         return this.data[0];
16598     },
16599
16600     _up: function (pos) {
16601         var data = this.data;
16602         var compare = this.compare;
16603         var item = data[pos];
16604
16605         while (pos > 0) {
16606             var parent = (pos - 1) >> 1;
16607             var current = data[parent];
16608             if (compare(item, current) >= 0) break;
16609             data[pos] = current;
16610             pos = parent;
16611         }
16612
16613         data[pos] = item;
16614     },
16615
16616     _down: function (pos) {
16617         var data = this.data;
16618         var compare = this.compare;
16619         var len = this.length;
16620         var halfLen = len >> 1;
16621         var item = data[pos];
16622
16623         while (pos < halfLen) {
16624             var left = (pos << 1) + 1;
16625             var right = left + 1;
16626             var best = data[left];
16627
16628             if (right < len && compare(data[right], best) < 0) {
16629                 left = right;
16630                 best = data[right];
16631             }
16632             if (compare(best, item) >= 0) break;
16633
16634             data[pos] = best;
16635             pos = left;
16636         }
16637
16638         data[pos] = item;
16639     }
16640 };
16641
16642 },{}],227:[function(require,module,exports){
16643 var createElement = require("./vdom/create-element.js")
16644
16645 module.exports = createElement
16646
16647 },{"./vdom/create-element.js":233}],228:[function(require,module,exports){
16648 var diff = require("./vtree/diff.js")
16649
16650 module.exports = diff
16651
16652 },{"./vtree/diff.js":253}],229:[function(require,module,exports){
16653 var h = require("./virtual-hyperscript/index.js")
16654
16655 module.exports = h
16656
16657 },{"./virtual-hyperscript/index.js":240}],230:[function(require,module,exports){
16658 var diff = require("./diff.js")
16659 var patch = require("./patch.js")
16660 var h = require("./h.js")
16661 var create = require("./create-element.js")
16662 var VNode = require('./vnode/vnode.js')
16663 var VText = require('./vnode/vtext.js')
16664
16665 module.exports = {
16666     diff: diff,
16667     patch: patch,
16668     h: h,
16669     create: create,
16670     VNode: VNode,
16671     VText: VText
16672 }
16673
16674 },{"./create-element.js":227,"./diff.js":228,"./h.js":229,"./patch.js":231,"./vnode/vnode.js":249,"./vnode/vtext.js":251}],231:[function(require,module,exports){
16675 var patch = require("./vdom/patch.js")
16676
16677 module.exports = patch
16678
16679 },{"./vdom/patch.js":236}],232:[function(require,module,exports){
16680 var isObject = require("is-object")
16681 var isHook = require("../vnode/is-vhook.js")
16682
16683 module.exports = applyProperties
16684
16685 function applyProperties(node, props, previous) {
16686     for (var propName in props) {
16687         var propValue = props[propName]
16688
16689         if (propValue === undefined) {
16690             removeProperty(node, propName, propValue, previous);
16691         } else if (isHook(propValue)) {
16692             removeProperty(node, propName, propValue, previous)
16693             if (propValue.hook) {
16694                 propValue.hook(node,
16695                     propName,
16696                     previous ? previous[propName] : undefined)
16697             }
16698         } else {
16699             if (isObject(propValue)) {
16700                 patchObject(node, props, previous, propName, propValue);
16701             } else {
16702                 node[propName] = propValue
16703             }
16704         }
16705     }
16706 }
16707
16708 function removeProperty(node, propName, propValue, previous) {
16709     if (previous) {
16710         var previousValue = previous[propName]
16711
16712         if (!isHook(previousValue)) {
16713             if (propName === "attributes") {
16714                 for (var attrName in previousValue) {
16715                     node.removeAttribute(attrName)
16716                 }
16717             } else if (propName === "style") {
16718                 for (var i in previousValue) {
16719                     node.style[i] = ""
16720                 }
16721             } else if (typeof previousValue === "string") {
16722                 node[propName] = ""
16723             } else {
16724                 node[propName] = null
16725             }
16726         } else if (previousValue.unhook) {
16727             previousValue.unhook(node, propName, propValue)
16728         }
16729     }
16730 }
16731
16732 function patchObject(node, props, previous, propName, propValue) {
16733     var previousValue = previous ? previous[propName] : undefined
16734
16735     // Set attributes
16736     if (propName === "attributes") {
16737         for (var attrName in propValue) {
16738             var attrValue = propValue[attrName]
16739
16740             if (attrValue === undefined) {
16741                 node.removeAttribute(attrName)
16742             } else {
16743                 node.setAttribute(attrName, attrValue)
16744             }
16745         }
16746
16747         return
16748     }
16749
16750     if(previousValue && isObject(previousValue) &&
16751         getPrototype(previousValue) !== getPrototype(propValue)) {
16752         node[propName] = propValue
16753         return
16754     }
16755
16756     if (!isObject(node[propName])) {
16757         node[propName] = {}
16758     }
16759
16760     var replacer = propName === "style" ? "" : undefined
16761
16762     for (var k in propValue) {
16763         var value = propValue[k]
16764         node[propName][k] = (value === undefined) ? replacer : value
16765     }
16766 }
16767
16768 function getPrototype(value) {
16769     if (Object.getPrototypeOf) {
16770         return Object.getPrototypeOf(value)
16771     } else if (value.__proto__) {
16772         return value.__proto__
16773     } else if (value.constructor) {
16774         return value.constructor.prototype
16775     }
16776 }
16777
16778 },{"../vnode/is-vhook.js":244,"is-object":20}],233:[function(require,module,exports){
16779 var document = require("global/document")
16780
16781 var applyProperties = require("./apply-properties")
16782
16783 var isVNode = require("../vnode/is-vnode.js")
16784 var isVText = require("../vnode/is-vtext.js")
16785 var isWidget = require("../vnode/is-widget.js")
16786 var handleThunk = require("../vnode/handle-thunk.js")
16787
16788 module.exports = createElement
16789
16790 function createElement(vnode, opts) {
16791     var doc = opts ? opts.document || document : document
16792     var warn = opts ? opts.warn : null
16793
16794     vnode = handleThunk(vnode).a
16795
16796     if (isWidget(vnode)) {
16797         return vnode.init()
16798     } else if (isVText(vnode)) {
16799         return doc.createTextNode(vnode.text)
16800     } else if (!isVNode(vnode)) {
16801         if (warn) {
16802             warn("Item is not a valid virtual dom node", vnode)
16803         }
16804         return null
16805     }
16806
16807     var node = (vnode.namespace === null) ?
16808         doc.createElement(vnode.tagName) :
16809         doc.createElementNS(vnode.namespace, vnode.tagName)
16810
16811     var props = vnode.properties
16812     applyProperties(node, props)
16813
16814     var children = vnode.children
16815
16816     for (var i = 0; i < children.length; i++) {
16817         var childNode = createElement(children[i], opts)
16818         if (childNode) {
16819             node.appendChild(childNode)
16820         }
16821     }
16822
16823     return node
16824 }
16825
16826 },{"../vnode/handle-thunk.js":242,"../vnode/is-vnode.js":245,"../vnode/is-vtext.js":246,"../vnode/is-widget.js":247,"./apply-properties":232,"global/document":16}],234:[function(require,module,exports){
16827 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
16828 // We don't want to read all of the DOM nodes in the tree so we use
16829 // the in-order tree indexing to eliminate recursion down certain branches.
16830 // We only recurse into a DOM node if we know that it contains a child of
16831 // interest.
16832
16833 var noChild = {}
16834
16835 module.exports = domIndex
16836
16837 function domIndex(rootNode, tree, indices, nodes) {
16838     if (!indices || indices.length === 0) {
16839         return {}
16840     } else {
16841         indices.sort(ascending)
16842         return recurse(rootNode, tree, indices, nodes, 0)
16843     }
16844 }
16845
16846 function recurse(rootNode, tree, indices, nodes, rootIndex) {
16847     nodes = nodes || {}
16848
16849
16850     if (rootNode) {
16851         if (indexInRange(indices, rootIndex, rootIndex)) {
16852             nodes[rootIndex] = rootNode
16853         }
16854
16855         var vChildren = tree.children
16856
16857         if (vChildren) {
16858
16859             var childNodes = rootNode.childNodes
16860
16861             for (var i = 0; i < tree.children.length; i++) {
16862                 rootIndex += 1
16863
16864                 var vChild = vChildren[i] || noChild
16865                 var nextIndex = rootIndex + (vChild.count || 0)
16866
16867                 // skip recursion down the tree if there are no nodes down here
16868                 if (indexInRange(indices, rootIndex, nextIndex)) {
16869                     recurse(childNodes[i], vChild, indices, nodes, rootIndex)
16870                 }
16871
16872                 rootIndex = nextIndex
16873             }
16874         }
16875     }
16876
16877     return nodes
16878 }
16879
16880 // Binary search for an index in the interval [left, right]
16881 function indexInRange(indices, left, right) {
16882     if (indices.length === 0) {
16883         return false
16884     }
16885
16886     var minIndex = 0
16887     var maxIndex = indices.length - 1
16888     var currentIndex
16889     var currentItem
16890
16891     while (minIndex <= maxIndex) {
16892         currentIndex = ((maxIndex + minIndex) / 2) >> 0
16893         currentItem = indices[currentIndex]
16894
16895         if (minIndex === maxIndex) {
16896             return currentItem >= left && currentItem <= right
16897         } else if (currentItem < left) {
16898             minIndex = currentIndex + 1
16899         } else  if (currentItem > right) {
16900             maxIndex = currentIndex - 1
16901         } else {
16902             return true
16903         }
16904     }
16905
16906     return false;
16907 }
16908
16909 function ascending(a, b) {
16910     return a > b ? 1 : -1
16911 }
16912
16913 },{}],235:[function(require,module,exports){
16914 var applyProperties = require("./apply-properties")
16915
16916 var isWidget = require("../vnode/is-widget.js")
16917 var VPatch = require("../vnode/vpatch.js")
16918
16919 var updateWidget = require("./update-widget")
16920
16921 module.exports = applyPatch
16922
16923 function applyPatch(vpatch, domNode, renderOptions) {
16924     var type = vpatch.type
16925     var vNode = vpatch.vNode
16926     var patch = vpatch.patch
16927
16928     switch (type) {
16929         case VPatch.REMOVE:
16930             return removeNode(domNode, vNode)
16931         case VPatch.INSERT:
16932             return insertNode(domNode, patch, renderOptions)
16933         case VPatch.VTEXT:
16934             return stringPatch(domNode, vNode, patch, renderOptions)
16935         case VPatch.WIDGET:
16936             return widgetPatch(domNode, vNode, patch, renderOptions)
16937         case VPatch.VNODE:
16938             return vNodePatch(domNode, vNode, patch, renderOptions)
16939         case VPatch.ORDER:
16940             reorderChildren(domNode, patch)
16941             return domNode
16942         case VPatch.PROPS:
16943             applyProperties(domNode, patch, vNode.properties)
16944             return domNode
16945         case VPatch.THUNK:
16946             return replaceRoot(domNode,
16947                 renderOptions.patch(domNode, patch, renderOptions))
16948         default:
16949             return domNode
16950     }
16951 }
16952
16953 function removeNode(domNode, vNode) {
16954     var parentNode = domNode.parentNode
16955
16956     if (parentNode) {
16957         parentNode.removeChild(domNode)
16958     }
16959
16960     destroyWidget(domNode, vNode);
16961
16962     return null
16963 }
16964
16965 function insertNode(parentNode, vNode, renderOptions) {
16966     var newNode = renderOptions.render(vNode, renderOptions)
16967
16968     if (parentNode) {
16969         parentNode.appendChild(newNode)
16970     }
16971
16972     return parentNode
16973 }
16974
16975 function stringPatch(domNode, leftVNode, vText, renderOptions) {
16976     var newNode
16977
16978     if (domNode.nodeType === 3) {
16979         domNode.replaceData(0, domNode.length, vText.text)
16980         newNode = domNode
16981     } else {
16982         var parentNode = domNode.parentNode
16983         newNode = renderOptions.render(vText, renderOptions)
16984
16985         if (parentNode && newNode !== domNode) {
16986             parentNode.replaceChild(newNode, domNode)
16987         }
16988     }
16989
16990     return newNode
16991 }
16992
16993 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
16994     var updating = updateWidget(leftVNode, widget)
16995     var newNode
16996
16997     if (updating) {
16998         newNode = widget.update(leftVNode, domNode) || domNode
16999     } else {
17000         newNode = renderOptions.render(widget, renderOptions)
17001     }
17002
17003     var parentNode = domNode.parentNode
17004
17005     if (parentNode && newNode !== domNode) {
17006         parentNode.replaceChild(newNode, domNode)
17007     }
17008
17009     if (!updating) {
17010         destroyWidget(domNode, leftVNode)
17011     }
17012
17013     return newNode
17014 }
17015
17016 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
17017     var parentNode = domNode.parentNode
17018     var newNode = renderOptions.render(vNode, renderOptions)
17019
17020     if (parentNode && newNode !== domNode) {
17021         parentNode.replaceChild(newNode, domNode)
17022     }
17023
17024     return newNode
17025 }
17026
17027 function destroyWidget(domNode, w) {
17028     if (typeof w.destroy === "function" && isWidget(w)) {
17029         w.destroy(domNode)
17030     }
17031 }
17032
17033 function reorderChildren(domNode, moves) {
17034     var childNodes = domNode.childNodes
17035     var keyMap = {}
17036     var node
17037     var remove
17038     var insert
17039
17040     for (var i = 0; i < moves.removes.length; i++) {
17041         remove = moves.removes[i]
17042         node = childNodes[remove.from]
17043         if (remove.key) {
17044             keyMap[remove.key] = node
17045         }
17046         domNode.removeChild(node)
17047     }
17048
17049     var length = childNodes.length
17050     for (var j = 0; j < moves.inserts.length; j++) {
17051         insert = moves.inserts[j]
17052         node = keyMap[insert.key]
17053         // this is the weirdest bug i've ever seen in webkit
17054         domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
17055     }
17056 }
17057
17058 function replaceRoot(oldRoot, newRoot) {
17059     if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
17060         oldRoot.parentNode.replaceChild(newRoot, oldRoot)
17061     }
17062
17063     return newRoot;
17064 }
17065
17066 },{"../vnode/is-widget.js":247,"../vnode/vpatch.js":250,"./apply-properties":232,"./update-widget":237}],236:[function(require,module,exports){
17067 var document = require("global/document")
17068 var isArray = require("x-is-array")
17069
17070 var render = require("./create-element")
17071 var domIndex = require("./dom-index")
17072 var patchOp = require("./patch-op")
17073 module.exports = patch
17074
17075 function patch(rootNode, patches, renderOptions) {
17076     renderOptions = renderOptions || {}
17077     renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
17078         ? renderOptions.patch
17079         : patchRecursive
17080     renderOptions.render = renderOptions.render || render
17081
17082     return renderOptions.patch(rootNode, patches, renderOptions)
17083 }
17084
17085 function patchRecursive(rootNode, patches, renderOptions) {
17086     var indices = patchIndices(patches)
17087
17088     if (indices.length === 0) {
17089         return rootNode
17090     }
17091
17092     var index = domIndex(rootNode, patches.a, indices)
17093     var ownerDocument = rootNode.ownerDocument
17094
17095     if (!renderOptions.document && ownerDocument !== document) {
17096         renderOptions.document = ownerDocument
17097     }
17098
17099     for (var i = 0; i < indices.length; i++) {
17100         var nodeIndex = indices[i]
17101         rootNode = applyPatch(rootNode,
17102             index[nodeIndex],
17103             patches[nodeIndex],
17104             renderOptions)
17105     }
17106
17107     return rootNode
17108 }
17109
17110 function applyPatch(rootNode, domNode, patchList, renderOptions) {
17111     if (!domNode) {
17112         return rootNode
17113     }
17114
17115     var newNode
17116
17117     if (isArray(patchList)) {
17118         for (var i = 0; i < patchList.length; i++) {
17119             newNode = patchOp(patchList[i], domNode, renderOptions)
17120
17121             if (domNode === rootNode) {
17122                 rootNode = newNode
17123             }
17124         }
17125     } else {
17126         newNode = patchOp(patchList, domNode, renderOptions)
17127
17128         if (domNode === rootNode) {
17129             rootNode = newNode
17130         }
17131     }
17132
17133     return rootNode
17134 }
17135
17136 function patchIndices(patches) {
17137     var indices = []
17138
17139     for (var key in patches) {
17140         if (key !== "a") {
17141             indices.push(Number(key))
17142         }
17143     }
17144
17145     return indices
17146 }
17147
17148 },{"./create-element":233,"./dom-index":234,"./patch-op":235,"global/document":16,"x-is-array":272}],237:[function(require,module,exports){
17149 var isWidget = require("../vnode/is-widget.js")
17150
17151 module.exports = updateWidget
17152
17153 function updateWidget(a, b) {
17154     if (isWidget(a) && isWidget(b)) {
17155         if ("name" in a && "name" in b) {
17156             return a.id === b.id
17157         } else {
17158             return a.init === b.init
17159         }
17160     }
17161
17162     return false
17163 }
17164
17165 },{"../vnode/is-widget.js":247}],238:[function(require,module,exports){
17166 'use strict';
17167
17168 var EvStore = require('ev-store');
17169
17170 module.exports = EvHook;
17171
17172 function EvHook(value) {
17173     if (!(this instanceof EvHook)) {
17174         return new EvHook(value);
17175     }
17176
17177     this.value = value;
17178 }
17179
17180 EvHook.prototype.hook = function (node, propertyName) {
17181     var es = EvStore(node);
17182     var propName = propertyName.substr(3);
17183
17184     es[propName] = this.value;
17185 };
17186
17187 EvHook.prototype.unhook = function(node, propertyName) {
17188     var es = EvStore(node);
17189     var propName = propertyName.substr(3);
17190
17191     es[propName] = undefined;
17192 };
17193
17194 },{"ev-store":9}],239:[function(require,module,exports){
17195 'use strict';
17196
17197 module.exports = SoftSetHook;
17198
17199 function SoftSetHook(value) {
17200     if (!(this instanceof SoftSetHook)) {
17201         return new SoftSetHook(value);
17202     }
17203
17204     this.value = value;
17205 }
17206
17207 SoftSetHook.prototype.hook = function (node, propertyName) {
17208     if (node[propertyName] !== this.value) {
17209         node[propertyName] = this.value;
17210     }
17211 };
17212
17213 },{}],240:[function(require,module,exports){
17214 'use strict';
17215
17216 var isArray = require('x-is-array');
17217
17218 var VNode = require('../vnode/vnode.js');
17219 var VText = require('../vnode/vtext.js');
17220 var isVNode = require('../vnode/is-vnode');
17221 var isVText = require('../vnode/is-vtext');
17222 var isWidget = require('../vnode/is-widget');
17223 var isHook = require('../vnode/is-vhook');
17224 var isVThunk = require('../vnode/is-thunk');
17225
17226 var parseTag = require('./parse-tag.js');
17227 var softSetHook = require('./hooks/soft-set-hook.js');
17228 var evHook = require('./hooks/ev-hook.js');
17229
17230 module.exports = h;
17231
17232 function h(tagName, properties, children) {
17233     var childNodes = [];
17234     var tag, props, key, namespace;
17235
17236     if (!children && isChildren(properties)) {
17237         children = properties;
17238         props = {};
17239     }
17240
17241     props = props || properties || {};
17242     tag = parseTag(tagName, props);
17243
17244     // support keys
17245     if (props.hasOwnProperty('key')) {
17246         key = props.key;
17247         props.key = undefined;
17248     }
17249
17250     // support namespace
17251     if (props.hasOwnProperty('namespace')) {
17252         namespace = props.namespace;
17253         props.namespace = undefined;
17254     }
17255
17256     // fix cursor bug
17257     if (tag === 'INPUT' &&
17258         !namespace &&
17259         props.hasOwnProperty('value') &&
17260         props.value !== undefined &&
17261         !isHook(props.value)
17262     ) {
17263         props.value = softSetHook(props.value);
17264     }
17265
17266     transformProperties(props);
17267
17268     if (children !== undefined && children !== null) {
17269         addChild(children, childNodes, tag, props);
17270     }
17271
17272
17273     return new VNode(tag, props, childNodes, key, namespace);
17274 }
17275
17276 function addChild(c, childNodes, tag, props) {
17277     if (typeof c === 'string') {
17278         childNodes.push(new VText(c));
17279     } else if (typeof c === 'number') {
17280         childNodes.push(new VText(String(c)));
17281     } else if (isChild(c)) {
17282         childNodes.push(c);
17283     } else if (isArray(c)) {
17284         for (var i = 0; i < c.length; i++) {
17285             addChild(c[i], childNodes, tag, props);
17286         }
17287     } else if (c === null || c === undefined) {
17288         return;
17289     } else {
17290         throw UnexpectedVirtualElement({
17291             foreignObject: c,
17292             parentVnode: {
17293                 tagName: tag,
17294                 properties: props
17295             }
17296         });
17297     }
17298 }
17299
17300 function transformProperties(props) {
17301     for (var propName in props) {
17302         if (props.hasOwnProperty(propName)) {
17303             var value = props[propName];
17304
17305             if (isHook(value)) {
17306                 continue;
17307             }
17308
17309             if (propName.substr(0, 3) === 'ev-') {
17310                 // add ev-foo support
17311                 props[propName] = evHook(value);
17312             }
17313         }
17314     }
17315 }
17316
17317 function isChild(x) {
17318     return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
17319 }
17320
17321 function isChildren(x) {
17322     return typeof x === 'string' || isArray(x) || isChild(x);
17323 }
17324
17325 function UnexpectedVirtualElement(data) {
17326     var err = new Error();
17327
17328     err.type = 'virtual-hyperscript.unexpected.virtual-element';
17329     err.message = 'Unexpected virtual child passed to h().\n' +
17330         'Expected a VNode / Vthunk / VWidget / string but:\n' +
17331         'got:\n' +
17332         errorString(data.foreignObject) +
17333         '.\n' +
17334         'The parent vnode is:\n' +
17335         errorString(data.parentVnode)
17336         '\n' +
17337         'Suggested fix: change your `h(..., [ ... ])` callsite.';
17338     err.foreignObject = data.foreignObject;
17339     err.parentVnode = data.parentVnode;
17340
17341     return err;
17342 }
17343
17344 function errorString(obj) {
17345     try {
17346         return JSON.stringify(obj, null, '    ');
17347     } catch (e) {
17348         return String(obj);
17349     }
17350 }
17351
17352 },{"../vnode/is-thunk":243,"../vnode/is-vhook":244,"../vnode/is-vnode":245,"../vnode/is-vtext":246,"../vnode/is-widget":247,"../vnode/vnode.js":249,"../vnode/vtext.js":251,"./hooks/ev-hook.js":238,"./hooks/soft-set-hook.js":239,"./parse-tag.js":241,"x-is-array":272}],241:[function(require,module,exports){
17353 'use strict';
17354
17355 var split = require('browser-split');
17356
17357 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
17358 var notClassId = /^\.|#/;
17359
17360 module.exports = parseTag;
17361
17362 function parseTag(tag, props) {
17363     if (!tag) {
17364         return 'DIV';
17365     }
17366
17367     var noId = !(props.hasOwnProperty('id'));
17368
17369     var tagParts = split(tag, classIdSplit);
17370     var tagName = null;
17371
17372     if (notClassId.test(tagParts[1])) {
17373         tagName = 'DIV';
17374     }
17375
17376     var classes, part, type, i;
17377
17378     for (i = 0; i < tagParts.length; i++) {
17379         part = tagParts[i];
17380
17381         if (!part) {
17382             continue;
17383         }
17384
17385         type = part.charAt(0);
17386
17387         if (!tagName) {
17388             tagName = part;
17389         } else if (type === '.') {
17390             classes = classes || [];
17391             classes.push(part.substring(1, part.length));
17392         } else if (type === '#' && noId) {
17393             props.id = part.substring(1, part.length);
17394         }
17395     }
17396
17397     if (classes) {
17398         if (props.className) {
17399             classes.push(props.className);
17400         }
17401
17402         props.className = classes.join(' ');
17403     }
17404
17405     return props.namespace ? tagName : tagName.toUpperCase();
17406 }
17407
17408 },{"browser-split":5}],242:[function(require,module,exports){
17409 var isVNode = require("./is-vnode")
17410 var isVText = require("./is-vtext")
17411 var isWidget = require("./is-widget")
17412 var isThunk = require("./is-thunk")
17413
17414 module.exports = handleThunk
17415
17416 function handleThunk(a, b) {
17417     var renderedA = a
17418     var renderedB = b
17419
17420     if (isThunk(b)) {
17421         renderedB = renderThunk(b, a)
17422     }
17423
17424     if (isThunk(a)) {
17425         renderedA = renderThunk(a, null)
17426     }
17427
17428     return {
17429         a: renderedA,
17430         b: renderedB
17431     }
17432 }
17433
17434 function renderThunk(thunk, previous) {
17435     var renderedThunk = thunk.vnode
17436
17437     if (!renderedThunk) {
17438         renderedThunk = thunk.vnode = thunk.render(previous)
17439     }
17440
17441     if (!(isVNode(renderedThunk) ||
17442             isVText(renderedThunk) ||
17443             isWidget(renderedThunk))) {
17444         throw new Error("thunk did not return a valid node");
17445     }
17446
17447     return renderedThunk
17448 }
17449
17450 },{"./is-thunk":243,"./is-vnode":245,"./is-vtext":246,"./is-widget":247}],243:[function(require,module,exports){
17451 module.exports = isThunk
17452
17453 function isThunk(t) {
17454     return t && t.type === "Thunk"
17455 }
17456
17457 },{}],244:[function(require,module,exports){
17458 module.exports = isHook
17459
17460 function isHook(hook) {
17461     return hook &&
17462       (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
17463        typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
17464 }
17465
17466 },{}],245:[function(require,module,exports){
17467 var version = require("./version")
17468
17469 module.exports = isVirtualNode
17470
17471 function isVirtualNode(x) {
17472     return x && x.type === "VirtualNode" && x.version === version
17473 }
17474
17475 },{"./version":248}],246:[function(require,module,exports){
17476 var version = require("./version")
17477
17478 module.exports = isVirtualText
17479
17480 function isVirtualText(x) {
17481     return x && x.type === "VirtualText" && x.version === version
17482 }
17483
17484 },{"./version":248}],247:[function(require,module,exports){
17485 module.exports = isWidget
17486
17487 function isWidget(w) {
17488     return w && w.type === "Widget"
17489 }
17490
17491 },{}],248:[function(require,module,exports){
17492 module.exports = "2"
17493
17494 },{}],249:[function(require,module,exports){
17495 var version = require("./version")
17496 var isVNode = require("./is-vnode")
17497 var isWidget = require("./is-widget")
17498 var isThunk = require("./is-thunk")
17499 var isVHook = require("./is-vhook")
17500
17501 module.exports = VirtualNode
17502
17503 var noProperties = {}
17504 var noChildren = []
17505
17506 function VirtualNode(tagName, properties, children, key, namespace) {
17507     this.tagName = tagName
17508     this.properties = properties || noProperties
17509     this.children = children || noChildren
17510     this.key = key != null ? String(key) : undefined
17511     this.namespace = (typeof namespace === "string") ? namespace : null
17512
17513     var count = (children && children.length) || 0
17514     var descendants = 0
17515     var hasWidgets = false
17516     var hasThunks = false
17517     var descendantHooks = false
17518     var hooks
17519
17520     for (var propName in properties) {
17521         if (properties.hasOwnProperty(propName)) {
17522             var property = properties[propName]
17523             if (isVHook(property) && property.unhook) {
17524                 if (!hooks) {
17525                     hooks = {}
17526                 }
17527
17528                 hooks[propName] = property
17529             }
17530         }
17531     }
17532
17533     for (var i = 0; i < count; i++) {
17534         var child = children[i]
17535         if (isVNode(child)) {
17536             descendants += child.count || 0
17537
17538             if (!hasWidgets && child.hasWidgets) {
17539                 hasWidgets = true
17540             }
17541
17542             if (!hasThunks && child.hasThunks) {
17543                 hasThunks = true
17544             }
17545
17546             if (!descendantHooks && (child.hooks || child.descendantHooks)) {
17547                 descendantHooks = true
17548             }
17549         } else if (!hasWidgets && isWidget(child)) {
17550             if (typeof child.destroy === "function") {
17551                 hasWidgets = true
17552             }
17553         } else if (!hasThunks && isThunk(child)) {
17554             hasThunks = true;
17555         }
17556     }
17557
17558     this.count = count + descendants
17559     this.hasWidgets = hasWidgets
17560     this.hasThunks = hasThunks
17561     this.hooks = hooks
17562     this.descendantHooks = descendantHooks
17563 }
17564
17565 VirtualNode.prototype.version = version
17566 VirtualNode.prototype.type = "VirtualNode"
17567
17568 },{"./is-thunk":243,"./is-vhook":244,"./is-vnode":245,"./is-widget":247,"./version":248}],250:[function(require,module,exports){
17569 var version = require("./version")
17570
17571 VirtualPatch.NONE = 0
17572 VirtualPatch.VTEXT = 1
17573 VirtualPatch.VNODE = 2
17574 VirtualPatch.WIDGET = 3
17575 VirtualPatch.PROPS = 4
17576 VirtualPatch.ORDER = 5
17577 VirtualPatch.INSERT = 6
17578 VirtualPatch.REMOVE = 7
17579 VirtualPatch.THUNK = 8
17580
17581 module.exports = VirtualPatch
17582
17583 function VirtualPatch(type, vNode, patch) {
17584     this.type = Number(type)
17585     this.vNode = vNode
17586     this.patch = patch
17587 }
17588
17589 VirtualPatch.prototype.version = version
17590 VirtualPatch.prototype.type = "VirtualPatch"
17591
17592 },{"./version":248}],251:[function(require,module,exports){
17593 var version = require("./version")
17594
17595 module.exports = VirtualText
17596
17597 function VirtualText(text) {
17598     this.text = String(text)
17599 }
17600
17601 VirtualText.prototype.version = version
17602 VirtualText.prototype.type = "VirtualText"
17603
17604 },{"./version":248}],252:[function(require,module,exports){
17605 var isObject = require("is-object")
17606 var isHook = require("../vnode/is-vhook")
17607
17608 module.exports = diffProps
17609
17610 function diffProps(a, b) {
17611     var diff
17612
17613     for (var aKey in a) {
17614         if (!(aKey in b)) {
17615             diff = diff || {}
17616             diff[aKey] = undefined
17617         }
17618
17619         var aValue = a[aKey]
17620         var bValue = b[aKey]
17621
17622         if (aValue === bValue) {
17623             continue
17624         } else if (isObject(aValue) && isObject(bValue)) {
17625             if (getPrototype(bValue) !== getPrototype(aValue)) {
17626                 diff = diff || {}
17627                 diff[aKey] = bValue
17628             } else if (isHook(bValue)) {
17629                  diff = diff || {}
17630                  diff[aKey] = bValue
17631             } else {
17632                 var objectDiff = diffProps(aValue, bValue)
17633                 if (objectDiff) {
17634                     diff = diff || {}
17635                     diff[aKey] = objectDiff
17636                 }
17637             }
17638         } else {
17639             diff = diff || {}
17640             diff[aKey] = bValue
17641         }
17642     }
17643
17644     for (var bKey in b) {
17645         if (!(bKey in a)) {
17646             diff = diff || {}
17647             diff[bKey] = b[bKey]
17648         }
17649     }
17650
17651     return diff
17652 }
17653
17654 function getPrototype(value) {
17655   if (Object.getPrototypeOf) {
17656     return Object.getPrototypeOf(value)
17657   } else if (value.__proto__) {
17658     return value.__proto__
17659   } else if (value.constructor) {
17660     return value.constructor.prototype
17661   }
17662 }
17663
17664 },{"../vnode/is-vhook":244,"is-object":20}],253:[function(require,module,exports){
17665 var isArray = require("x-is-array")
17666
17667 var VPatch = require("../vnode/vpatch")
17668 var isVNode = require("../vnode/is-vnode")
17669 var isVText = require("../vnode/is-vtext")
17670 var isWidget = require("../vnode/is-widget")
17671 var isThunk = require("../vnode/is-thunk")
17672 var handleThunk = require("../vnode/handle-thunk")
17673
17674 var diffProps = require("./diff-props")
17675
17676 module.exports = diff
17677
17678 function diff(a, b) {
17679     var patch = { a: a }
17680     walk(a, b, patch, 0)
17681     return patch
17682 }
17683
17684 function walk(a, b, patch, index) {
17685     if (a === b) {
17686         return
17687     }
17688
17689     var apply = patch[index]
17690     var applyClear = false
17691
17692     if (isThunk(a) || isThunk(b)) {
17693         thunks(a, b, patch, index)
17694     } else if (b == null) {
17695
17696         // If a is a widget we will add a remove patch for it
17697         // Otherwise any child widgets/hooks must be destroyed.
17698         // This prevents adding two remove patches for a widget.
17699         if (!isWidget(a)) {
17700             clearState(a, patch, index)
17701             apply = patch[index]
17702         }
17703
17704         apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
17705     } else if (isVNode(b)) {
17706         if (isVNode(a)) {
17707             if (a.tagName === b.tagName &&
17708                 a.namespace === b.namespace &&
17709                 a.key === b.key) {
17710                 var propsPatch = diffProps(a.properties, b.properties)
17711                 if (propsPatch) {
17712                     apply = appendPatch(apply,
17713                         new VPatch(VPatch.PROPS, a, propsPatch))
17714                 }
17715                 apply = diffChildren(a, b, patch, apply, index)
17716             } else {
17717                 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
17718                 applyClear = true
17719             }
17720         } else {
17721             apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
17722             applyClear = true
17723         }
17724     } else if (isVText(b)) {
17725         if (!isVText(a)) {
17726             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
17727             applyClear = true
17728         } else if (a.text !== b.text) {
17729             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
17730         }
17731     } else if (isWidget(b)) {
17732         if (!isWidget(a)) {
17733             applyClear = true
17734         }
17735
17736         apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
17737     }
17738
17739     if (apply) {
17740         patch[index] = apply
17741     }
17742
17743     if (applyClear) {
17744         clearState(a, patch, index)
17745     }
17746 }
17747
17748 function diffChildren(a, b, patch, apply, index) {
17749     var aChildren = a.children
17750     var orderedSet = reorder(aChildren, b.children)
17751     var bChildren = orderedSet.children
17752
17753     var aLen = aChildren.length
17754     var bLen = bChildren.length
17755     var len = aLen > bLen ? aLen : bLen
17756
17757     for (var i = 0; i < len; i++) {
17758         var leftNode = aChildren[i]
17759         var rightNode = bChildren[i]
17760         index += 1
17761
17762         if (!leftNode) {
17763             if (rightNode) {
17764                 // Excess nodes in b need to be added
17765                 apply = appendPatch(apply,
17766                     new VPatch(VPatch.INSERT, null, rightNode))
17767             }
17768         } else {
17769             walk(leftNode, rightNode, patch, index)
17770         }
17771
17772         if (isVNode(leftNode) && leftNode.count) {
17773             index += leftNode.count
17774         }
17775     }
17776
17777     if (orderedSet.moves) {
17778         // Reorder nodes last
17779         apply = appendPatch(apply, new VPatch(
17780             VPatch.ORDER,
17781             a,
17782             orderedSet.moves
17783         ))
17784     }
17785
17786     return apply
17787 }
17788
17789 function clearState(vNode, patch, index) {
17790     // TODO: Make this a single walk, not two
17791     unhook(vNode, patch, index)
17792     destroyWidgets(vNode, patch, index)
17793 }
17794
17795 // Patch records for all destroyed widgets must be added because we need
17796 // a DOM node reference for the destroy function
17797 function destroyWidgets(vNode, patch, index) {
17798     if (isWidget(vNode)) {
17799         if (typeof vNode.destroy === "function") {
17800             patch[index] = appendPatch(
17801                 patch[index],
17802                 new VPatch(VPatch.REMOVE, vNode, null)
17803             )
17804         }
17805     } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
17806         var children = vNode.children
17807         var len = children.length
17808         for (var i = 0; i < len; i++) {
17809             var child = children[i]
17810             index += 1
17811
17812             destroyWidgets(child, patch, index)
17813
17814             if (isVNode(child) && child.count) {
17815                 index += child.count
17816             }
17817         }
17818     } else if (isThunk(vNode)) {
17819         thunks(vNode, null, patch, index)
17820     }
17821 }
17822
17823 // Create a sub-patch for thunks
17824 function thunks(a, b, patch, index) {
17825     var nodes = handleThunk(a, b)
17826     var thunkPatch = diff(nodes.a, nodes.b)
17827     if (hasPatches(thunkPatch)) {
17828         patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
17829     }
17830 }
17831
17832 function hasPatches(patch) {
17833     for (var index in patch) {
17834         if (index !== "a") {
17835             return true
17836         }
17837     }
17838
17839     return false
17840 }
17841
17842 // Execute hooks when two nodes are identical
17843 function unhook(vNode, patch, index) {
17844     if (isVNode(vNode)) {
17845         if (vNode.hooks) {
17846             patch[index] = appendPatch(
17847                 patch[index],
17848                 new VPatch(
17849                     VPatch.PROPS,
17850                     vNode,
17851                     undefinedKeys(vNode.hooks)
17852                 )
17853             )
17854         }
17855
17856         if (vNode.descendantHooks || vNode.hasThunks) {
17857             var children = vNode.children
17858             var len = children.length
17859             for (var i = 0; i < len; i++) {
17860                 var child = children[i]
17861                 index += 1
17862
17863                 unhook(child, patch, index)
17864
17865                 if (isVNode(child) && child.count) {
17866                     index += child.count
17867                 }
17868             }
17869         }
17870     } else if (isThunk(vNode)) {
17871         thunks(vNode, null, patch, index)
17872     }
17873 }
17874
17875 function undefinedKeys(obj) {
17876     var result = {}
17877
17878     for (var key in obj) {
17879         result[key] = undefined
17880     }
17881
17882     return result
17883 }
17884
17885 // List diff, naive left to right reordering
17886 function reorder(aChildren, bChildren) {
17887     // O(M) time, O(M) memory
17888     var bChildIndex = keyIndex(bChildren)
17889     var bKeys = bChildIndex.keys
17890     var bFree = bChildIndex.free
17891
17892     if (bFree.length === bChildren.length) {
17893         return {
17894             children: bChildren,
17895             moves: null
17896         }
17897     }
17898
17899     // O(N) time, O(N) memory
17900     var aChildIndex = keyIndex(aChildren)
17901     var aKeys = aChildIndex.keys
17902     var aFree = aChildIndex.free
17903
17904     if (aFree.length === aChildren.length) {
17905         return {
17906             children: bChildren,
17907             moves: null
17908         }
17909     }
17910
17911     // O(MAX(N, M)) memory
17912     var newChildren = []
17913
17914     var freeIndex = 0
17915     var freeCount = bFree.length
17916     var deletedItems = 0
17917
17918     // Iterate through a and match a node in b
17919     // O(N) time,
17920     for (var i = 0 ; i < aChildren.length; i++) {
17921         var aItem = aChildren[i]
17922         var itemIndex
17923
17924         if (aItem.key) {
17925             if (bKeys.hasOwnProperty(aItem.key)) {
17926                 // Match up the old keys
17927                 itemIndex = bKeys[aItem.key]
17928                 newChildren.push(bChildren[itemIndex])
17929
17930             } else {
17931                 // Remove old keyed items
17932                 itemIndex = i - deletedItems++
17933                 newChildren.push(null)
17934             }
17935         } else {
17936             // Match the item in a with the next free item in b
17937             if (freeIndex < freeCount) {
17938                 itemIndex = bFree[freeIndex++]
17939                 newChildren.push(bChildren[itemIndex])
17940             } else {
17941                 // There are no free items in b to match with
17942                 // the free items in a, so the extra free nodes
17943                 // are deleted.
17944                 itemIndex = i - deletedItems++
17945                 newChildren.push(null)
17946             }
17947         }
17948     }
17949
17950     var lastFreeIndex = freeIndex >= bFree.length ?
17951         bChildren.length :
17952         bFree[freeIndex]
17953
17954     // Iterate through b and append any new keys
17955     // O(M) time
17956     for (var j = 0; j < bChildren.length; j++) {
17957         var newItem = bChildren[j]
17958
17959         if (newItem.key) {
17960             if (!aKeys.hasOwnProperty(newItem.key)) {
17961                 // Add any new keyed items
17962                 // We are adding new items to the end and then sorting them
17963                 // in place. In future we should insert new items in place.
17964                 newChildren.push(newItem)
17965             }
17966         } else if (j >= lastFreeIndex) {
17967             // Add any leftover non-keyed items
17968             newChildren.push(newItem)
17969         }
17970     }
17971
17972     var simulate = newChildren.slice()
17973     var simulateIndex = 0
17974     var removes = []
17975     var inserts = []
17976     var simulateItem
17977
17978     for (var k = 0; k < bChildren.length;) {
17979         var wantedItem = bChildren[k]
17980         simulateItem = simulate[simulateIndex]
17981
17982         // remove items
17983         while (simulateItem === null && simulate.length) {
17984             removes.push(remove(simulate, simulateIndex, null))
17985             simulateItem = simulate[simulateIndex]
17986         }
17987
17988         if (!simulateItem || simulateItem.key !== wantedItem.key) {
17989             // if we need a key in this position...
17990             if (wantedItem.key) {
17991                 if (simulateItem && simulateItem.key) {
17992                     // if an insert doesn't put this key in place, it needs to move
17993                     if (bKeys[simulateItem.key] !== k + 1) {
17994                         removes.push(remove(simulate, simulateIndex, simulateItem.key))
17995                         simulateItem = simulate[simulateIndex]
17996                         // if the remove didn't put the wanted item in place, we need to insert it
17997                         if (!simulateItem || simulateItem.key !== wantedItem.key) {
17998                             inserts.push({key: wantedItem.key, to: k})
17999                         }
18000                         // items are matching, so skip ahead
18001                         else {
18002                             simulateIndex++
18003                         }
18004                     }
18005                     else {
18006                         inserts.push({key: wantedItem.key, to: k})
18007                     }
18008                 }
18009                 else {
18010                     inserts.push({key: wantedItem.key, to: k})
18011                 }
18012                 k++
18013             }
18014             // a key in simulate has no matching wanted key, remove it
18015             else if (simulateItem && simulateItem.key) {
18016                 removes.push(remove(simulate, simulateIndex, simulateItem.key))
18017             }
18018         }
18019         else {
18020             simulateIndex++
18021             k++
18022         }
18023     }
18024
18025     // remove all the remaining nodes from simulate
18026     while(simulateIndex < simulate.length) {
18027         simulateItem = simulate[simulateIndex]
18028         removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
18029     }
18030
18031     // If the only moves we have are deletes then we can just
18032     // let the delete patch remove these items.
18033     if (removes.length === deletedItems && !inserts.length) {
18034         return {
18035             children: newChildren,
18036             moves: null
18037         }
18038     }
18039
18040     return {
18041         children: newChildren,
18042         moves: {
18043             removes: removes,
18044             inserts: inserts
18045         }
18046     }
18047 }
18048
18049 function remove(arr, index, key) {
18050     arr.splice(index, 1)
18051
18052     return {
18053         from: index,
18054         key: key
18055     }
18056 }
18057
18058 function keyIndex(children) {
18059     var keys = {}
18060     var free = []
18061     var length = children.length
18062
18063     for (var i = 0; i < length; i++) {
18064         var child = children[i]
18065
18066         if (child.key) {
18067             keys[child.key] = i
18068         } else {
18069             free.push(i)
18070         }
18071     }
18072
18073     return {
18074         keys: keys,     // A hash of key name to index
18075         free: free      // An array of unkeyed item indices
18076     }
18077 }
18078
18079 function appendPatch(apply, patch) {
18080     if (apply) {
18081         if (isArray(apply)) {
18082             apply.push(patch)
18083         } else {
18084             apply = [apply, patch]
18085         }
18086
18087         return apply
18088     } else {
18089         return patch
18090     }
18091 }
18092
18093 },{"../vnode/handle-thunk":242,"../vnode/is-thunk":243,"../vnode/is-vnode":245,"../vnode/is-vtext":246,"../vnode/is-widget":247,"../vnode/vpatch":250,"./diff-props":252,"x-is-array":272}],254:[function(require,module,exports){
18094 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18095 /** @author Brian Cavalier */
18096 /** @author John Hann */
18097
18098 (function(define) { 'use strict';
18099 define(function (require) {
18100
18101         var makePromise = require('./makePromise');
18102         var Scheduler = require('./Scheduler');
18103         var async = require('./env').asap;
18104
18105         return makePromise({
18106                 scheduler: new Scheduler(async)
18107         });
18108
18109 });
18110 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
18111
18112 },{"./Scheduler":255,"./env":267,"./makePromise":269}],255:[function(require,module,exports){
18113 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18114 /** @author Brian Cavalier */
18115 /** @author John Hann */
18116
18117 (function(define) { 'use strict';
18118 define(function() {
18119
18120         // Credit to Twisol (https://github.com/Twisol) for suggesting
18121         // this type of extensible queue + trampoline approach for next-tick conflation.
18122
18123         /**
18124          * Async task scheduler
18125          * @param {function} async function to schedule a single async function
18126          * @constructor
18127          */
18128         function Scheduler(async) {
18129                 this._async = async;
18130                 this._running = false;
18131
18132                 this._queue = this;
18133                 this._queueLen = 0;
18134                 this._afterQueue = {};
18135                 this._afterQueueLen = 0;
18136
18137                 var self = this;
18138                 this.drain = function() {
18139                         self._drain();
18140                 };
18141         }
18142
18143         /**
18144          * Enqueue a task
18145          * @param {{ run:function }} task
18146          */
18147         Scheduler.prototype.enqueue = function(task) {
18148                 this._queue[this._queueLen++] = task;
18149                 this.run();
18150         };
18151
18152         /**
18153          * Enqueue a task to run after the main task queue
18154          * @param {{ run:function }} task
18155          */
18156         Scheduler.prototype.afterQueue = function(task) {
18157                 this._afterQueue[this._afterQueueLen++] = task;
18158                 this.run();
18159         };
18160
18161         Scheduler.prototype.run = function() {
18162                 if (!this._running) {
18163                         this._running = true;
18164                         this._async(this.drain);
18165                 }
18166         };
18167
18168         /**
18169          * Drain the handler queue entirely, and then the after queue
18170          */
18171         Scheduler.prototype._drain = function() {
18172                 var i = 0;
18173                 for (; i < this._queueLen; ++i) {
18174                         this._queue[i].run();
18175                         this._queue[i] = void 0;
18176                 }
18177
18178                 this._queueLen = 0;
18179                 this._running = false;
18180
18181                 for (i = 0; i < this._afterQueueLen; ++i) {
18182                         this._afterQueue[i].run();
18183                         this._afterQueue[i] = void 0;
18184                 }
18185
18186                 this._afterQueueLen = 0;
18187         };
18188
18189         return Scheduler;
18190
18191 });
18192 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18193
18194 },{}],256:[function(require,module,exports){
18195 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18196 /** @author Brian Cavalier */
18197 /** @author John Hann */
18198
18199 (function(define) { 'use strict';
18200 define(function() {
18201
18202         /**
18203          * Custom error type for promises rejected by promise.timeout
18204          * @param {string} message
18205          * @constructor
18206          */
18207         function TimeoutError (message) {
18208                 Error.call(this);
18209                 this.message = message;
18210                 this.name = TimeoutError.name;
18211                 if (typeof Error.captureStackTrace === 'function') {
18212                         Error.captureStackTrace(this, TimeoutError);
18213                 }
18214         }
18215
18216         TimeoutError.prototype = Object.create(Error.prototype);
18217         TimeoutError.prototype.constructor = TimeoutError;
18218
18219         return TimeoutError;
18220 });
18221 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18222 },{}],257:[function(require,module,exports){
18223 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18224 /** @author Brian Cavalier */
18225 /** @author John Hann */
18226
18227 (function(define) { 'use strict';
18228 define(function() {
18229
18230         makeApply.tryCatchResolve = tryCatchResolve;
18231
18232         return makeApply;
18233
18234         function makeApply(Promise, call) {
18235                 if(arguments.length < 2) {
18236                         call = tryCatchResolve;
18237                 }
18238
18239                 return apply;
18240
18241                 function apply(f, thisArg, args) {
18242                         var p = Promise._defer();
18243                         var l = args.length;
18244                         var params = new Array(l);
18245                         callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
18246
18247                         return p;
18248                 }
18249
18250                 function callAndResolve(c, h) {
18251                         if(c.i < 0) {
18252                                 return call(c.f, c.thisArg, c.params, h);
18253                         }
18254
18255                         var handler = Promise._handler(c.args[c.i]);
18256                         handler.fold(callAndResolveNext, c, void 0, h);
18257                 }
18258
18259                 function callAndResolveNext(c, x, h) {
18260                         c.params[c.i] = x;
18261                         c.i -= 1;
18262                         callAndResolve(c, h);
18263                 }
18264         }
18265
18266         function tryCatchResolve(f, thisArg, args, resolver) {
18267                 try {
18268                         resolver.resolve(f.apply(thisArg, args));
18269                 } catch(e) {
18270                         resolver.reject(e);
18271                 }
18272         }
18273
18274 });
18275 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18276
18277
18278
18279 },{}],258:[function(require,module,exports){
18280 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18281 /** @author Brian Cavalier */
18282 /** @author John Hann */
18283
18284 (function(define) { 'use strict';
18285 define(function(require) {
18286
18287         var state = require('../state');
18288         var applier = require('../apply');
18289
18290         return function array(Promise) {
18291
18292                 var applyFold = applier(Promise);
18293                 var toPromise = Promise.resolve;
18294                 var all = Promise.all;
18295
18296                 var ar = Array.prototype.reduce;
18297                 var arr = Array.prototype.reduceRight;
18298                 var slice = Array.prototype.slice;
18299
18300                 // Additional array combinators
18301
18302                 Promise.any = any;
18303                 Promise.some = some;
18304                 Promise.settle = settle;
18305
18306                 Promise.map = map;
18307                 Promise.filter = filter;
18308                 Promise.reduce = reduce;
18309                 Promise.reduceRight = reduceRight;
18310
18311                 /**
18312                  * When this promise fulfills with an array, do
18313                  * onFulfilled.apply(void 0, array)
18314                  * @param {function} onFulfilled function to apply
18315                  * @returns {Promise} promise for the result of applying onFulfilled
18316                  */
18317                 Promise.prototype.spread = function(onFulfilled) {
18318                         return this.then(all).then(function(array) {
18319                                 return onFulfilled.apply(this, array);
18320                         });
18321                 };
18322
18323                 return Promise;
18324
18325                 /**
18326                  * One-winner competitive race.
18327                  * Return a promise that will fulfill when one of the promises
18328                  * in the input array fulfills, or will reject when all promises
18329                  * have rejected.
18330                  * @param {array} promises
18331                  * @returns {Promise} promise for the first fulfilled value
18332                  */
18333                 function any(promises) {
18334                         var p = Promise._defer();
18335                         var resolver = p._handler;
18336                         var l = promises.length>>>0;
18337
18338                         var pending = l;
18339                         var errors = [];
18340
18341                         for (var h, x, i = 0; i < l; ++i) {
18342                                 x = promises[i];
18343                                 if(x === void 0 && !(i in promises)) {
18344                                         --pending;
18345                                         continue;
18346                                 }
18347
18348                                 h = Promise._handler(x);
18349                                 if(h.state() > 0) {
18350                                         resolver.become(h);
18351                                         Promise._visitRemaining(promises, i, h);
18352                                         break;
18353                                 } else {
18354                                         h.visit(resolver, handleFulfill, handleReject);
18355                                 }
18356                         }
18357
18358                         if(pending === 0) {
18359                                 resolver.reject(new RangeError('any(): array must not be empty'));
18360                         }
18361
18362                         return p;
18363
18364                         function handleFulfill(x) {
18365                                 /*jshint validthis:true*/
18366                                 errors = null;
18367                                 this.resolve(x); // this === resolver
18368                         }
18369
18370                         function handleReject(e) {
18371                                 /*jshint validthis:true*/
18372                                 if(this.resolved) { // this === resolver
18373                                         return;
18374                                 }
18375
18376                                 errors.push(e);
18377                                 if(--pending === 0) {
18378                                         this.reject(errors);
18379                                 }
18380                         }
18381                 }
18382
18383                 /**
18384                  * N-winner competitive race
18385                  * Return a promise that will fulfill when n input promises have
18386                  * fulfilled, or will reject when it becomes impossible for n
18387                  * input promises to fulfill (ie when promises.length - n + 1
18388                  * have rejected)
18389                  * @param {array} promises
18390                  * @param {number} n
18391                  * @returns {Promise} promise for the earliest n fulfillment values
18392                  *
18393                  * @deprecated
18394                  */
18395                 function some(promises, n) {
18396                         /*jshint maxcomplexity:7*/
18397                         var p = Promise._defer();
18398                         var resolver = p._handler;
18399
18400                         var results = [];
18401                         var errors = [];
18402
18403                         var l = promises.length>>>0;
18404                         var nFulfill = 0;
18405                         var nReject;
18406                         var x, i; // reused in both for() loops
18407
18408                         // First pass: count actual array items
18409                         for(i=0; i<l; ++i) {
18410                                 x = promises[i];
18411                                 if(x === void 0 && !(i in promises)) {
18412                                         continue;
18413                                 }
18414                                 ++nFulfill;
18415                         }
18416
18417                         // Compute actual goals
18418                         n = Math.max(n, 0);
18419                         nReject = (nFulfill - n + 1);
18420                         nFulfill = Math.min(n, nFulfill);
18421
18422                         if(n > nFulfill) {
18423                                 resolver.reject(new RangeError('some(): array must contain at least '
18424                                 + n + ' item(s), but had ' + nFulfill));
18425                         } else if(nFulfill === 0) {
18426                                 resolver.resolve(results);
18427                         }
18428
18429                         // Second pass: observe each array item, make progress toward goals
18430                         for(i=0; i<l; ++i) {
18431                                 x = promises[i];
18432                                 if(x === void 0 && !(i in promises)) {
18433                                         continue;
18434                                 }
18435
18436                                 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
18437                         }
18438
18439                         return p;
18440
18441                         function fulfill(x) {
18442                                 /*jshint validthis:true*/
18443                                 if(this.resolved) { // this === resolver
18444                                         return;
18445                                 }
18446
18447                                 results.push(x);
18448                                 if(--nFulfill === 0) {
18449                                         errors = null;
18450                                         this.resolve(results);
18451                                 }
18452                         }
18453
18454                         function reject(e) {
18455                                 /*jshint validthis:true*/
18456                                 if(this.resolved) { // this === resolver
18457                                         return;
18458                                 }
18459
18460                                 errors.push(e);
18461                                 if(--nReject === 0) {
18462                                         results = null;
18463                                         this.reject(errors);
18464                                 }
18465                         }
18466                 }
18467
18468                 /**
18469                  * Apply f to the value of each promise in a list of promises
18470                  * and return a new list containing the results.
18471                  * @param {array} promises
18472                  * @param {function(x:*, index:Number):*} f mapping function
18473                  * @returns {Promise}
18474                  */
18475                 function map(promises, f) {
18476                         return Promise._traverse(f, promises);
18477                 }
18478
18479                 /**
18480                  * Filter the provided array of promises using the provided predicate.  Input may
18481                  * contain promises and values
18482                  * @param {Array} promises array of promises and values
18483                  * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
18484                  *  Must return truthy (or promise for truthy) for items to retain.
18485                  * @returns {Promise} promise that will fulfill with an array containing all items
18486                  *  for which predicate returned truthy.
18487                  */
18488                 function filter(promises, predicate) {
18489                         var a = slice.call(promises);
18490                         return Promise._traverse(predicate, a).then(function(keep) {
18491                                 return filterSync(a, keep);
18492                         });
18493                 }
18494
18495                 function filterSync(promises, keep) {
18496                         // Safe because we know all promises have fulfilled if we've made it this far
18497                         var l = keep.length;
18498                         var filtered = new Array(l);
18499                         for(var i=0, j=0; i<l; ++i) {
18500                                 if(keep[i]) {
18501                                         filtered[j++] = Promise._handler(promises[i]).value;
18502                                 }
18503                         }
18504                         filtered.length = j;
18505                         return filtered;
18506
18507                 }
18508
18509                 /**
18510                  * Return a promise that will always fulfill with an array containing
18511                  * the outcome states of all input promises.  The returned promise
18512                  * will never reject.
18513                  * @param {Array} promises
18514                  * @returns {Promise} promise for array of settled state descriptors
18515                  */
18516                 function settle(promises) {
18517                         return all(promises.map(settleOne));
18518                 }
18519
18520                 function settleOne(p) {
18521                         // Optimize the case where we get an already-resolved when.js promise
18522                         //  by extracting its state:
18523                         var handler;
18524                         if (p instanceof Promise) {
18525                                 // This is our own Promise type and we can reach its handler internals:
18526                                 handler = p._handler.join();
18527                         }
18528                         if((handler && handler.state() === 0) || !handler) {
18529                                 // Either still pending, or not a Promise at all:
18530                                 return toPromise(p).then(state.fulfilled, state.rejected);
18531                         }
18532
18533                         // The promise is our own, but it is already resolved. Take a shortcut.
18534                         // Since we're not actually handling the resolution, we need to disable
18535                         // rejection reporting.
18536                         handler._unreport();
18537                         return state.inspect(handler);
18538                 }
18539
18540                 /**
18541                  * Traditional reduce function, similar to `Array.prototype.reduce()`, but
18542                  * input may contain promises and/or values, and reduceFunc
18543                  * may return either a value or a promise, *and* initialValue may
18544                  * be a promise for the starting value.
18545                  * @param {Array|Promise} promises array or promise for an array of anything,
18546                  *      may contain a mix of promises and values.
18547                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
18548                  * @returns {Promise} that will resolve to the final reduced value
18549                  */
18550                 function reduce(promises, f /*, initialValue */) {
18551                         return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
18552                                         : ar.call(promises, liftCombine(f));
18553                 }
18554
18555                 /**
18556                  * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
18557                  * input may contain promises and/or values, and reduceFunc
18558                  * may return either a value or a promise, *and* initialValue may
18559                  * be a promise for the starting value.
18560                  * @param {Array|Promise} promises array or promise for an array of anything,
18561                  *      may contain a mix of promises and values.
18562                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
18563                  * @returns {Promise} that will resolve to the final reduced value
18564                  */
18565                 function reduceRight(promises, f /*, initialValue */) {
18566                         return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
18567                                         : arr.call(promises, liftCombine(f));
18568                 }
18569
18570                 function liftCombine(f) {
18571                         return function(z, x, i) {
18572                                 return applyFold(f, void 0, [z,x,i]);
18573                         };
18574                 }
18575         };
18576
18577 });
18578 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18579
18580 },{"../apply":257,"../state":270}],259:[function(require,module,exports){
18581 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18582 /** @author Brian Cavalier */
18583 /** @author John Hann */
18584
18585 (function(define) { 'use strict';
18586 define(function() {
18587
18588         return function flow(Promise) {
18589
18590                 var resolve = Promise.resolve;
18591                 var reject = Promise.reject;
18592                 var origCatch = Promise.prototype['catch'];
18593
18594                 /**
18595                  * Handle the ultimate fulfillment value or rejection reason, and assume
18596                  * responsibility for all errors.  If an error propagates out of result
18597                  * or handleFatalError, it will be rethrown to the host, resulting in a
18598                  * loud stack track on most platforms and a crash on some.
18599                  * @param {function?} onResult
18600                  * @param {function?} onError
18601                  * @returns {undefined}
18602                  */
18603                 Promise.prototype.done = function(onResult, onError) {
18604                         this._handler.visit(this._handler.receiver, onResult, onError);
18605                 };
18606
18607                 /**
18608                  * Add Error-type and predicate matching to catch.  Examples:
18609                  * promise.catch(TypeError, handleTypeError)
18610                  *   .catch(predicate, handleMatchedErrors)
18611                  *   .catch(handleRemainingErrors)
18612                  * @param onRejected
18613                  * @returns {*}
18614                  */
18615                 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
18616                         if (arguments.length < 2) {
18617                                 return origCatch.call(this, onRejected);
18618                         }
18619
18620                         if(typeof onRejected !== 'function') {
18621                                 return this.ensure(rejectInvalidPredicate);
18622                         }
18623
18624                         return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
18625                 };
18626
18627                 /**
18628                  * Wraps the provided catch handler, so that it will only be called
18629                  * if the predicate evaluates truthy
18630                  * @param {?function} handler
18631                  * @param {function} predicate
18632                  * @returns {function} conditional catch handler
18633                  */
18634                 function createCatchFilter(handler, predicate) {
18635                         return function(e) {
18636                                 return evaluatePredicate(e, predicate)
18637                                         ? handler.call(this, e)
18638                                         : reject(e);
18639                         };
18640                 }
18641
18642                 /**
18643                  * Ensures that onFulfilledOrRejected will be called regardless of whether
18644                  * this promise is fulfilled or rejected.  onFulfilledOrRejected WILL NOT
18645                  * receive the promises' value or reason.  Any returned value will be disregarded.
18646                  * onFulfilledOrRejected may throw or return a rejected promise to signal
18647                  * an additional error.
18648                  * @param {function} handler handler to be called regardless of
18649                  *  fulfillment or rejection
18650                  * @returns {Promise}
18651                  */
18652                 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
18653                         if(typeof handler !== 'function') {
18654                                 return this;
18655                         }
18656
18657                         return this.then(function(x) {
18658                                 return runSideEffect(handler, this, identity, x);
18659                         }, function(e) {
18660                                 return runSideEffect(handler, this, reject, e);
18661                         });
18662                 };
18663
18664                 function runSideEffect (handler, thisArg, propagate, value) {
18665                         var result = handler.call(thisArg);
18666                         return maybeThenable(result)
18667                                 ? propagateValue(result, propagate, value)
18668                                 : propagate(value);
18669                 }
18670
18671                 function propagateValue (result, propagate, x) {
18672                         return resolve(result).then(function () {
18673                                 return propagate(x);
18674                         });
18675                 }
18676
18677                 /**
18678                  * Recover from a failure by returning a defaultValue.  If defaultValue
18679                  * is a promise, it's fulfillment value will be used.  If defaultValue is
18680                  * a promise that rejects, the returned promise will reject with the
18681                  * same reason.
18682                  * @param {*} defaultValue
18683                  * @returns {Promise} new promise
18684                  */
18685                 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
18686                         return this.then(void 0, function() {
18687                                 return defaultValue;
18688                         });
18689                 };
18690
18691                 /**
18692                  * Shortcut for .then(function() { return value; })
18693                  * @param  {*} value
18694                  * @return {Promise} a promise that:
18695                  *  - is fulfilled if value is not a promise, or
18696                  *  - if value is a promise, will fulfill with its value, or reject
18697                  *    with its reason.
18698                  */
18699                 Promise.prototype['yield'] = function(value) {
18700                         return this.then(function() {
18701                                 return value;
18702                         });
18703                 };
18704
18705                 /**
18706                  * Runs a side effect when this promise fulfills, without changing the
18707                  * fulfillment value.
18708                  * @param {function} onFulfilledSideEffect
18709                  * @returns {Promise}
18710                  */
18711                 Promise.prototype.tap = function(onFulfilledSideEffect) {
18712                         return this.then(onFulfilledSideEffect)['yield'](this);
18713                 };
18714
18715                 return Promise;
18716         };
18717
18718         function rejectInvalidPredicate() {
18719                 throw new TypeError('catch predicate must be a function');
18720         }
18721
18722         function evaluatePredicate(e, predicate) {
18723                 return isError(predicate) ? e instanceof predicate : predicate(e);
18724         }
18725
18726         function isError(predicate) {
18727                 return predicate === Error
18728                         || (predicate != null && predicate.prototype instanceof Error);
18729         }
18730
18731         function maybeThenable(x) {
18732                 return (typeof x === 'object' || typeof x === 'function') && x !== null;
18733         }
18734
18735         function identity(x) {
18736                 return x;
18737         }
18738
18739 });
18740 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18741
18742 },{}],260:[function(require,module,exports){
18743 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18744 /** @author Brian Cavalier */
18745 /** @author John Hann */
18746 /** @author Jeff Escalante */
18747
18748 (function(define) { 'use strict';
18749 define(function() {
18750
18751         return function fold(Promise) {
18752
18753                 Promise.prototype.fold = function(f, z) {
18754                         var promise = this._beget();
18755
18756                         this._handler.fold(function(z, x, to) {
18757                                 Promise._handler(z).fold(function(x, z, to) {
18758                                         to.resolve(f.call(this, z, x));
18759                                 }, x, this, to);
18760                         }, z, promise._handler.receiver, promise._handler);
18761
18762                         return promise;
18763                 };
18764
18765                 return Promise;
18766         };
18767
18768 });
18769 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18770
18771 },{}],261:[function(require,module,exports){
18772 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18773 /** @author Brian Cavalier */
18774 /** @author John Hann */
18775
18776 (function(define) { 'use strict';
18777 define(function(require) {
18778
18779         var inspect = require('../state').inspect;
18780
18781         return function inspection(Promise) {
18782
18783                 Promise.prototype.inspect = function() {
18784                         return inspect(Promise._handler(this));
18785                 };
18786
18787                 return Promise;
18788         };
18789
18790 });
18791 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18792
18793 },{"../state":270}],262:[function(require,module,exports){
18794 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18795 /** @author Brian Cavalier */
18796 /** @author John Hann */
18797
18798 (function(define) { 'use strict';
18799 define(function() {
18800
18801         return function generate(Promise) {
18802
18803                 var resolve = Promise.resolve;
18804
18805                 Promise.iterate = iterate;
18806                 Promise.unfold = unfold;
18807
18808                 return Promise;
18809
18810                 /**
18811                  * @deprecated Use github.com/cujojs/most streams and most.iterate
18812                  * Generate a (potentially infinite) stream of promised values:
18813                  * x, f(x), f(f(x)), etc. until condition(x) returns true
18814                  * @param {function} f function to generate a new x from the previous x
18815                  * @param {function} condition function that, given the current x, returns
18816                  *  truthy when the iterate should stop
18817                  * @param {function} handler function to handle the value produced by f
18818                  * @param {*|Promise} x starting value, may be a promise
18819                  * @return {Promise} the result of the last call to f before
18820                  *  condition returns true
18821                  */
18822                 function iterate(f, condition, handler, x) {
18823                         return unfold(function(x) {
18824                                 return [x, f(x)];
18825                         }, condition, handler, x);
18826                 }
18827
18828                 /**
18829                  * @deprecated Use github.com/cujojs/most streams and most.unfold
18830                  * Generate a (potentially infinite) stream of promised values
18831                  * by applying handler(generator(seed)) iteratively until
18832                  * condition(seed) returns true.
18833                  * @param {function} unspool function that generates a [value, newSeed]
18834                  *  given a seed.
18835                  * @param {function} condition function that, given the current seed, returns
18836                  *  truthy when the unfold should stop
18837                  * @param {function} handler function to handle the value produced by unspool
18838                  * @param x {*|Promise} starting value, may be a promise
18839                  * @return {Promise} the result of the last value produced by unspool before
18840                  *  condition returns true
18841                  */
18842                 function unfold(unspool, condition, handler, x) {
18843                         return resolve(x).then(function(seed) {
18844                                 return resolve(condition(seed)).then(function(done) {
18845                                         return done ? seed : resolve(unspool(seed)).spread(next);
18846                                 });
18847                         });
18848
18849                         function next(item, newSeed) {
18850                                 return resolve(handler(item)).then(function() {
18851                                         return unfold(unspool, condition, handler, newSeed);
18852                                 });
18853                         }
18854                 }
18855         };
18856
18857 });
18858 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18859
18860 },{}],263:[function(require,module,exports){
18861 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18862 /** @author Brian Cavalier */
18863 /** @author John Hann */
18864
18865 (function(define) { 'use strict';
18866 define(function() {
18867
18868         return function progress(Promise) {
18869
18870                 /**
18871                  * @deprecated
18872                  * Register a progress handler for this promise
18873                  * @param {function} onProgress
18874                  * @returns {Promise}
18875                  */
18876                 Promise.prototype.progress = function(onProgress) {
18877                         return this.then(void 0, void 0, onProgress);
18878                 };
18879
18880                 return Promise;
18881         };
18882
18883 });
18884 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18885
18886 },{}],264:[function(require,module,exports){
18887 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18888 /** @author Brian Cavalier */
18889 /** @author John Hann */
18890
18891 (function(define) { 'use strict';
18892 define(function(require) {
18893
18894         var env = require('../env');
18895         var TimeoutError = require('../TimeoutError');
18896
18897         function setTimeout(f, ms, x, y) {
18898                 return env.setTimer(function() {
18899                         f(x, y, ms);
18900                 }, ms);
18901         }
18902
18903         return function timed(Promise) {
18904                 /**
18905                  * Return a new promise whose fulfillment value is revealed only
18906                  * after ms milliseconds
18907                  * @param {number} ms milliseconds
18908                  * @returns {Promise}
18909                  */
18910                 Promise.prototype.delay = function(ms) {
18911                         var p = this._beget();
18912                         this._handler.fold(handleDelay, ms, void 0, p._handler);
18913                         return p;
18914                 };
18915
18916                 function handleDelay(ms, x, h) {
18917                         setTimeout(resolveDelay, ms, x, h);
18918                 }
18919
18920                 function resolveDelay(x, h) {
18921                         h.resolve(x);
18922                 }
18923
18924                 /**
18925                  * Return a new promise that rejects after ms milliseconds unless
18926                  * this promise fulfills earlier, in which case the returned promise
18927                  * fulfills with the same value.
18928                  * @param {number} ms milliseconds
18929                  * @param {Error|*=} reason optional rejection reason to use, defaults
18930                  *   to a TimeoutError if not provided
18931                  * @returns {Promise}
18932                  */
18933                 Promise.prototype.timeout = function(ms, reason) {
18934                         var p = this._beget();
18935                         var h = p._handler;
18936
18937                         var t = setTimeout(onTimeout, ms, reason, p._handler);
18938
18939                         this._handler.visit(h,
18940                                 function onFulfill(x) {
18941                                         env.clearTimer(t);
18942                                         this.resolve(x); // this = h
18943                                 },
18944                                 function onReject(x) {
18945                                         env.clearTimer(t);
18946                                         this.reject(x); // this = h
18947                                 },
18948                                 h.notify);
18949
18950                         return p;
18951                 };
18952
18953                 function onTimeout(reason, h, ms) {
18954                         var e = typeof reason === 'undefined'
18955                                 ? new TimeoutError('timed out after ' + ms + 'ms')
18956                                 : reason;
18957                         h.reject(e);
18958                 }
18959
18960                 return Promise;
18961         };
18962
18963 });
18964 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18965
18966 },{"../TimeoutError":256,"../env":267}],265:[function(require,module,exports){
18967 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18968 /** @author Brian Cavalier */
18969 /** @author John Hann */
18970
18971 (function(define) { 'use strict';
18972 define(function(require) {
18973
18974         var setTimer = require('../env').setTimer;
18975         var format = require('../format');
18976
18977         return function unhandledRejection(Promise) {
18978
18979                 var logError = noop;
18980                 var logInfo = noop;
18981                 var localConsole;
18982
18983                 if(typeof console !== 'undefined') {
18984                         // Alias console to prevent things like uglify's drop_console option from
18985                         // removing console.log/error. Unhandled rejections fall into the same
18986                         // category as uncaught exceptions, and build tools shouldn't silence them.
18987                         localConsole = console;
18988                         logError = typeof localConsole.error !== 'undefined'
18989                                 ? function (e) { localConsole.error(e); }
18990                                 : function (e) { localConsole.log(e); };
18991
18992                         logInfo = typeof localConsole.info !== 'undefined'
18993                                 ? function (e) { localConsole.info(e); }
18994                                 : function (e) { localConsole.log(e); };
18995                 }
18996
18997                 Promise.onPotentiallyUnhandledRejection = function(rejection) {
18998                         enqueue(report, rejection);
18999                 };
19000
19001                 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
19002                         enqueue(unreport, rejection);
19003                 };
19004
19005                 Promise.onFatalRejection = function(rejection) {
19006                         enqueue(throwit, rejection.value);
19007                 };
19008
19009                 var tasks = [];
19010                 var reported = [];
19011                 var running = null;
19012
19013                 function report(r) {
19014                         if(!r.handled) {
19015                                 reported.push(r);
19016                                 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
19017                         }
19018                 }
19019
19020                 function unreport(r) {
19021                         var i = reported.indexOf(r);
19022                         if(i >= 0) {
19023                                 reported.splice(i, 1);
19024                                 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
19025                         }
19026                 }
19027
19028                 function enqueue(f, x) {
19029                         tasks.push(f, x);
19030                         if(running === null) {
19031                                 running = setTimer(flush, 0);
19032                         }
19033                 }
19034
19035                 function flush() {
19036                         running = null;
19037                         while(tasks.length > 0) {
19038                                 tasks.shift()(tasks.shift());
19039                         }
19040                 }
19041
19042                 return Promise;
19043         };
19044
19045         function throwit(e) {
19046                 throw e;
19047         }
19048
19049         function noop() {}
19050
19051 });
19052 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
19053
19054 },{"../env":267,"../format":268}],266:[function(require,module,exports){
19055 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19056 /** @author Brian Cavalier */
19057 /** @author John Hann */
19058
19059 (function(define) { 'use strict';
19060 define(function() {
19061
19062         return function addWith(Promise) {
19063                 /**
19064                  * Returns a promise whose handlers will be called with `this` set to
19065                  * the supplied receiver.  Subsequent promises derived from the
19066                  * returned promise will also have their handlers called with receiver
19067                  * as `this`. Calling `with` with undefined or no arguments will return
19068                  * a promise whose handlers will again be called in the usual Promises/A+
19069                  * way (no `this`) thus safely undoing any previous `with` in the
19070                  * promise chain.
19071                  *
19072                  * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
19073                  * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
19074                  *
19075                  * @param {object} receiver `this` value for all handlers attached to
19076                  *  the returned promise.
19077                  * @returns {Promise}
19078                  */
19079                 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
19080                         var p = this._beget();
19081                         var child = p._handler;
19082                         child.receiver = receiver;
19083                         this._handler.chain(child, receiver);
19084                         return p;
19085                 };
19086
19087                 return Promise;
19088         };
19089
19090 });
19091 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19092
19093
19094 },{}],267:[function(require,module,exports){
19095 (function (process){
19096 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19097 /** @author Brian Cavalier */
19098 /** @author John Hann */
19099
19100 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
19101 (function(define) { 'use strict';
19102 define(function(require) {
19103         /*jshint maxcomplexity:6*/
19104
19105         // Sniff "best" async scheduling option
19106         // Prefer process.nextTick or MutationObserver, then check for
19107         // setTimeout, and finally vertx, since its the only env that doesn't
19108         // have setTimeout
19109
19110         var MutationObs;
19111         var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
19112
19113         // Default env
19114         var setTimer = function(f, ms) { return setTimeout(f, ms); };
19115         var clearTimer = function(t) { return clearTimeout(t); };
19116         var asap = function (f) { return capturedSetTimeout(f, 0); };
19117
19118         // Detect specific env
19119         if (isNode()) { // Node
19120                 asap = function (f) { return process.nextTick(f); };
19121
19122         } else if (MutationObs = hasMutationObserver()) { // Modern browser
19123                 asap = initMutationObserver(MutationObs);
19124
19125         } else if (!capturedSetTimeout) { // vert.x
19126                 var vertxRequire = require;
19127                 var vertx = vertxRequire('vertx');
19128                 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
19129                 clearTimer = vertx.cancelTimer;
19130                 asap = vertx.runOnLoop || vertx.runOnContext;
19131         }
19132
19133         return {
19134                 setTimer: setTimer,
19135                 clearTimer: clearTimer,
19136                 asap: asap
19137         };
19138
19139         function isNode () {
19140                 return typeof process !== 'undefined' &&
19141                         Object.prototype.toString.call(process) === '[object process]';
19142         }
19143
19144         function hasMutationObserver () {
19145             return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
19146                         (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
19147         }
19148
19149         function initMutationObserver(MutationObserver) {
19150                 var scheduled;
19151                 var node = document.createTextNode('');
19152                 var o = new MutationObserver(run);
19153                 o.observe(node, { characterData: true });
19154
19155                 function run() {
19156                         var f = scheduled;
19157                         scheduled = void 0;
19158                         f();
19159                 }
19160
19161                 var i = 0;
19162                 return function (f) {
19163                         scheduled = f;
19164                         node.data = (i ^= 1);
19165                 };
19166         }
19167 });
19168 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
19169
19170 }).call(this,require('_process'))
19171
19172 },{"_process":6}],268:[function(require,module,exports){
19173 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19174 /** @author Brian Cavalier */
19175 /** @author John Hann */
19176
19177 (function(define) { 'use strict';
19178 define(function() {
19179
19180         return {
19181                 formatError: formatError,
19182                 formatObject: formatObject,
19183                 tryStringify: tryStringify
19184         };
19185
19186         /**
19187          * Format an error into a string.  If e is an Error and has a stack property,
19188          * it's returned.  Otherwise, e is formatted using formatObject, with a
19189          * warning added about e not being a proper Error.
19190          * @param {*} e
19191          * @returns {String} formatted string, suitable for output to developers
19192          */
19193         function formatError(e) {
19194                 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
19195                 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
19196         }
19197
19198         /**
19199          * Format an object, detecting "plain" objects and running them through
19200          * JSON.stringify if possible.
19201          * @param {Object} o
19202          * @returns {string}
19203          */
19204         function formatObject(o) {
19205                 var s = String(o);
19206                 if(s === '[object Object]' && typeof JSON !== 'undefined') {
19207                         s = tryStringify(o, s);
19208                 }
19209                 return s;
19210         }
19211
19212         /**
19213          * Try to return the result of JSON.stringify(x).  If that fails, return
19214          * defaultValue
19215          * @param {*} x
19216          * @param {*} defaultValue
19217          * @returns {String|*} JSON.stringify(x) or defaultValue
19218          */
19219         function tryStringify(x, defaultValue) {
19220                 try {
19221                         return JSON.stringify(x);
19222                 } catch(e) {
19223                         return defaultValue;
19224                 }
19225         }
19226
19227 });
19228 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19229
19230 },{}],269:[function(require,module,exports){
19231 (function (process){
19232 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19233 /** @author Brian Cavalier */
19234 /** @author John Hann */
19235
19236 (function(define) { 'use strict';
19237 define(function() {
19238
19239         return function makePromise(environment) {
19240
19241                 var tasks = environment.scheduler;
19242                 var emitRejection = initEmitRejection();
19243
19244                 var objectCreate = Object.create ||
19245                         function(proto) {
19246                                 function Child() {}
19247                                 Child.prototype = proto;
19248                                 return new Child();
19249                         };
19250
19251                 /**
19252                  * Create a promise whose fate is determined by resolver
19253                  * @constructor
19254                  * @returns {Promise} promise
19255                  * @name Promise
19256                  */
19257                 function Promise(resolver, handler) {
19258                         this._handler = resolver === Handler ? handler : init(resolver);
19259                 }
19260
19261                 /**
19262                  * Run the supplied resolver
19263                  * @param resolver
19264                  * @returns {Pending}
19265                  */
19266                 function init(resolver) {
19267                         var handler = new Pending();
19268
19269                         try {
19270                                 resolver(promiseResolve, promiseReject, promiseNotify);
19271                         } catch (e) {
19272                                 promiseReject(e);
19273                         }
19274
19275                         return handler;
19276
19277                         /**
19278                          * Transition from pre-resolution state to post-resolution state, notifying
19279                          * all listeners of the ultimate fulfillment or rejection
19280                          * @param {*} x resolution value
19281                          */
19282                         function promiseResolve (x) {
19283                                 handler.resolve(x);
19284                         }
19285                         /**
19286                          * Reject this promise with reason, which will be used verbatim
19287                          * @param {Error|*} reason rejection reason, strongly suggested
19288                          *   to be an Error type
19289                          */
19290                         function promiseReject (reason) {
19291                                 handler.reject(reason);
19292                         }
19293
19294                         /**
19295                          * @deprecated
19296                          * Issue a progress event, notifying all progress listeners
19297                          * @param {*} x progress event payload to pass to all listeners
19298                          */
19299                         function promiseNotify (x) {
19300                                 handler.notify(x);
19301                         }
19302                 }
19303
19304                 // Creation
19305
19306                 Promise.resolve = resolve;
19307                 Promise.reject = reject;
19308                 Promise.never = never;
19309
19310                 Promise._defer = defer;
19311                 Promise._handler = getHandler;
19312
19313                 /**
19314                  * Returns a trusted promise. If x is already a trusted promise, it is
19315                  * returned, otherwise returns a new trusted Promise which follows x.
19316                  * @param  {*} x
19317                  * @return {Promise} promise
19318                  */
19319                 function resolve(x) {
19320                         return isPromise(x) ? x
19321                                 : new Promise(Handler, new Async(getHandler(x)));
19322                 }
19323
19324                 /**
19325                  * Return a reject promise with x as its reason (x is used verbatim)
19326                  * @param {*} x
19327                  * @returns {Promise} rejected promise
19328                  */
19329                 function reject(x) {
19330                         return new Promise(Handler, new Async(new Rejected(x)));
19331                 }
19332
19333                 /**
19334                  * Return a promise that remains pending forever
19335                  * @returns {Promise} forever-pending promise.
19336                  */
19337                 function never() {
19338                         return foreverPendingPromise; // Should be frozen
19339                 }
19340
19341                 /**
19342                  * Creates an internal {promise, resolver} pair
19343                  * @private
19344                  * @returns {Promise}
19345                  */
19346                 function defer() {
19347                         return new Promise(Handler, new Pending());
19348                 }
19349
19350                 // Transformation and flow control
19351
19352                 /**
19353                  * Transform this promise's fulfillment value, returning a new Promise
19354                  * for the transformed result.  If the promise cannot be fulfilled, onRejected
19355                  * is called with the reason.  onProgress *may* be called with updates toward
19356                  * this promise's fulfillment.
19357                  * @param {function=} onFulfilled fulfillment handler
19358                  * @param {function=} onRejected rejection handler
19359                  * @param {function=} onProgress @deprecated progress handler
19360                  * @return {Promise} new promise
19361                  */
19362                 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
19363                         var parent = this._handler;
19364                         var state = parent.join().state();
19365
19366                         if ((typeof onFulfilled !== 'function' && state > 0) ||
19367                                 (typeof onRejected !== 'function' && state < 0)) {
19368                                 // Short circuit: value will not change, simply share handler
19369                                 return new this.constructor(Handler, parent);
19370                         }
19371
19372                         var p = this._beget();
19373                         var child = p._handler;
19374
19375                         parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
19376
19377                         return p;
19378                 };
19379
19380                 /**
19381                  * If this promise cannot be fulfilled due to an error, call onRejected to
19382                  * handle the error. Shortcut for .then(undefined, onRejected)
19383                  * @param {function?} onRejected
19384                  * @return {Promise}
19385                  */
19386                 Promise.prototype['catch'] = function(onRejected) {
19387                         return this.then(void 0, onRejected);
19388                 };
19389
19390                 /**
19391                  * Creates a new, pending promise of the same type as this promise
19392                  * @private
19393                  * @returns {Promise}
19394                  */
19395                 Promise.prototype._beget = function() {
19396                         return begetFrom(this._handler, this.constructor);
19397                 };
19398
19399                 function begetFrom(parent, Promise) {
19400                         var child = new Pending(parent.receiver, parent.join().context);
19401                         return new Promise(Handler, child);
19402                 }
19403
19404                 // Array combinators
19405
19406                 Promise.all = all;
19407                 Promise.race = race;
19408                 Promise._traverse = traverse;
19409
19410                 /**
19411                  * Return a promise that will fulfill when all promises in the
19412                  * input array have fulfilled, or will reject when one of the
19413                  * promises rejects.
19414                  * @param {array} promises array of promises
19415                  * @returns {Promise} promise for array of fulfillment values
19416                  */
19417                 function all(promises) {
19418                         return traverseWith(snd, null, promises);
19419                 }
19420
19421                 /**
19422                  * Array<Promise<X>> -> Promise<Array<f(X)>>
19423                  * @private
19424                  * @param {function} f function to apply to each promise's value
19425                  * @param {Array} promises array of promises
19426                  * @returns {Promise} promise for transformed values
19427                  */
19428                 function traverse(f, promises) {
19429                         return traverseWith(tryCatch2, f, promises);
19430                 }
19431
19432                 function traverseWith(tryMap, f, promises) {
19433                         var handler = typeof f === 'function' ? mapAt : settleAt;
19434
19435                         var resolver = new Pending();
19436                         var pending = promises.length >>> 0;
19437                         var results = new Array(pending);
19438
19439                         for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
19440                                 x = promises[i];
19441
19442                                 if (x === void 0 && !(i in promises)) {
19443                                         --pending;
19444                                         continue;
19445                                 }
19446
19447                                 traverseAt(promises, handler, i, x, resolver);
19448                         }
19449
19450                         if(pending === 0) {
19451                                 resolver.become(new Fulfilled(results));
19452                         }
19453
19454                         return new Promise(Handler, resolver);
19455
19456                         function mapAt(i, x, resolver) {
19457                                 if(!resolver.resolved) {
19458                                         traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
19459                                 }
19460                         }
19461
19462                         function settleAt(i, x, resolver) {
19463                                 results[i] = x;
19464                                 if(--pending === 0) {
19465                                         resolver.become(new Fulfilled(results));
19466                                 }
19467                         }
19468                 }
19469
19470                 function traverseAt(promises, handler, i, x, resolver) {
19471                         if (maybeThenable(x)) {
19472                                 var h = getHandlerMaybeThenable(x);
19473                                 var s = h.state();
19474
19475                                 if (s === 0) {
19476                                         h.fold(handler, i, void 0, resolver);
19477                                 } else if (s > 0) {
19478                                         handler(i, h.value, resolver);
19479                                 } else {
19480                                         resolver.become(h);
19481                                         visitRemaining(promises, i+1, h);
19482                                 }
19483                         } else {
19484                                 handler(i, x, resolver);
19485                         }
19486                 }
19487
19488                 Promise._visitRemaining = visitRemaining;
19489                 function visitRemaining(promises, start, handler) {
19490                         for(var i=start; i<promises.length; ++i) {
19491                                 markAsHandled(getHandler(promises[i]), handler);
19492                         }
19493                 }
19494
19495                 function markAsHandled(h, handler) {
19496                         if(h === handler) {
19497                                 return;
19498                         }
19499
19500                         var s = h.state();
19501                         if(s === 0) {
19502                                 h.visit(h, void 0, h._unreport);
19503                         } else if(s < 0) {
19504                                 h._unreport();
19505                         }
19506                 }
19507
19508                 /**
19509                  * Fulfill-reject competitive race. Return a promise that will settle
19510                  * to the same state as the earliest input promise to settle.
19511                  *
19512                  * WARNING: The ES6 Promise spec requires that race()ing an empty array
19513                  * must return a promise that is pending forever.  This implementation
19514                  * returns a singleton forever-pending promise, the same singleton that is
19515                  * returned by Promise.never(), thus can be checked with ===
19516                  *
19517                  * @param {array} promises array of promises to race
19518                  * @returns {Promise} if input is non-empty, a promise that will settle
19519                  * to the same outcome as the earliest input promise to settle. if empty
19520                  * is empty, returns a promise that will never settle.
19521                  */
19522                 function race(promises) {
19523                         if(typeof promises !== 'object' || promises === null) {
19524                                 return reject(new TypeError('non-iterable passed to race()'));
19525                         }
19526
19527                         // Sigh, race([]) is untestable unless we return *something*
19528                         // that is recognizable without calling .then() on it.
19529                         return promises.length === 0 ? never()
19530                                  : promises.length === 1 ? resolve(promises[0])
19531                                  : runRace(promises);
19532                 }
19533
19534                 function runRace(promises) {
19535                         var resolver = new Pending();
19536                         var i, x, h;
19537                         for(i=0; i<promises.length; ++i) {
19538                                 x = promises[i];
19539                                 if (x === void 0 && !(i in promises)) {
19540                                         continue;
19541                                 }
19542
19543                                 h = getHandler(x);
19544                                 if(h.state() !== 0) {
19545                                         resolver.become(h);
19546                                         visitRemaining(promises, i+1, h);
19547                                         break;
19548                                 } else {
19549                                         h.visit(resolver, resolver.resolve, resolver.reject);
19550                                 }
19551                         }
19552                         return new Promise(Handler, resolver);
19553                 }
19554
19555                 // Promise internals
19556                 // Below this, everything is @private
19557
19558                 /**
19559                  * Get an appropriate handler for x, without checking for cycles
19560                  * @param {*} x
19561                  * @returns {object} handler
19562                  */
19563                 function getHandler(x) {
19564                         if(isPromise(x)) {
19565                                 return x._handler.join();
19566                         }
19567                         return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
19568                 }
19569
19570                 /**
19571                  * Get a handler for thenable x.
19572                  * NOTE: You must only call this if maybeThenable(x) == true
19573                  * @param {object|function|Promise} x
19574                  * @returns {object} handler
19575                  */
19576                 function getHandlerMaybeThenable(x) {
19577                         return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
19578                 }
19579
19580                 /**
19581                  * Get a handler for potentially untrusted thenable x
19582                  * @param {*} x
19583                  * @returns {object} handler
19584                  */
19585                 function getHandlerUntrusted(x) {
19586                         try {
19587                                 var untrustedThen = x.then;
19588                                 return typeof untrustedThen === 'function'
19589                                         ? new Thenable(untrustedThen, x)
19590                                         : new Fulfilled(x);
19591                         } catch(e) {
19592                                 return new Rejected(e);
19593                         }
19594                 }
19595
19596                 /**
19597                  * Handler for a promise that is pending forever
19598                  * @constructor
19599                  */
19600                 function Handler() {}
19601
19602                 Handler.prototype.when
19603                         = Handler.prototype.become
19604                         = Handler.prototype.notify // deprecated
19605                         = Handler.prototype.fail
19606                         = Handler.prototype._unreport
19607                         = Handler.prototype._report
19608                         = noop;
19609
19610                 Handler.prototype._state = 0;
19611
19612                 Handler.prototype.state = function() {
19613                         return this._state;
19614                 };
19615
19616                 /**
19617                  * Recursively collapse handler chain to find the handler
19618                  * nearest to the fully resolved value.
19619                  * @returns {object} handler nearest the fully resolved value
19620                  */
19621                 Handler.prototype.join = function() {
19622                         var h = this;
19623                         while(h.handler !== void 0) {
19624                                 h = h.handler;
19625                         }
19626                         return h;
19627                 };
19628
19629                 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
19630                         this.when({
19631                                 resolver: to,
19632                                 receiver: receiver,
19633                                 fulfilled: fulfilled,
19634                                 rejected: rejected,
19635                                 progress: progress
19636                         });
19637                 };
19638
19639                 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
19640                         this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
19641                 };
19642
19643                 Handler.prototype.fold = function(f, z, c, to) {
19644                         this.when(new Fold(f, z, c, to));
19645                 };
19646
19647                 /**
19648                  * Handler that invokes fail() on any handler it becomes
19649                  * @constructor
19650                  */
19651                 function FailIfRejected() {}
19652
19653                 inherit(Handler, FailIfRejected);
19654
19655                 FailIfRejected.prototype.become = function(h) {
19656                         h.fail();
19657                 };
19658
19659                 var failIfRejected = new FailIfRejected();
19660
19661                 /**
19662                  * Handler that manages a queue of consumers waiting on a pending promise
19663                  * @constructor
19664                  */
19665                 function Pending(receiver, inheritedContext) {
19666                         Promise.createContext(this, inheritedContext);
19667
19668                         this.consumers = void 0;
19669                         this.receiver = receiver;
19670                         this.handler = void 0;
19671                         this.resolved = false;
19672                 }
19673
19674                 inherit(Handler, Pending);
19675
19676                 Pending.prototype._state = 0;
19677
19678                 Pending.prototype.resolve = function(x) {
19679                         this.become(getHandler(x));
19680                 };
19681
19682                 Pending.prototype.reject = function(x) {
19683                         if(this.resolved) {
19684                                 return;
19685                         }
19686
19687                         this.become(new Rejected(x));
19688                 };
19689
19690                 Pending.prototype.join = function() {
19691                         if (!this.resolved) {
19692                                 return this;
19693                         }
19694
19695                         var h = this;
19696
19697                         while (h.handler !== void 0) {
19698                                 h = h.handler;
19699                                 if (h === this) {
19700                                         return this.handler = cycle();
19701                                 }
19702                         }
19703
19704                         return h;
19705                 };
19706
19707                 Pending.prototype.run = function() {
19708                         var q = this.consumers;
19709                         var handler = this.handler;
19710                         this.handler = this.handler.join();
19711                         this.consumers = void 0;
19712
19713                         for (var i = 0; i < q.length; ++i) {
19714                                 handler.when(q[i]);
19715                         }
19716                 };
19717
19718                 Pending.prototype.become = function(handler) {
19719                         if(this.resolved) {
19720                                 return;
19721                         }
19722
19723                         this.resolved = true;
19724                         this.handler = handler;
19725                         if(this.consumers !== void 0) {
19726                                 tasks.enqueue(this);
19727                         }
19728
19729                         if(this.context !== void 0) {
19730                                 handler._report(this.context);
19731                         }
19732                 };
19733
19734                 Pending.prototype.when = function(continuation) {
19735                         if(this.resolved) {
19736                                 tasks.enqueue(new ContinuationTask(continuation, this.handler));
19737                         } else {
19738                                 if(this.consumers === void 0) {
19739                                         this.consumers = [continuation];
19740                                 } else {
19741                                         this.consumers.push(continuation);
19742                                 }
19743                         }
19744                 };
19745
19746                 /**
19747                  * @deprecated
19748                  */
19749                 Pending.prototype.notify = function(x) {
19750                         if(!this.resolved) {
19751                                 tasks.enqueue(new ProgressTask(x, this));
19752                         }
19753                 };
19754
19755                 Pending.prototype.fail = function(context) {
19756                         var c = typeof context === 'undefined' ? this.context : context;
19757                         this.resolved && this.handler.join().fail(c);
19758                 };
19759
19760                 Pending.prototype._report = function(context) {
19761                         this.resolved && this.handler.join()._report(context);
19762                 };
19763
19764                 Pending.prototype._unreport = function() {
19765                         this.resolved && this.handler.join()._unreport();
19766                 };
19767
19768                 /**
19769                  * Wrap another handler and force it into a future stack
19770                  * @param {object} handler
19771                  * @constructor
19772                  */
19773                 function Async(handler) {
19774                         this.handler = handler;
19775                 }
19776
19777                 inherit(Handler, Async);
19778
19779                 Async.prototype.when = function(continuation) {
19780                         tasks.enqueue(new ContinuationTask(continuation, this));
19781                 };
19782
19783                 Async.prototype._report = function(context) {
19784                         this.join()._report(context);
19785                 };
19786
19787                 Async.prototype._unreport = function() {
19788                         this.join()._unreport();
19789                 };
19790
19791                 /**
19792                  * Handler that wraps an untrusted thenable and assimilates it in a future stack
19793                  * @param {function} then
19794                  * @param {{then: function}} thenable
19795                  * @constructor
19796                  */
19797                 function Thenable(then, thenable) {
19798                         Pending.call(this);
19799                         tasks.enqueue(new AssimilateTask(then, thenable, this));
19800                 }
19801
19802                 inherit(Pending, Thenable);
19803
19804                 /**
19805                  * Handler for a fulfilled promise
19806                  * @param {*} x fulfillment value
19807                  * @constructor
19808                  */
19809                 function Fulfilled(x) {
19810                         Promise.createContext(this);
19811                         this.value = x;
19812                 }
19813
19814                 inherit(Handler, Fulfilled);
19815
19816                 Fulfilled.prototype._state = 1;
19817
19818                 Fulfilled.prototype.fold = function(f, z, c, to) {
19819                         runContinuation3(f, z, this, c, to);
19820                 };
19821
19822                 Fulfilled.prototype.when = function(cont) {
19823                         runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
19824                 };
19825
19826                 var errorId = 0;
19827
19828                 /**
19829                  * Handler for a rejected promise
19830                  * @param {*} x rejection reason
19831                  * @constructor
19832                  */
19833                 function Rejected(x) {
19834                         Promise.createContext(this);
19835
19836                         this.id = ++errorId;
19837                         this.value = x;
19838                         this.handled = false;
19839                         this.reported = false;
19840
19841                         this._report();
19842                 }
19843
19844                 inherit(Handler, Rejected);
19845
19846                 Rejected.prototype._state = -1;
19847
19848                 Rejected.prototype.fold = function(f, z, c, to) {
19849                         to.become(this);
19850                 };
19851
19852                 Rejected.prototype.when = function(cont) {
19853                         if(typeof cont.rejected === 'function') {
19854                                 this._unreport();
19855                         }
19856                         runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
19857                 };
19858
19859                 Rejected.prototype._report = function(context) {
19860                         tasks.afterQueue(new ReportTask(this, context));
19861                 };
19862
19863                 Rejected.prototype._unreport = function() {
19864                         if(this.handled) {
19865                                 return;
19866                         }
19867                         this.handled = true;
19868                         tasks.afterQueue(new UnreportTask(this));
19869                 };
19870
19871                 Rejected.prototype.fail = function(context) {
19872                         this.reported = true;
19873                         emitRejection('unhandledRejection', this);
19874                         Promise.onFatalRejection(this, context === void 0 ? this.context : context);
19875                 };
19876
19877                 function ReportTask(rejection, context) {
19878                         this.rejection = rejection;
19879                         this.context = context;
19880                 }
19881
19882                 ReportTask.prototype.run = function() {
19883                         if(!this.rejection.handled && !this.rejection.reported) {
19884                                 this.rejection.reported = true;
19885                                 emitRejection('unhandledRejection', this.rejection) ||
19886                                         Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
19887                         }
19888                 };
19889
19890                 function UnreportTask(rejection) {
19891                         this.rejection = rejection;
19892                 }
19893
19894                 UnreportTask.prototype.run = function() {
19895                         if(this.rejection.reported) {
19896                                 emitRejection('rejectionHandled', this.rejection) ||
19897                                         Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
19898                         }
19899                 };
19900
19901                 // Unhandled rejection hooks
19902                 // By default, everything is a noop
19903
19904                 Promise.createContext
19905                         = Promise.enterContext
19906                         = Promise.exitContext
19907                         = Promise.onPotentiallyUnhandledRejection
19908                         = Promise.onPotentiallyUnhandledRejectionHandled
19909                         = Promise.onFatalRejection
19910                         = noop;
19911
19912                 // Errors and singletons
19913
19914                 var foreverPendingHandler = new Handler();
19915                 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
19916
19917                 function cycle() {
19918                         return new Rejected(new TypeError('Promise cycle'));
19919                 }
19920
19921                 // Task runners
19922
19923                 /**
19924                  * Run a single consumer
19925                  * @constructor
19926                  */
19927                 function ContinuationTask(continuation, handler) {
19928                         this.continuation = continuation;
19929                         this.handler = handler;
19930                 }
19931
19932                 ContinuationTask.prototype.run = function() {
19933                         this.handler.join().when(this.continuation);
19934                 };
19935
19936                 /**
19937                  * Run a queue of progress handlers
19938                  * @constructor
19939                  */
19940                 function ProgressTask(value, handler) {
19941                         this.handler = handler;
19942                         this.value = value;
19943                 }
19944
19945                 ProgressTask.prototype.run = function() {
19946                         var q = this.handler.consumers;
19947                         if(q === void 0) {
19948                                 return;
19949                         }
19950
19951                         for (var c, i = 0; i < q.length; ++i) {
19952                                 c = q[i];
19953                                 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
19954                         }
19955                 };
19956
19957                 /**
19958                  * Assimilate a thenable, sending it's value to resolver
19959                  * @param {function} then
19960                  * @param {object|function} thenable
19961                  * @param {object} resolver
19962                  * @constructor
19963                  */
19964                 function AssimilateTask(then, thenable, resolver) {
19965                         this._then = then;
19966                         this.thenable = thenable;
19967                         this.resolver = resolver;
19968                 }
19969
19970                 AssimilateTask.prototype.run = function() {
19971                         var h = this.resolver;
19972                         tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
19973
19974                         function _resolve(x) { h.resolve(x); }
19975                         function _reject(x)  { h.reject(x); }
19976                         function _notify(x)  { h.notify(x); }
19977                 };
19978
19979                 function tryAssimilate(then, thenable, resolve, reject, notify) {
19980                         try {
19981                                 then.call(thenable, resolve, reject, notify);
19982                         } catch (e) {
19983                                 reject(e);
19984                         }
19985                 }
19986
19987                 /**
19988                  * Fold a handler value with z
19989                  * @constructor
19990                  */
19991                 function Fold(f, z, c, to) {
19992                         this.f = f; this.z = z; this.c = c; this.to = to;
19993                         this.resolver = failIfRejected;
19994                         this.receiver = this;
19995                 }
19996
19997                 Fold.prototype.fulfilled = function(x) {
19998                         this.f.call(this.c, this.z, x, this.to);
19999                 };
20000
20001                 Fold.prototype.rejected = function(x) {
20002                         this.to.reject(x);
20003                 };
20004
20005                 Fold.prototype.progress = function(x) {
20006                         this.to.notify(x);
20007                 };
20008
20009                 // Other helpers
20010
20011                 /**
20012                  * @param {*} x
20013                  * @returns {boolean} true iff x is a trusted Promise
20014                  */
20015                 function isPromise(x) {
20016                         return x instanceof Promise;
20017                 }
20018
20019                 /**
20020                  * Test just enough to rule out primitives, in order to take faster
20021                  * paths in some code
20022                  * @param {*} x
20023                  * @returns {boolean} false iff x is guaranteed *not* to be a thenable
20024                  */
20025                 function maybeThenable(x) {
20026                         return (typeof x === 'object' || typeof x === 'function') && x !== null;
20027                 }
20028
20029                 function runContinuation1(f, h, receiver, next) {
20030                         if(typeof f !== 'function') {
20031                                 return next.become(h);
20032                         }
20033
20034                         Promise.enterContext(h);
20035                         tryCatchReject(f, h.value, receiver, next);
20036                         Promise.exitContext();
20037                 }
20038
20039                 function runContinuation3(f, x, h, receiver, next) {
20040                         if(typeof f !== 'function') {
20041                                 return next.become(h);
20042                         }
20043
20044                         Promise.enterContext(h);
20045                         tryCatchReject3(f, x, h.value, receiver, next);
20046                         Promise.exitContext();
20047                 }
20048
20049                 /**
20050                  * @deprecated
20051                  */
20052                 function runNotify(f, x, h, receiver, next) {
20053                         if(typeof f !== 'function') {
20054                                 return next.notify(x);
20055                         }
20056
20057                         Promise.enterContext(h);
20058                         tryCatchReturn(f, x, receiver, next);
20059                         Promise.exitContext();
20060                 }
20061
20062                 function tryCatch2(f, a, b) {
20063                         try {
20064                                 return f(a, b);
20065                         } catch(e) {
20066                                 return reject(e);
20067                         }
20068                 }
20069
20070                 /**
20071                  * Return f.call(thisArg, x), or if it throws return a rejected promise for
20072                  * the thrown exception
20073                  */
20074                 function tryCatchReject(f, x, thisArg, next) {
20075                         try {
20076                                 next.become(getHandler(f.call(thisArg, x)));
20077                         } catch(e) {
20078                                 next.become(new Rejected(e));
20079                         }
20080                 }
20081
20082                 /**
20083                  * Same as above, but includes the extra argument parameter.
20084                  */
20085                 function tryCatchReject3(f, x, y, thisArg, next) {
20086                         try {
20087                                 f.call(thisArg, x, y, next);
20088                         } catch(e) {
20089                                 next.become(new Rejected(e));
20090                         }
20091                 }
20092
20093                 /**
20094                  * @deprecated
20095                  * Return f.call(thisArg, x), or if it throws, *return* the exception
20096                  */
20097                 function tryCatchReturn(f, x, thisArg, next) {
20098                         try {
20099                                 next.notify(f.call(thisArg, x));
20100                         } catch(e) {
20101                                 next.notify(e);
20102                         }
20103                 }
20104
20105                 function inherit(Parent, Child) {
20106                         Child.prototype = objectCreate(Parent.prototype);
20107                         Child.prototype.constructor = Child;
20108                 }
20109
20110                 function snd(x, y) {
20111                         return y;
20112                 }
20113
20114                 function noop() {}
20115
20116                 function hasCustomEvent() {
20117                         if(typeof CustomEvent === 'function') {
20118                                 try {
20119                                         var ev = new CustomEvent('unhandledRejection');
20120                                         return ev instanceof CustomEvent;
20121                                 } catch (ignoredException) {}
20122                         }
20123                         return false;
20124                 }
20125
20126                 function hasInternetExplorerCustomEvent() {
20127                         if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
20128                                 try {
20129                                         // Try to create one event to make sure it's supported
20130                                         var ev = document.createEvent('CustomEvent');
20131                                         ev.initCustomEvent('eventType', false, true, {});
20132                                         return true;
20133                                 } catch (ignoredException) {}
20134                         }
20135                         return false;
20136                 }
20137
20138                 function initEmitRejection() {
20139                         /*global process, self, CustomEvent*/
20140                         if(typeof process !== 'undefined' && process !== null
20141                                 && typeof process.emit === 'function') {
20142                                 // Returning falsy here means to call the default
20143                                 // onPotentiallyUnhandledRejection API.  This is safe even in
20144                                 // browserify since process.emit always returns falsy in browserify:
20145                                 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
20146                                 return function(type, rejection) {
20147                                         return type === 'unhandledRejection'
20148                                                 ? process.emit(type, rejection.value, rejection)
20149                                                 : process.emit(type, rejection);
20150                                 };
20151                         } else if(typeof self !== 'undefined' && hasCustomEvent()) {
20152                                 return (function (self, CustomEvent) {
20153                                         return function (type, rejection) {
20154                                                 var ev = new CustomEvent(type, {
20155                                                         detail: {
20156                                                                 reason: rejection.value,
20157                                                                 key: rejection
20158                                                         },
20159                                                         bubbles: false,
20160                                                         cancelable: true
20161                                                 });
20162
20163                                                 return !self.dispatchEvent(ev);
20164                                         };
20165                                 }(self, CustomEvent));
20166                         } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
20167                                 return (function(self, document) {
20168                                         return function(type, rejection) {
20169                                                 var ev = document.createEvent('CustomEvent');
20170                                                 ev.initCustomEvent(type, false, true, {
20171                                                         reason: rejection.value,
20172                                                         key: rejection
20173                                                 });
20174
20175                                                 return !self.dispatchEvent(ev);
20176                                         };
20177                                 }(self, document));
20178                         }
20179
20180                         return noop;
20181                 }
20182
20183                 return Promise;
20184         };
20185 });
20186 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20187
20188 }).call(this,require('_process'))
20189
20190 },{"_process":6}],270:[function(require,module,exports){
20191 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20192 /** @author Brian Cavalier */
20193 /** @author John Hann */
20194
20195 (function(define) { 'use strict';
20196 define(function() {
20197
20198         return {
20199                 pending: toPendingState,
20200                 fulfilled: toFulfilledState,
20201                 rejected: toRejectedState,
20202                 inspect: inspect
20203         };
20204
20205         function toPendingState() {
20206                 return { state: 'pending' };
20207         }
20208
20209         function toRejectedState(e) {
20210                 return { state: 'rejected', reason: e };
20211         }
20212
20213         function toFulfilledState(x) {
20214                 return { state: 'fulfilled', value: x };
20215         }
20216
20217         function inspect(handler) {
20218                 var state = handler.state();
20219                 return state === 0 ? toPendingState()
20220                          : state > 0   ? toFulfilledState(handler.value)
20221                                        : toRejectedState(handler.value);
20222         }
20223
20224 });
20225 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20226
20227 },{}],271:[function(require,module,exports){
20228 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20229
20230 /**
20231  * Promises/A+ and when() implementation
20232  * when is part of the cujoJS family of libraries (http://cujojs.com/)
20233  * @author Brian Cavalier
20234  * @author John Hann
20235  */
20236 (function(define) { 'use strict';
20237 define(function (require) {
20238
20239         var timed = require('./lib/decorators/timed');
20240         var array = require('./lib/decorators/array');
20241         var flow = require('./lib/decorators/flow');
20242         var fold = require('./lib/decorators/fold');
20243         var inspect = require('./lib/decorators/inspect');
20244         var generate = require('./lib/decorators/iterate');
20245         var progress = require('./lib/decorators/progress');
20246         var withThis = require('./lib/decorators/with');
20247         var unhandledRejection = require('./lib/decorators/unhandledRejection');
20248         var TimeoutError = require('./lib/TimeoutError');
20249
20250         var Promise = [array, flow, fold, generate, progress,
20251                 inspect, withThis, timed, unhandledRejection]
20252                 .reduce(function(Promise, feature) {
20253                         return feature(Promise);
20254                 }, require('./lib/Promise'));
20255
20256         var apply = require('./lib/apply')(Promise);
20257
20258         // Public API
20259
20260         when.promise     = promise;              // Create a pending promise
20261         when.resolve     = Promise.resolve;      // Create a resolved promise
20262         when.reject      = Promise.reject;       // Create a rejected promise
20263
20264         when.lift        = lift;                 // lift a function to return promises
20265         when['try']      = attempt;              // call a function and return a promise
20266         when.attempt     = attempt;              // alias for when.try
20267
20268         when.iterate     = Promise.iterate;      // DEPRECATED (use cujojs/most streams) Generate a stream of promises
20269         when.unfold      = Promise.unfold;       // DEPRECATED (use cujojs/most streams) Generate a stream of promises
20270
20271         when.join        = join;                 // Join 2 or more promises
20272
20273         when.all         = all;                  // Resolve a list of promises
20274         when.settle      = settle;               // Settle a list of promises
20275
20276         when.any         = lift(Promise.any);    // One-winner race
20277         when.some        = lift(Promise.some);   // Multi-winner race
20278         when.race        = lift(Promise.race);   // First-to-settle race
20279
20280         when.map         = map;                  // Array.map() for promises
20281         when.filter      = filter;               // Array.filter() for promises
20282         when.reduce      = lift(Promise.reduce);       // Array.reduce() for promises
20283         when.reduceRight = lift(Promise.reduceRight);  // Array.reduceRight() for promises
20284
20285         when.isPromiseLike = isPromiseLike;      // Is something promise-like, aka thenable
20286
20287         when.Promise     = Promise;              // Promise constructor
20288         when.defer       = defer;                // Create a {promise, resolve, reject} tuple
20289
20290         // Error types
20291
20292         when.TimeoutError = TimeoutError;
20293
20294         /**
20295          * Get a trusted promise for x, or by transforming x with onFulfilled
20296          *
20297          * @param {*} x
20298          * @param {function?} onFulfilled callback to be called when x is
20299          *   successfully fulfilled.  If promiseOrValue is an immediate value, callback
20300          *   will be invoked immediately.
20301          * @param {function?} onRejected callback to be called when x is
20302          *   rejected.
20303          * @param {function?} onProgress callback to be called when progress updates
20304          *   are issued for x. @deprecated
20305          * @returns {Promise} a new promise that will fulfill with the return
20306          *   value of callback or errback or the completion value of promiseOrValue if
20307          *   callback and/or errback is not supplied.
20308          */
20309         function when(x, onFulfilled, onRejected, onProgress) {
20310                 var p = Promise.resolve(x);
20311                 if (arguments.length < 2) {
20312                         return p;
20313                 }
20314
20315                 return p.then(onFulfilled, onRejected, onProgress);
20316         }
20317
20318         /**
20319          * Creates a new promise whose fate is determined by resolver.
20320          * @param {function} resolver function(resolve, reject, notify)
20321          * @returns {Promise} promise whose fate is determine by resolver
20322          */
20323         function promise(resolver) {
20324                 return new Promise(resolver);
20325         }
20326
20327         /**
20328          * Lift the supplied function, creating a version of f that returns
20329          * promises, and accepts promises as arguments.
20330          * @param {function} f
20331          * @returns {Function} version of f that returns promises
20332          */
20333         function lift(f) {
20334                 return function() {
20335                         for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
20336                                 a[i] = arguments[i];
20337                         }
20338                         return apply(f, this, a);
20339                 };
20340         }
20341
20342         /**
20343          * Call f in a future turn, with the supplied args, and return a promise
20344          * for the result.
20345          * @param {function} f
20346          * @returns {Promise}
20347          */
20348         function attempt(f /*, args... */) {
20349                 /*jshint validthis:true */
20350                 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
20351                         a[i] = arguments[i+1];
20352                 }
20353                 return apply(f, this, a);
20354         }
20355
20356         /**
20357          * Creates a {promise, resolver} pair, either or both of which
20358          * may be given out safely to consumers.
20359          * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
20360          */
20361         function defer() {
20362                 return new Deferred();
20363         }
20364
20365         function Deferred() {
20366                 var p = Promise._defer();
20367
20368                 function resolve(x) { p._handler.resolve(x); }
20369                 function reject(x) { p._handler.reject(x); }
20370                 function notify(x) { p._handler.notify(x); }
20371
20372                 this.promise = p;
20373                 this.resolve = resolve;
20374                 this.reject = reject;
20375                 this.notify = notify;
20376                 this.resolver = { resolve: resolve, reject: reject, notify: notify };
20377         }
20378
20379         /**
20380          * Determines if x is promise-like, i.e. a thenable object
20381          * NOTE: Will return true for *any thenable object*, and isn't truly
20382          * safe, since it may attempt to access the `then` property of x (i.e.
20383          *  clever/malicious getters may do weird things)
20384          * @param {*} x anything
20385          * @returns {boolean} true if x is promise-like
20386          */
20387         function isPromiseLike(x) {
20388                 return x && typeof x.then === 'function';
20389         }
20390
20391         /**
20392          * Return a promise that will resolve only once all the supplied arguments
20393          * have resolved. The resolution value of the returned promise will be an array
20394          * containing the resolution values of each of the arguments.
20395          * @param {...*} arguments may be a mix of promises and values
20396          * @returns {Promise}
20397          */
20398         function join(/* ...promises */) {
20399                 return Promise.all(arguments);
20400         }
20401
20402         /**
20403          * Return a promise that will fulfill once all input promises have
20404          * fulfilled, or reject when any one input promise rejects.
20405          * @param {array|Promise} promises array (or promise for an array) of promises
20406          * @returns {Promise}
20407          */
20408         function all(promises) {
20409                 return when(promises, Promise.all);
20410         }
20411
20412         /**
20413          * Return a promise that will always fulfill with an array containing
20414          * the outcome states of all input promises.  The returned promise
20415          * will only reject if `promises` itself is a rejected promise.
20416          * @param {array|Promise} promises array (or promise for an array) of promises
20417          * @returns {Promise} promise for array of settled state descriptors
20418          */
20419         function settle(promises) {
20420                 return when(promises, Promise.settle);
20421         }
20422
20423         /**
20424          * Promise-aware array map function, similar to `Array.prototype.map()`,
20425          * but input array may contain promises or values.
20426          * @param {Array|Promise} promises array of anything, may contain promises and values
20427          * @param {function(x:*, index:Number):*} mapFunc map function which may
20428          *  return a promise or value
20429          * @returns {Promise} promise that will fulfill with an array of mapped values
20430          *  or reject if any input promise rejects.
20431          */
20432         function map(promises, mapFunc) {
20433                 return when(promises, function(promises) {
20434                         return Promise.map(promises, mapFunc);
20435                 });
20436         }
20437
20438         /**
20439          * Filter the provided array of promises using the provided predicate.  Input may
20440          * contain promises and values
20441          * @param {Array|Promise} promises array of promises and values
20442          * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
20443          *  Must return truthy (or promise for truthy) for items to retain.
20444          * @returns {Promise} promise that will fulfill with an array containing all items
20445          *  for which predicate returned truthy.
20446          */
20447         function filter(promises, predicate) {
20448                 return when(promises, function(promises) {
20449                         return Promise.filter(promises, predicate);
20450                 });
20451         }
20452
20453         return when;
20454 });
20455 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
20456
20457 },{"./lib/Promise":254,"./lib/TimeoutError":256,"./lib/apply":257,"./lib/decorators/array":258,"./lib/decorators/flow":259,"./lib/decorators/fold":260,"./lib/decorators/inspect":261,"./lib/decorators/iterate":262,"./lib/decorators/progress":263,"./lib/decorators/timed":264,"./lib/decorators/unhandledRejection":265,"./lib/decorators/with":266}],272:[function(require,module,exports){
20458 var nativeIsArray = Array.isArray
20459 var toString = Object.prototype.toString
20460
20461 module.exports = nativeIsArray || isArray
20462
20463 function isArray(obj) {
20464     return toString.call(obj) === "[object Array]"
20465 }
20466
20467 },{}],273:[function(require,module,exports){
20468 "use strict";
20469 Object.defineProperty(exports, "__esModule", { value: true });
20470 var APIv3_1 = require("./api/APIv3");
20471 exports.APIv3 = APIv3_1.APIv3;
20472 var ModelCreator_1 = require("./api/ModelCreator");
20473 exports.ModelCreator = ModelCreator_1.ModelCreator;
20474
20475 },{"./api/APIv3":286,"./api/ModelCreator":287}],274:[function(require,module,exports){
20476 "use strict";
20477 function __export(m) {
20478     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
20479 }
20480 Object.defineProperty(exports, "__esModule", { value: true });
20481 var Component_1 = require("./component/Component");
20482 exports.Component = Component_1.Component;
20483 var ComponentService_1 = require("./component/ComponentService");
20484 exports.ComponentService = ComponentService_1.ComponentService;
20485 var HandlerBase_1 = require("./component/utils/HandlerBase");
20486 exports.HandlerBase = HandlerBase_1.HandlerBase;
20487 var MeshFactory_1 = require("./component/utils/MeshFactory");
20488 exports.MeshFactory = MeshFactory_1.MeshFactory;
20489 var MeshScene_1 = require("./component/utils/MeshScene");
20490 exports.MeshScene = MeshScene_1.MeshScene;
20491 var MouseOperator_1 = require("./component/utils/MouseOperator");
20492 exports.MouseOperator = MouseOperator_1.MouseOperator;
20493 var AttributionComponent_1 = require("./component/AttributionComponent");
20494 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
20495 var BackgroundComponent_1 = require("./component/BackgroundComponent");
20496 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
20497 var BearingComponent_1 = require("./component/BearingComponent");
20498 exports.BearingComponent = BearingComponent_1.BearingComponent;
20499 var CacheComponent_1 = require("./component/CacheComponent");
20500 exports.CacheComponent = CacheComponent_1.CacheComponent;
20501 var CoverComponent_1 = require("./component/CoverComponent");
20502 exports.CoverComponent = CoverComponent_1.CoverComponent;
20503 var DebugComponent_1 = require("./component/DebugComponent");
20504 exports.DebugComponent = DebugComponent_1.DebugComponent;
20505 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
20506 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
20507 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
20508 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
20509 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
20510 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
20511 var ImageComponent_1 = require("./component/ImageComponent");
20512 exports.ImageComponent = ImageComponent_1.ImageComponent;
20513 var KeyboardComponent_1 = require("./component/keyboard/KeyboardComponent");
20514 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
20515 var KeyPlayHandler_1 = require("./component/keyboard/KeyPlayHandler");
20516 exports.KeyPlayHandler = KeyPlayHandler_1.KeyPlayHandler;
20517 var KeyZoomHandler_1 = require("./component/keyboard/KeyZoomHandler");
20518 exports.KeyZoomHandler = KeyZoomHandler_1.KeyZoomHandler;
20519 var KeySequenceNavigationHandler_1 = require("./component/keyboard/KeySequenceNavigationHandler");
20520 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler_1.KeySequenceNavigationHandler;
20521 var KeySpatialNavigationHandler_1 = require("./component/keyboard/KeySpatialNavigationHandler");
20522 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler_1.KeySpatialNavigationHandler;
20523 var LoadingComponent_1 = require("./component/LoadingComponent");
20524 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
20525 var Marker_1 = require("./component/marker/marker/Marker");
20526 exports.Marker = Marker_1.Marker;
20527 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
20528 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
20529 var MarkerScene_1 = require("./component/marker/MarkerScene");
20530 exports.MarkerScene = MarkerScene_1.MarkerScene;
20531 var MarkerSet_1 = require("./component/marker/MarkerSet");
20532 exports.MarkerSet = MarkerSet_1.MarkerSet;
20533 var MouseComponent_1 = require("./component/mouse/MouseComponent");
20534 exports.MouseComponent = MouseComponent_1.MouseComponent;
20535 var BounceHandler_1 = require("./component/mouse/BounceHandler");
20536 exports.BounceHandler = BounceHandler_1.BounceHandler;
20537 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
20538 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
20539 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
20540 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
20541 var EarthControlHandler_1 = require("./component/mouse/EarthControlHandler");
20542 exports.EarthControlHandler = EarthControlHandler_1.EarthControlHandler;
20543 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
20544 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
20545 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
20546 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
20547 var ImageBoundary = require("./component/mouse/ImageBoundary");
20548 exports.ImageBoundary = ImageBoundary;
20549 var Popup_1 = require("./component/popup/popup/Popup");
20550 exports.Popup = Popup_1.Popup;
20551 var PopupComponent_1 = require("./component/popup/PopupComponent");
20552 exports.PopupComponent = PopupComponent_1.PopupComponent;
20553 var NavigationComponent_1 = require("./component/NavigationComponent");
20554 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
20555 var RouteComponent_1 = require("./component/RouteComponent");
20556 exports.RouteComponent = RouteComponent_1.RouteComponent;
20557 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
20558 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
20559 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
20560 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
20561 var SequenceMode_1 = require("./component/sequence/SequenceMode");
20562 exports.SequenceMode = SequenceMode_1.SequenceMode;
20563 var SpatialDataCache_1 = require("./component/spatialdata/SpatialDataCache");
20564 exports.SpatialDataCache = SpatialDataCache_1.SpatialDataCache;
20565 var SpatialDataComponent_1 = require("./component/spatialdata/SpatialDataComponent");
20566 exports.SpatialDataComponent = SpatialDataComponent_1.SpatialDataComponent;
20567 var SpatialDataScene_1 = require("./component/spatialdata/SpatialDataScene");
20568 exports.SpatialDataScene = SpatialDataScene_1.SpatialDataScene;
20569 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
20570 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
20571 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
20572 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
20573 var Shaders_1 = require("./component/shaders/Shaders");
20574 exports.Shaders = Shaders_1.Shaders;
20575 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
20576 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
20577 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
20578 exports.CircleMarker = CircleMarker_1.CircleMarker;
20579 var SliderComponent_1 = require("./component/slider/SliderComponent");
20580 exports.SliderComponent = SliderComponent_1.SliderComponent;
20581 var SliderDOMRenderer_1 = require("./component/slider/SliderDOMRenderer");
20582 exports.SliderDOMRenderer = SliderDOMRenderer_1.SliderDOMRenderer;
20583 var SliderGLRenderer_1 = require("./component/slider/SliderGLRenderer");
20584 exports.SliderGLRenderer = SliderGLRenderer_1.SliderGLRenderer;
20585 var StatsComponent_1 = require("./component/StatsComponent");
20586 exports.StatsComponent = StatsComponent_1.StatsComponent;
20587 var TagHandlerBase_1 = require("./component/tag/handlers/TagHandlerBase");
20588 exports.TagHandlerBase = TagHandlerBase_1.TagHandlerBase;
20589 var CreateHandlerBase_1 = require("./component/tag/handlers/CreateHandlerBase");
20590 exports.CreateHandlerBase = CreateHandlerBase_1.CreateHandlerBase;
20591 var CreatePointHandler_1 = require("./component/tag/handlers/CreatePointHandler");
20592 exports.CreatePointHandler = CreatePointHandler_1.CreatePointHandler;
20593 var CreateVertexHandler_1 = require("./component/tag/handlers/CreateVertexHandler");
20594 exports.CreateVertexHandler = CreateVertexHandler_1.CreateVertexHandler;
20595 var CreatePolygonHandler_1 = require("./component/tag/handlers/CreatePolygonHandler");
20596 exports.CreatePolygonHandler = CreatePolygonHandler_1.CreatePolygonHandler;
20597 var CreateRectHandler_1 = require("./component/tag/handlers/CreateRectHandler");
20598 exports.CreateRectHandler = CreateRectHandler_1.CreateRectHandler;
20599 var CreateRectDragHandler_1 = require("./component/tag/handlers/CreateRectDragHandler");
20600 exports.CreateRectDragHandler = CreateRectDragHandler_1.CreateRectDragHandler;
20601 var EditVertexHandler_1 = require("./component/tag/handlers/EditVertexHandler");
20602 exports.EditVertexHandler = EditVertexHandler_1.EditVertexHandler;
20603 var Tag_1 = require("./component/tag/tag/Tag");
20604 exports.Tag = Tag_1.Tag;
20605 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
20606 exports.OutlineTag = OutlineTag_1.OutlineTag;
20607 var RenderTag_1 = require("./component/tag/tag/RenderTag");
20608 exports.RenderTag = RenderTag_1.RenderTag;
20609 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
20610 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
20611 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
20612 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
20613 var SpotTag_1 = require("./component/tag/tag/SpotTag");
20614 exports.SpotTag = SpotTag_1.SpotTag;
20615 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
20616 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
20617 var TagDomain_1 = require("./component/tag/tag/TagDomain");
20618 exports.TagDomain = TagDomain_1.TagDomain;
20619 var TagComponent_1 = require("./component/tag/TagComponent");
20620 exports.TagComponent = TagComponent_1.TagComponent;
20621 var TagCreator_1 = require("./component/tag/TagCreator");
20622 exports.TagCreator = TagCreator_1.TagCreator;
20623 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
20624 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
20625 var TagMode_1 = require("./component/tag/TagMode");
20626 exports.TagMode = TagMode_1.TagMode;
20627 var TagOperation_1 = require("./component/tag/TagOperation");
20628 exports.TagOperation = TagOperation_1.TagOperation;
20629 var TagScene_1 = require("./component/tag/TagScene");
20630 exports.TagScene = TagScene_1.TagScene;
20631 var TagSet_1 = require("./component/tag/TagSet");
20632 exports.TagSet = TagSet_1.TagSet;
20633 var Geometry_1 = require("./component/tag/geometry/Geometry");
20634 exports.Geometry = Geometry_1.Geometry;
20635 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
20636 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
20637 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
20638 exports.RectGeometry = RectGeometry_1.RectGeometry;
20639 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
20640 exports.PointGeometry = PointGeometry_1.PointGeometry;
20641 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
20642 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
20643 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
20644 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
20645 var ZoomComponent_1 = require("./component/zoom/ZoomComponent");
20646 exports.ZoomComponent = ZoomComponent_1.ZoomComponent;
20647 __export(require("./component/interfaces/interfaces"));
20648
20649 },{"./component/AttributionComponent":288,"./component/BackgroundComponent":289,"./component/BearingComponent":290,"./component/CacheComponent":291,"./component/Component":292,"./component/ComponentService":293,"./component/CoverComponent":294,"./component/DebugComponent":295,"./component/ImageComponent":296,"./component/LoadingComponent":297,"./component/NavigationComponent":298,"./component/RouteComponent":299,"./component/StatsComponent":300,"./component/direction/DirectionComponent":301,"./component/direction/DirectionDOMCalculator":302,"./component/direction/DirectionDOMRenderer":303,"./component/imageplane/ImagePlaneComponent":304,"./component/imageplane/ImagePlaneGLRenderer":305,"./component/interfaces/interfaces":308,"./component/keyboard/KeyPlayHandler":309,"./component/keyboard/KeySequenceNavigationHandler":310,"./component/keyboard/KeySpatialNavigationHandler":311,"./component/keyboard/KeyZoomHandler":312,"./component/keyboard/KeyboardComponent":313,"./component/marker/MarkerComponent":315,"./component/marker/MarkerScene":316,"./component/marker/MarkerSet":317,"./component/marker/marker/CircleMarker":318,"./component/marker/marker/Marker":319,"./component/marker/marker/SimpleMarker":320,"./component/mouse/BounceHandler":321,"./component/mouse/DoubleClickZoomHandler":322,"./component/mouse/DragPanHandler":323,"./component/mouse/EarthControlHandler":324,"./component/mouse/ImageBoundary":325,"./component/mouse/MouseComponent":326,"./component/mouse/ScrollZoomHandler":327,"./component/mouse/TouchZoomHandler":328,"./component/popup/PopupComponent":330,"./component/popup/popup/Popup":331,"./component/sequence/SequenceComponent":332,"./component/sequence/SequenceDOMRenderer":333,"./component/sequence/SequenceMode":334,"./component/shaders/Shaders":335,"./component/slider/SliderComponent":336,"./component/slider/SliderDOMRenderer":337,"./component/slider/SliderGLRenderer":338,"./component/spatialdata/SpatialDataCache":339,"./component/spatialdata/SpatialDataComponent":340,"./component/spatialdata/SpatialDataScene":341,"./component/tag/TagComponent":343,"./component/tag/TagCreator":344,"./component/tag/TagDOMRenderer":345,"./component/tag/TagMode":346,"./component/tag/TagOperation":347,"./component/tag/TagScene":348,"./component/tag/TagSet":349,"./component/tag/error/GeometryTagError":350,"./component/tag/geometry/Geometry":351,"./component/tag/geometry/PointGeometry":352,"./component/tag/geometry/PolygonGeometry":353,"./component/tag/geometry/RectGeometry":354,"./component/tag/geometry/VertexGeometry":355,"./component/tag/handlers/CreateHandlerBase":356,"./component/tag/handlers/CreatePointHandler":357,"./component/tag/handlers/CreatePolygonHandler":358,"./component/tag/handlers/CreateRectDragHandler":359,"./component/tag/handlers/CreateRectHandler":360,"./component/tag/handlers/CreateVertexHandler":361,"./component/tag/handlers/EditVertexHandler":362,"./component/tag/handlers/TagHandlerBase":363,"./component/tag/tag/OutlineCreateTag":364,"./component/tag/tag/OutlineRenderTag":365,"./component/tag/tag/OutlineTag":366,"./component/tag/tag/RenderTag":367,"./component/tag/tag/SpotRenderTag":368,"./component/tag/tag/SpotTag":369,"./component/tag/tag/Tag":370,"./component/tag/tag/TagDomain":371,"./component/utils/HandlerBase":372,"./component/utils/MeshFactory":373,"./component/utils/MeshScene":374,"./component/utils/MouseOperator":375,"./component/zoom/ZoomComponent":376}],275:[function(require,module,exports){
20650 "use strict";
20651 Object.defineProperty(exports, "__esModule", { value: true });
20652 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
20653 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
20654 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
20655 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
20656 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
20657 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
20658 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
20659 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
20660 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
20661 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
20662
20663 },{"./graph/edge/EdgeCalculator":398,"./graph/edge/EdgeCalculatorCoefficients":399,"./graph/edge/EdgeCalculatorDirections":400,"./graph/edge/EdgeCalculatorSettings":401,"./graph/edge/EdgeDirection":402}],276:[function(require,module,exports){
20664 "use strict";
20665 Object.defineProperty(exports, "__esModule", { value: true });
20666 var AbortMapillaryError_1 = require("./error/AbortMapillaryError");
20667 exports.AbortMapillaryError = AbortMapillaryError_1.AbortMapillaryError;
20668 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
20669 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
20670 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
20671 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
20672 var MapillaryError_1 = require("./error/MapillaryError");
20673 exports.MapillaryError = MapillaryError_1.MapillaryError;
20674
20675 },{"./error/AbortMapillaryError":377,"./error/ArgumentMapillaryError":378,"./error/GraphMapillaryError":379,"./error/MapillaryError":380}],277:[function(require,module,exports){
20676 "use strict";
20677 Object.defineProperty(exports, "__esModule", { value: true });
20678 var Camera_1 = require("./geo/Camera");
20679 exports.Camera = Camera_1.Camera;
20680 var GeoCoords_1 = require("./geo/GeoCoords");
20681 exports.GeoCoords = GeoCoords_1.GeoCoords;
20682 var ViewportCoords_1 = require("./geo/ViewportCoords");
20683 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
20684 var Spatial_1 = require("./geo/Spatial");
20685 exports.Spatial = Spatial_1.Spatial;
20686 var Transform_1 = require("./geo/Transform");
20687 exports.Transform = Transform_1.Transform;
20688 var Geo = require("./geo/Geo");
20689 exports.Geo = Geo;
20690 var Lines = require("./geo/Lines");
20691 exports.Lines = Lines;
20692
20693 },{"./geo/Camera":381,"./geo/Geo":382,"./geo/GeoCoords":383,"./geo/Lines":384,"./geo/Spatial":385,"./geo/Transform":386,"./geo/ViewportCoords":387}],278:[function(require,module,exports){
20694 "use strict";
20695 Object.defineProperty(exports, "__esModule", { value: true });
20696 var FilterCreator_1 = require("./graph/FilterCreator");
20697 exports.FilterCreator = FilterCreator_1.FilterCreator;
20698 var Graph_1 = require("./graph/Graph");
20699 exports.Graph = Graph_1.Graph;
20700 var GraphCalculator_1 = require("./graph/GraphCalculator");
20701 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
20702 var GraphMode_1 = require("./graph/GraphMode");
20703 exports.GraphMode = GraphMode_1.GraphMode;
20704 var GraphService_1 = require("./graph/GraphService");
20705 exports.GraphService = GraphService_1.GraphService;
20706 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
20707 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
20708 var MeshReader_1 = require("./graph/MeshReader");
20709 exports.MeshReader = MeshReader_1.MeshReader;
20710 var Node_1 = require("./graph/Node");
20711 exports.Node = Node_1.Node;
20712 var NodeCache_1 = require("./graph/NodeCache");
20713 exports.NodeCache = NodeCache_1.NodeCache;
20714 var Sequence_1 = require("./graph/Sequence");
20715 exports.Sequence = Sequence_1.Sequence;
20716
20717 },{"./graph/FilterCreator":388,"./graph/Graph":389,"./graph/GraphCalculator":390,"./graph/GraphMode":391,"./graph/GraphService":392,"./graph/ImageLoadingService":393,"./graph/MeshReader":394,"./graph/Node":395,"./graph/NodeCache":396,"./graph/Sequence":397}],279:[function(require,module,exports){
20718 "use strict";
20719 /**
20720  * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
20721  * @name Mapillary
20722  */
20723 function __export(m) {
20724     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
20725 }
20726 Object.defineProperty(exports, "__esModule", { value: true });
20727 __export(require("./Support"));
20728 var Edge_1 = require("./Edge");
20729 exports.EdgeDirection = Edge_1.EdgeDirection;
20730 var Error_1 = require("./Error");
20731 exports.AbortMapillaryError = Error_1.AbortMapillaryError;
20732 var Render_1 = require("./Render");
20733 exports.RenderMode = Render_1.RenderMode;
20734 var State_1 = require("./State");
20735 exports.TransitionMode = State_1.TransitionMode;
20736 var Viewer_1 = require("./Viewer");
20737 exports.Alignment = Viewer_1.Alignment;
20738 exports.ImageSize = Viewer_1.ImageSize;
20739 exports.Viewer = Viewer_1.Viewer;
20740 var Component_1 = require("./Component");
20741 exports.SliderMode = Component_1.SliderMode;
20742 var TagComponent = require("./component/tag/Tag");
20743 exports.TagComponent = TagComponent;
20744 var MarkerComponent = require("./component/marker/Marker");
20745 exports.MarkerComponent = MarkerComponent;
20746 var PopupComponent = require("./component/popup/Popup");
20747 exports.PopupComponent = PopupComponent;
20748
20749 },{"./Component":274,"./Edge":275,"./Error":276,"./Render":280,"./State":281,"./Support":282,"./Viewer":285,"./component/marker/Marker":314,"./component/popup/Popup":329,"./component/tag/Tag":342}],280:[function(require,module,exports){
20750 "use strict";
20751 Object.defineProperty(exports, "__esModule", { value: true });
20752 var DOMRenderer_1 = require("./render/DOMRenderer");
20753 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
20754 var GLRenderer_1 = require("./render/GLRenderer");
20755 exports.GLRenderer = GLRenderer_1.GLRenderer;
20756 var GLRenderStage_1 = require("./render/GLRenderStage");
20757 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
20758 var RenderCamera_1 = require("./render/RenderCamera");
20759 exports.RenderCamera = RenderCamera_1.RenderCamera;
20760 var RenderMode_1 = require("./render/RenderMode");
20761 exports.RenderMode = RenderMode_1.RenderMode;
20762 var RenderService_1 = require("./render/RenderService");
20763 exports.RenderService = RenderService_1.RenderService;
20764
20765 },{"./render/DOMRenderer":403,"./render/GLRenderStage":404,"./render/GLRenderer":405,"./render/RenderCamera":406,"./render/RenderMode":407,"./render/RenderService":408}],281:[function(require,module,exports){
20766 "use strict";
20767 Object.defineProperty(exports, "__esModule", { value: true });
20768 var FrameGenerator_1 = require("./state/FrameGenerator");
20769 exports.FrameGenerator = FrameGenerator_1.FrameGenerator;
20770 var RotationDelta_1 = require("./state/RotationDelta");
20771 exports.RotationDelta = RotationDelta_1.RotationDelta;
20772 var State_1 = require("./state/State");
20773 exports.State = State_1.State;
20774 var StateBase_1 = require("./state/states/StateBase");
20775 exports.StateBase = StateBase_1.StateBase;
20776 var StateContext_1 = require("./state/StateContext");
20777 exports.StateContext = StateContext_1.StateContext;
20778 var StateService_1 = require("./state/StateService");
20779 exports.StateService = StateService_1.StateService;
20780 var TransitionMode_1 = require("./state/TransitionMode");
20781 exports.TransitionMode = TransitionMode_1.TransitionMode;
20782 var EarthState_1 = require("./state/states/EarthState");
20783 exports.EarthState = EarthState_1.EarthState;
20784 var InteractiveStateBase_1 = require("./state/states/InteractiveStateBase");
20785 exports.InteractiveStateBase = InteractiveStateBase_1.InteractiveStateBase;
20786 var InteractiveWaitingState_1 = require("./state/states/InteractiveWaitingState");
20787 exports.InteractiveWaitingState = InteractiveWaitingState_1.InteractiveWaitingState;
20788 var TraversingState_1 = require("./state/states/TraversingState");
20789 exports.TraversingState = TraversingState_1.TraversingState;
20790 var WaitingState_1 = require("./state/states/WaitingState");
20791 exports.WaitingState = WaitingState_1.WaitingState;
20792
20793 },{"./state/FrameGenerator":409,"./state/RotationDelta":410,"./state/State":411,"./state/StateContext":412,"./state/StateService":413,"./state/TransitionMode":414,"./state/states/EarthState":415,"./state/states/InteractiveStateBase":416,"./state/states/InteractiveWaitingState":417,"./state/states/StateBase":418,"./state/states/TraversingState":419,"./state/states/WaitingState":420}],282:[function(require,module,exports){
20794 "use strict";
20795 Object.defineProperty(exports, "__esModule", { value: true });
20796 var support = require("./utils/Support");
20797 /**
20798  * Test whether the current browser supports the full
20799  * functionality of MapillaryJS.
20800  *
20801  * @description The full functionality includes WebGL rendering.
20802  *
20803  * @return {boolean}
20804  *
20805  * @example `var supported = Mapillary.isSupported();`
20806  */
20807 function isSupported() {
20808     return isFallbackSupported() &&
20809         support.isWebGLSupportedCached();
20810 }
20811 exports.isSupported = isSupported;
20812 /**
20813  * Test whether the current browser supports the fallback
20814  * functionality of MapillaryJS.
20815  *
20816  * @description The fallback functionality does not include WebGL
20817  * rendering, only 2D canvas rendering.
20818  *
20819  * @return {boolean}
20820  *
20821  * @example `var fallbackSupported = Mapillary.isFallbackSupported();`
20822  */
20823 function isFallbackSupported() {
20824     return support.isBrowser() &&
20825         support.isBlobSupported() &&
20826         support.isArraySupported() &&
20827         support.isFunctionSupported() &&
20828         support.isJSONSupported() &&
20829         support.isObjectSupported();
20830 }
20831 exports.isFallbackSupported = isFallbackSupported;
20832
20833 },{"./utils/Support":428}],283:[function(require,module,exports){
20834 "use strict";
20835 Object.defineProperty(exports, "__esModule", { value: true });
20836 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
20837 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
20838 var ImageTileStore_1 = require("./tiles/ImageTileStore");
20839 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
20840 var TextureProvider_1 = require("./tiles/TextureProvider");
20841 exports.TextureProvider = TextureProvider_1.TextureProvider;
20842 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
20843 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
20844
20845 },{"./tiles/ImageTileLoader":421,"./tiles/ImageTileStore":422,"./tiles/RegionOfInterestCalculator":423,"./tiles/TextureProvider":424}],284:[function(require,module,exports){
20846 "use strict";
20847 function __export(m) {
20848     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
20849 }
20850 Object.defineProperty(exports, "__esModule", { value: true });
20851 var DOM_1 = require("./utils/DOM");
20852 exports.DOM = DOM_1.DOM;
20853 var EventEmitter_1 = require("./utils/EventEmitter");
20854 exports.EventEmitter = EventEmitter_1.EventEmitter;
20855 var Settings_1 = require("./utils/Settings");
20856 exports.Settings = Settings_1.Settings;
20857 __export(require("./utils/Support"));
20858 var Urls_1 = require("./utils/Urls");
20859 exports.Urls = Urls_1.Urls;
20860
20861 },{"./utils/DOM":425,"./utils/EventEmitter":426,"./utils/Settings":427,"./utils/Support":428,"./utils/Urls":429}],285:[function(require,module,exports){
20862 "use strict";
20863 Object.defineProperty(exports, "__esModule", { value: true });
20864 var Alignment_1 = require("./viewer/Alignment");
20865 exports.Alignment = Alignment_1.Alignment;
20866 var CacheService_1 = require("./viewer/CacheService");
20867 exports.CacheService = CacheService_1.CacheService;
20868 var ComponentController_1 = require("./viewer/ComponentController");
20869 exports.ComponentController = ComponentController_1.ComponentController;
20870 var Container_1 = require("./viewer/Container");
20871 exports.Container = Container_1.Container;
20872 var Observer_1 = require("./viewer/Observer");
20873 exports.Observer = Observer_1.Observer;
20874 var ImageSize_1 = require("./viewer/ImageSize");
20875 exports.ImageSize = ImageSize_1.ImageSize;
20876 var KeyboardService_1 = require("./viewer/KeyboardService");
20877 exports.KeyboardService = KeyboardService_1.KeyboardService;
20878 var LoadingService_1 = require("./viewer/LoadingService");
20879 exports.LoadingService = LoadingService_1.LoadingService;
20880 var MouseService_1 = require("./viewer/MouseService");
20881 exports.MouseService = MouseService_1.MouseService;
20882 var Navigator_1 = require("./viewer/Navigator");
20883 exports.Navigator = Navigator_1.Navigator;
20884 var PlayService_1 = require("./viewer/PlayService");
20885 exports.PlayService = PlayService_1.PlayService;
20886 var Projection_1 = require("./viewer/Projection");
20887 exports.Projection = Projection_1.Projection;
20888 var SpriteService_1 = require("./viewer/SpriteService");
20889 exports.SpriteService = SpriteService_1.SpriteService;
20890 var TouchService_1 = require("./viewer/TouchService");
20891 exports.TouchService = TouchService_1.TouchService;
20892 var Viewer_1 = require("./viewer/Viewer");
20893 exports.Viewer = Viewer_1.Viewer;
20894
20895 },{"./viewer/Alignment":430,"./viewer/CacheService":431,"./viewer/ComponentController":432,"./viewer/Container":433,"./viewer/ImageSize":434,"./viewer/KeyboardService":435,"./viewer/LoadingService":436,"./viewer/MouseService":437,"./viewer/Navigator":438,"./viewer/Observer":439,"./viewer/PlayService":440,"./viewer/Projection":441,"./viewer/SpriteService":442,"./viewer/TouchService":443,"./viewer/Viewer":444}],286:[function(require,module,exports){
20896 "use strict";
20897 Object.defineProperty(exports, "__esModule", { value: true });
20898 var operators_1 = require("rxjs/operators");
20899 var rxjs_1 = require("rxjs");
20900 var API_1 = require("../API");
20901 /**
20902  * @class APIv3
20903  *
20904  * @classdesc Provides methods for access of API v3.
20905  */
20906 var APIv3 = /** @class */ (function () {
20907     /**
20908      * Create a new api v3 instance.
20909      *
20910      * @param {number} clientId - Client id for API requests.
20911      * @param {number} [token] - Optional bearer token for API requests of
20912      * protected resources.
20913      * @param {ModelCreator} [creator] - Optional model creator instance.
20914      */
20915     function APIv3(clientId, token, creator) {
20916         this._clientId = clientId;
20917         this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
20918         this._model = this._modelCreator.createModel(clientId, token);
20919         this._pageCount = 999;
20920         this._pathImageByKey = "imageByKey";
20921         this._pathImageCloseTo = "imageCloseTo";
20922         this._pathImagesByH = "imagesByH";
20923         this._pathImageViewAdd = "imageViewAdd";
20924         this._pathSequenceByKey = "sequenceByKey";
20925         this._pathSequenceViewAdd = "sequenceViewAdd";
20926         this._propertiesCore = [
20927             "cl",
20928             "l",
20929             "sequence_key",
20930         ];
20931         this._propertiesFill = [
20932             "captured_at",
20933             "captured_with_camera_uuid",
20934             "user",
20935             "organization_key",
20936             "private",
20937             "project",
20938         ];
20939         this._propertiesKey = [
20940             "key",
20941         ];
20942         this._propertiesSequence = [
20943             "keys",
20944         ];
20945         this._propertiesSpatial = [
20946             "atomic_scale",
20947             "ca",
20948             "calt",
20949             "cca",
20950             "cfocal",
20951             "ck1",
20952             "ck2",
20953             "gpano",
20954             "height",
20955             "merge_cc",
20956             "merge_version",
20957             "c_rotation",
20958             "orientation",
20959             "width",
20960         ];
20961         this._propertiesUser = [
20962             "username",
20963         ];
20964     }
20965     APIv3.prototype.imageByKeyFill$ = function (keys) {
20966         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
20967             this._pathImageByKey,
20968             keys,
20969             this._propertiesKey
20970                 .concat(this._propertiesFill)
20971                 .concat(this._propertiesSpatial),
20972             this._propertiesKey
20973                 .concat(this._propertiesUser)
20974         ])).pipe(operators_1.map(function (value) {
20975             if (!value) {
20976                 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
20977             }
20978             return value.json.imageByKey;
20979         })), this._pathImageByKey, keys);
20980     };
20981     APIv3.prototype.imageByKeyFull$ = function (keys) {
20982         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
20983             this._pathImageByKey,
20984             keys,
20985             this._propertiesKey
20986                 .concat(this._propertiesCore)
20987                 .concat(this._propertiesFill)
20988                 .concat(this._propertiesSpatial),
20989             this._propertiesKey
20990                 .concat(this._propertiesUser)
20991         ])).pipe(operators_1.map(function (value) {
20992             if (!value) {
20993                 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
20994             }
20995             return value.json.imageByKey;
20996         })), this._pathImageByKey, keys);
20997     };
20998     APIv3.prototype.imageCloseTo$ = function (lat, lon) {
20999         var lonLat = lon + ":" + lat;
21000         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
21001             this._pathImageCloseTo,
21002             [lonLat],
21003             this._propertiesKey
21004                 .concat(this._propertiesCore)
21005                 .concat(this._propertiesFill)
21006                 .concat(this._propertiesSpatial),
21007             this._propertiesKey
21008                 .concat(this._propertiesUser)
21009         ])).pipe(operators_1.map(function (value) {
21010             return value != null ? value.json.imageCloseTo[lonLat] : null;
21011         })), this._pathImageCloseTo, [lonLat]);
21012     };
21013     APIv3.prototype.imagesByH$ = function (hs) {
21014         var _this = this;
21015         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
21016             this._pathImagesByH,
21017             hs,
21018             { from: 0, to: this._pageCount },
21019             this._propertiesKey
21020                 .concat(this._propertiesCore)
21021         ])).pipe(operators_1.map(function (value) {
21022             if (!value) {
21023                 value = { json: { imagesByH: {} } };
21024                 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
21025                     var h = hs_1[_i];
21026                     value.json.imagesByH[h] = {};
21027                     for (var i = 0; i <= _this._pageCount; i++) {
21028                         value.json.imagesByH[h][i] = null;
21029                     }
21030                 }
21031             }
21032             return value.json.imagesByH;
21033         })), this._pathImagesByH, hs);
21034     };
21035     APIv3.prototype.imageViewAdd$ = function (keys) {
21036         return this._catchInvalidateCall$(this._wrapCallModelResponse$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
21037     };
21038     APIv3.prototype.invalidateImageByKey = function (keys) {
21039         this._invalidateGet(this._pathImageByKey, keys);
21040     };
21041     APIv3.prototype.invalidateImagesByH = function (hs) {
21042         this._invalidateGet(this._pathImagesByH, hs);
21043     };
21044     APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
21045         this._invalidateGet(this._pathSequenceByKey, sKeys);
21046     };
21047     APIv3.prototype.setToken = function (token) {
21048         this._model.invalidate([]);
21049         this._model = null;
21050         this._model = this._modelCreator.createModel(this._clientId, token);
21051     };
21052     APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
21053         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
21054             this._pathSequenceByKey,
21055             sequenceKeys,
21056             this._propertiesKey
21057                 .concat(this._propertiesSequence)
21058         ])).pipe(operators_1.map(function (value) {
21059             if (!value) {
21060                 value = { json: { sequenceByKey: {} } };
21061             }
21062             for (var _i = 0, sequenceKeys_1 = sequenceKeys; _i < sequenceKeys_1.length; _i++) {
21063                 var sequenceKey = sequenceKeys_1[_i];
21064                 if (!(sequenceKey in value.json.sequenceByKey)) {
21065                     console.warn("Sequence data missing (" + sequenceKey + ")");
21066                     value.json.sequenceByKey[sequenceKey] = { key: sequenceKey, keys: [] };
21067                 }
21068             }
21069             return value.json.sequenceByKey;
21070         })), this._pathSequenceByKey, sequenceKeys);
21071     };
21072     APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
21073         return this._catchInvalidateCall$(this._wrapCallModelResponse$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
21074     };
21075     Object.defineProperty(APIv3.prototype, "clientId", {
21076         get: function () {
21077             return this._clientId;
21078         },
21079         enumerable: true,
21080         configurable: true
21081     });
21082     APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
21083         var _this = this;
21084         return observable.pipe(operators_1.catchError(function (error) {
21085             _this._invalidateGet(path, paths);
21086             throw error;
21087         }));
21088     };
21089     APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
21090         var _this = this;
21091         return observable.pipe(operators_1.catchError(function (error) {
21092             _this._invalidateCall(path, paths);
21093             throw error;
21094         }));
21095     };
21096     APIv3.prototype._invalidateGet = function (path, paths) {
21097         this._model.invalidate([path, paths]);
21098     };
21099     APIv3.prototype._invalidateCall = function (path, paths) {
21100         this._model.invalidate([path], [paths]);
21101     };
21102     APIv3.prototype._wrapModelResponse$ = function (modelResponse) {
21103         return rxjs_1.Observable
21104             .create(function (subscriber) {
21105             modelResponse
21106                 .then(function (value) {
21107                 subscriber.next(value);
21108                 subscriber.complete();
21109             }, function (error) {
21110                 subscriber.error(error);
21111             });
21112         });
21113     };
21114     APIv3.prototype._wrapCallModelResponse$ = function (modelResponse) {
21115         return this._wrapModelResponse$(modelResponse).pipe(operators_1.map(function (value) {
21116             return;
21117         }));
21118     };
21119     return APIv3;
21120 }());
21121 exports.APIv3 = APIv3;
21122 exports.default = APIv3;
21123
21124 },{"../API":273,"rxjs":26,"rxjs/operators":224}],287:[function(require,module,exports){
21125 "use strict";
21126 Object.defineProperty(exports, "__esModule", { value: true });
21127 var falcor = require("falcor");
21128 var falcor_http_datasource_1 = require("falcor-http-datasource");
21129 var Utils_1 = require("../Utils");
21130 /**
21131  * @class ModelCreator
21132  *
21133  * @classdesc Creates API models.
21134  */
21135 var ModelCreator = /** @class */ (function () {
21136     function ModelCreator() {
21137     }
21138     /**
21139      * Creates a Falcor model.
21140      *
21141      * @description Max cache size will be set to 16 MB. Authorization
21142      * header will be added if bearer token is supplied.
21143      *
21144      * @param {number} clientId - Client id for API requests.
21145      * @param {number} [token] - Optional bearer token for API requests of
21146      * protected resources.
21147      * @returns {falcor.Model} Falcor model for HTTP requests.
21148      */
21149     ModelCreator.prototype.createModel = function (clientId, token) {
21150         var configuration = {
21151             crossDomain: true,
21152             withCredentials: false,
21153         };
21154         if (token != null) {
21155             configuration.headers = { "Authorization": "Bearer " + token };
21156         }
21157         return new falcor.Model({
21158             maxSize: 16 * 1024 * 1024,
21159             source: new falcor_http_datasource_1.default(Utils_1.Urls.falcorModel(clientId), configuration),
21160         });
21161     };
21162     return ModelCreator;
21163 }());
21164 exports.ModelCreator = ModelCreator;
21165 exports.default = ModelCreator;
21166
21167 },{"../Utils":284,"falcor":15,"falcor-http-datasource":10}],288:[function(require,module,exports){
21168 "use strict";
21169 var __extends = (this && this.__extends) || (function () {
21170     var extendStatics = function (d, b) {
21171         extendStatics = Object.setPrototypeOf ||
21172             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21173             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21174         return extendStatics(d, b);
21175     }
21176     return function (d, b) {
21177         extendStatics(d, b);
21178         function __() { this.constructor = d; }
21179         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21180     };
21181 })();
21182 Object.defineProperty(exports, "__esModule", { value: true });
21183 var rxjs_1 = require("rxjs");
21184 var operators_1 = require("rxjs/operators");
21185 var vd = require("virtual-dom");
21186 var Component_1 = require("../Component");
21187 var Utils_1 = require("../Utils");
21188 var AttributionComponent = /** @class */ (function (_super) {
21189     __extends(AttributionComponent, _super);
21190     function AttributionComponent(name, container, navigator) {
21191         return _super.call(this, name, container, navigator) || this;
21192     }
21193     AttributionComponent.prototype._activate = function () {
21194         var _this = this;
21195         this._disposable = rxjs_1.combineLatest(this._navigator.stateService.currentNode$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
21196             var node = _a[0], size = _a[1];
21197             return {
21198                 name: _this._name,
21199                 vnode: _this._getAttributionNode(node.username, node.key, node.capturedAt, size.width),
21200             };
21201         }))
21202             .subscribe(this._container.domRenderer.render$);
21203     };
21204     AttributionComponent.prototype._deactivate = function () {
21205         this._disposable.unsubscribe();
21206     };
21207     AttributionComponent.prototype._getDefaultConfiguration = function () {
21208         return {};
21209     };
21210     AttributionComponent.prototype._getAttributionNode = function (username, key, capturedAt, width) {
21211         var compact = width <= 640;
21212         var mapillaryIcon = vd.h("div.AttributionMapillaryLogo", []);
21213         var mapillaryLink = vd.h("a.AttributionIconContainer", { href: Utils_1.Urls.explore, target: "_blank" }, [mapillaryIcon]);
21214         var imageBy = compact ? "" + username : "image by " + username;
21215         var imageByContent = vd.h("div.AttributionUsername", { textContent: imageBy }, []);
21216         var date = new Date(capturedAt).toDateString().split(" ");
21217         var formatted = (date.length > 3 ?
21218             compact ?
21219                 [date[3]] :
21220                 [date[1], date[2] + ",", date[3]] :
21221             date).join(" ");
21222         var dateContent = vd.h("div.AttributionDate", { textContent: formatted }, []);
21223         var imageLink = vd.h("a.AttributionImageContainer", { href: Utils_1.Urls.exporeImage(key), target: "_blank" }, [imageByContent, dateContent]);
21224         var compactClass = compact ? ".AttributionCompact" : "";
21225         return vd.h("div.AttributionContainer" + compactClass, {}, [mapillaryLink, imageLink]);
21226     };
21227     AttributionComponent.componentName = "attribution";
21228     return AttributionComponent;
21229 }(Component_1.Component));
21230 exports.AttributionComponent = AttributionComponent;
21231 Component_1.ComponentService.register(AttributionComponent);
21232 exports.default = AttributionComponent;
21233
21234 },{"../Component":274,"../Utils":284,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],289:[function(require,module,exports){
21235 "use strict";
21236 var __extends = (this && this.__extends) || (function () {
21237     var extendStatics = function (d, b) {
21238         extendStatics = Object.setPrototypeOf ||
21239             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21240             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21241         return extendStatics(d, b);
21242     }
21243     return function (d, b) {
21244         extendStatics(d, b);
21245         function __() { this.constructor = d; }
21246         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21247     };
21248 })();
21249 Object.defineProperty(exports, "__esModule", { value: true });
21250 var vd = require("virtual-dom");
21251 var Component_1 = require("../Component");
21252 var BackgroundComponent = /** @class */ (function (_super) {
21253     __extends(BackgroundComponent, _super);
21254     function BackgroundComponent(name, container, navigator) {
21255         return _super.call(this, name, container, navigator) || this;
21256     }
21257     BackgroundComponent.prototype._activate = function () {
21258         this._container.domRenderer.render$
21259             .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given image.") });
21260     };
21261     BackgroundComponent.prototype._deactivate = function () {
21262         return;
21263     };
21264     BackgroundComponent.prototype._getDefaultConfiguration = function () {
21265         return {};
21266     };
21267     BackgroundComponent.prototype._getBackgroundNode = function (notice) {
21268         // todo: add condition for when to display the DOM node
21269         return vd.h("div.BackgroundWrapper", {}, [
21270             vd.h("p", { textContent: notice }, []),
21271         ]);
21272     };
21273     BackgroundComponent.componentName = "background";
21274     return BackgroundComponent;
21275 }(Component_1.Component));
21276 exports.BackgroundComponent = BackgroundComponent;
21277 Component_1.ComponentService.register(BackgroundComponent);
21278 exports.default = BackgroundComponent;
21279
21280 },{"../Component":274,"virtual-dom":230}],290:[function(require,module,exports){
21281 "use strict";
21282 var __extends = (this && this.__extends) || (function () {
21283     var extendStatics = function (d, b) {
21284         extendStatics = Object.setPrototypeOf ||
21285             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21286             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21287         return extendStatics(d, b);
21288     }
21289     return function (d, b) {
21290         extendStatics(d, b);
21291         function __() { this.constructor = d; }
21292         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21293     };
21294 })();
21295 Object.defineProperty(exports, "__esModule", { value: true });
21296 var operators_1 = require("rxjs/operators");
21297 var vd = require("virtual-dom");
21298 var Component_1 = require("../Component");
21299 var Geo_1 = require("../Geo");
21300 var BearingComponent = /** @class */ (function (_super) {
21301     __extends(BearingComponent, _super);
21302     function BearingComponent(name, container, navigator) {
21303         var _this = _super.call(this, name, container, navigator) || this;
21304         _this._spatial = new Geo_1.Spatial();
21305         _this._svgNamespace = "http://www.w3.org/2000/svg";
21306         _this._distinctThreshold = Math.PI / 360;
21307         return _this;
21308     }
21309     BearingComponent.prototype._activate = function () {
21310         var _this = this;
21311         var cameraBearingFov$ = this._container.renderService.renderCamera$.pipe(operators_1.map(function (rc) {
21312             var vFov = _this._spatial.degToRad(rc.perspective.fov);
21313             var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
21314                 Math.PI :
21315                 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
21316             return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
21317         }), operators_1.distinctUntilChanged(function (a1, a2) {
21318             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
21319                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
21320         }));
21321         this._renderSubscription = cameraBearingFov$.pipe(operators_1.map(function (_a) {
21322             var bearing = _a[0], fov = _a[1];
21323             var background = vd.h("div.BearingIndicatorBackground", {}, []);
21324             var backgroundCircle = vd.h("div.BearingIndicatorBackgroundCircle", {}, []);
21325             var north = _this._createNorth(bearing);
21326             var cameraSector = _this._createCircleSectorCompass(_this._createCircleSector(Math.max(Math.PI / 20, fov), "#FFF"));
21327             return {
21328                 name: _this._name,
21329                 vnode: vd.h("div.BearingIndicatorContainer", { oncontextmenu: function (event) { event.preventDefault(); } }, [
21330                     background,
21331                     backgroundCircle,
21332                     north,
21333                     cameraSector,
21334                 ]),
21335             };
21336         }))
21337             .subscribe(this._container.domRenderer.render$);
21338     };
21339     BearingComponent.prototype._deactivate = function () {
21340         this._renderSubscription.unsubscribe();
21341     };
21342     BearingComponent.prototype._getDefaultConfiguration = function () {
21343         return {};
21344     };
21345     BearingComponent.prototype._createCircleSectorCompass = function (cameraSector) {
21346         var group = vd.h("g", {
21347             attributes: { transform: "translate(1,1)" },
21348             namespace: this._svgNamespace,
21349         }, [cameraSector]);
21350         var svg = vd.h("svg", {
21351             attributes: { viewBox: "0 0 2 2" },
21352             namespace: this._svgNamespace,
21353             style: {
21354                 height: "30px",
21355                 left: "4px",
21356                 position: "absolute",
21357                 top: "4px",
21358                 width: "30px",
21359             },
21360         }, [group]);
21361         return svg;
21362     };
21363     BearingComponent.prototype._createCircleSector = function (fov, fill) {
21364         if (fov > 2 * Math.PI - Math.PI / 90) {
21365             return vd.h("circle", {
21366                 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
21367                 namespace: this._svgNamespace,
21368             }, []);
21369         }
21370         var arcStart = -Math.PI / 2 - fov / 2;
21371         var arcEnd = arcStart + fov;
21372         var startX = Math.cos(arcStart);
21373         var startY = Math.sin(arcStart);
21374         var endX = Math.cos(arcEnd);
21375         var endY = Math.sin(arcEnd);
21376         var largeArc = fov >= Math.PI ? 1 : 0;
21377         var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
21378         return vd.h("path", {
21379             attributes: { d: description, fill: fill },
21380             namespace: this._svgNamespace,
21381         }, []);
21382     };
21383     BearingComponent.prototype._createNorth = function (bearing) {
21384         var north = vd.h("div.BearingNorth", []);
21385         var container = vd.h("div.BearingNorthContainer", { style: { transform: "rotateZ(" + -bearing * 180 / Math.PI + "deg)" } }, [north]);
21386         return container;
21387     };
21388     BearingComponent.componentName = "bearing";
21389     return BearingComponent;
21390 }(Component_1.Component));
21391 exports.BearingComponent = BearingComponent;
21392 Component_1.ComponentService.register(BearingComponent);
21393 exports.default = BearingComponent;
21394
21395 },{"../Component":274,"../Geo":277,"rxjs/operators":224,"virtual-dom":230}],291:[function(require,module,exports){
21396 "use strict";
21397 var __extends = (this && this.__extends) || (function () {
21398     var extendStatics = function (d, b) {
21399         extendStatics = Object.setPrototypeOf ||
21400             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21401             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21402         return extendStatics(d, b);
21403     }
21404     return function (d, b) {
21405         extendStatics(d, b);
21406         function __() { this.constructor = d; }
21407         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21408     };
21409 })();
21410 Object.defineProperty(exports, "__esModule", { value: true });
21411 var rxjs_1 = require("rxjs");
21412 var operators_1 = require("rxjs/operators");
21413 var Edge_1 = require("../Edge");
21414 var Component_1 = require("../Component");
21415 var CacheComponent = /** @class */ (function (_super) {
21416     __extends(CacheComponent, _super);
21417     function CacheComponent(name, container, navigator) {
21418         return _super.call(this, name, container, navigator) || this;
21419     }
21420     /**
21421      * Set the cache depth.
21422      *
21423      * Configures the cache depth. The cache depth can be different for
21424      * different edge direction types.
21425      *
21426      * @param {ICacheDepth} depth - Cache depth structure.
21427      */
21428     CacheComponent.prototype.setDepth = function (depth) {
21429         this.configure({ depth: depth });
21430     };
21431     CacheComponent.prototype._activate = function () {
21432         var _this = this;
21433         this._sequenceSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
21434             return node.sequenceEdges$;
21435         }), operators_1.filter(function (status) {
21436             return status.cached;
21437         })), this._configuration$).pipe(operators_1.switchMap(function (nc) {
21438             var status = nc[0];
21439             var configuration = nc[1];
21440             var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
21441             var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
21442             var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
21443             return rxjs_1.merge(next$, prev$).pipe(operators_1.catchError(function (error, caught) {
21444                 console.error("Failed to cache sequence edges.", error);
21445                 return rxjs_1.empty();
21446             }));
21447         }))
21448             .subscribe(function () { });
21449         this._spatialSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
21450             return rxjs_1.combineLatest(rxjs_1.of(node), node.spatialEdges$.pipe(operators_1.filter(function (status) {
21451                 return status.cached;
21452             })));
21453         })), this._configuration$).pipe(operators_1.switchMap(function (_a) {
21454             var _b = _a[0], node = _b[0], edgeStatus = _b[1], configuration = _a[1];
21455             var edges = edgeStatus.edges;
21456             var depth = configuration.depth;
21457             var panoDepth = Math.max(0, Math.min(2, depth.pano));
21458             var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
21459             var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
21460             var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
21461             var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
21462             var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
21463             var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
21464             var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
21465             var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
21466             var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
21467             var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
21468             return rxjs_1.merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$).pipe(operators_1.catchError(function (error, caught) {
21469                 console.error("Failed to cache spatial edges.", error);
21470                 return rxjs_1.empty();
21471             }));
21472         }))
21473             .subscribe(function () { });
21474     };
21475     CacheComponent.prototype._deactivate = function () {
21476         this._sequenceSubscription.unsubscribe();
21477         this._spatialSubscription.unsubscribe();
21478     };
21479     CacheComponent.prototype._getDefaultConfiguration = function () {
21480         return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
21481     };
21482     CacheComponent.prototype._cache$ = function (edges, direction, depth) {
21483         var _this = this;
21484         return rxjs_1.zip(rxjs_1.of(edges), rxjs_1.of(depth)).pipe(operators_1.expand(function (ed) {
21485             var es = ed[0];
21486             var d = ed[1];
21487             var edgesDepths$ = [];
21488             if (d > 0) {
21489                 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
21490                     var edge = es_1[_i];
21491                     if (edge.data.direction === direction) {
21492                         edgesDepths$.push(rxjs_1.zip(_this._navigator.graphService.cacheNode$(edge.to).pipe(operators_1.mergeMap(function (n) {
21493                             return _this._nodeToEdges$(n, direction);
21494                         })), rxjs_1.of(d - 1)));
21495                     }
21496                 }
21497             }
21498             return rxjs_1.from(edgesDepths$).pipe(operators_1.mergeAll());
21499         }), operators_1.skip(1));
21500     };
21501     CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
21502         return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
21503             node.sequenceEdges$ :
21504             node.spatialEdges$).pipe(operators_1.first(function (status) {
21505             return status.cached;
21506         }), operators_1.map(function (status) {
21507             return status.edges;
21508         }));
21509     };
21510     CacheComponent.componentName = "cache";
21511     return CacheComponent;
21512 }(Component_1.Component));
21513 exports.CacheComponent = CacheComponent;
21514 Component_1.ComponentService.register(CacheComponent);
21515 exports.default = CacheComponent;
21516
21517 },{"../Component":274,"../Edge":275,"rxjs":26,"rxjs/operators":224}],292:[function(require,module,exports){
21518 "use strict";
21519 var __extends = (this && this.__extends) || (function () {
21520     var extendStatics = function (d, b) {
21521         extendStatics = Object.setPrototypeOf ||
21522             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21523             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21524         return extendStatics(d, b);
21525     }
21526     return function (d, b) {
21527         extendStatics(d, b);
21528         function __() { this.constructor = d; }
21529         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21530     };
21531 })();
21532 Object.defineProperty(exports, "__esModule", { value: true });
21533 var operators_1 = require("rxjs/operators");
21534 var rxjs_1 = require("rxjs");
21535 var Utils_1 = require("../Utils");
21536 var Component = /** @class */ (function (_super) {
21537     __extends(Component, _super);
21538     function Component(name, container, navigator) {
21539         var _this = _super.call(this) || this;
21540         _this._activated$ = new rxjs_1.BehaviorSubject(false);
21541         _this._configurationSubject$ = new rxjs_1.Subject();
21542         _this._activated = false;
21543         _this._container = container;
21544         _this._name = name;
21545         _this._navigator = navigator;
21546         _this._configuration$ =
21547             _this._configurationSubject$.pipe(operators_1.startWith(_this.defaultConfiguration), operators_1.scan(function (conf, newConf) {
21548                 for (var key in newConf) {
21549                     if (newConf.hasOwnProperty(key)) {
21550                         conf[key] = newConf[key];
21551                     }
21552                 }
21553                 return conf;
21554             }), operators_1.publishReplay(1), operators_1.refCount());
21555         _this._configuration$.subscribe(function () { });
21556         return _this;
21557     }
21558     Object.defineProperty(Component.prototype, "activated", {
21559         get: function () {
21560             return this._activated;
21561         },
21562         enumerable: true,
21563         configurable: true
21564     });
21565     Object.defineProperty(Component.prototype, "activated$", {
21566         /** @ignore */
21567         get: function () {
21568             return this._activated$;
21569         },
21570         enumerable: true,
21571         configurable: true
21572     });
21573     Object.defineProperty(Component.prototype, "defaultConfiguration", {
21574         /**
21575          * Get default configuration.
21576          *
21577          * @returns {TConfiguration} Default configuration for component.
21578          */
21579         get: function () {
21580             return this._getDefaultConfiguration();
21581         },
21582         enumerable: true,
21583         configurable: true
21584     });
21585     Object.defineProperty(Component.prototype, "configuration$", {
21586         /** @ignore */
21587         get: function () {
21588             return this._configuration$;
21589         },
21590         enumerable: true,
21591         configurable: true
21592     });
21593     Object.defineProperty(Component.prototype, "name", {
21594         /**
21595          * Get name.
21596          *
21597          * @description The name of the component. Used when interacting with the
21598          * component through the Viewer's API.
21599          */
21600         get: function () {
21601             return this._name;
21602         },
21603         enumerable: true,
21604         configurable: true
21605     });
21606     Component.prototype.activate = function (conf) {
21607         if (this._activated) {
21608             return;
21609         }
21610         if (conf !== undefined) {
21611             this._configurationSubject$.next(conf);
21612         }
21613         this._activated = true;
21614         this._activate();
21615         this._activated$.next(true);
21616     };
21617     Component.prototype.configure = function (conf) {
21618         this._configurationSubject$.next(conf);
21619     };
21620     Component.prototype.deactivate = function () {
21621         if (!this._activated) {
21622             return;
21623         }
21624         this._activated = false;
21625         this._deactivate();
21626         this._container.domRenderer.clear(this._name);
21627         this._container.glRenderer.clear(this._name);
21628         this._activated$.next(false);
21629     };
21630     /**
21631      * Detect the viewer's new width and height and resize the component's
21632      * rendered elements accordingly if applicable.
21633      *
21634      * @ignore
21635      */
21636     Component.prototype.resize = function () { return; };
21637     Component.componentName = "not_worthy";
21638     return Component;
21639 }(Utils_1.EventEmitter));
21640 exports.Component = Component;
21641 exports.default = Component;
21642
21643 },{"../Utils":284,"rxjs":26,"rxjs/operators":224}],293:[function(require,module,exports){
21644 "use strict";
21645 Object.defineProperty(exports, "__esModule", { value: true });
21646 var Error_1 = require("../Error");
21647 var ComponentService = /** @class */ (function () {
21648     function ComponentService(container, navigator) {
21649         this._components = {};
21650         for (var componentName in ComponentService.registeredComponents) {
21651             if (!ComponentService.registeredComponents.hasOwnProperty(componentName)) {
21652                 continue;
21653             }
21654             var component = ComponentService.registeredComponents[componentName];
21655             this._components[componentName] = {
21656                 active: false,
21657                 component: new component(componentName, container, navigator),
21658             };
21659         }
21660         this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
21661         this._coverComponent.activate();
21662         this._coverActivated = true;
21663     }
21664     ComponentService.register = function (component) {
21665         if (ComponentService.registeredComponents[component.componentName] === undefined) {
21666             ComponentService.registeredComponents[component.componentName] = component;
21667         }
21668     };
21669     ComponentService.registerCover = function (coverComponent) {
21670         ComponentService.registeredCoverComponent = coverComponent;
21671     };
21672     Object.defineProperty(ComponentService.prototype, "coverActivated", {
21673         get: function () {
21674             return this._coverActivated;
21675         },
21676         enumerable: true,
21677         configurable: true
21678     });
21679     ComponentService.prototype.activateCover = function () {
21680         if (this._coverActivated) {
21681             return;
21682         }
21683         this._coverActivated = true;
21684         for (var componentName in this._components) {
21685             if (!this._components.hasOwnProperty(componentName)) {
21686                 continue;
21687             }
21688             var component = this._components[componentName];
21689             if (component.active) {
21690                 component.component.deactivate();
21691             }
21692         }
21693     };
21694     ComponentService.prototype.deactivateCover = function () {
21695         if (!this._coverActivated) {
21696             return;
21697         }
21698         this._coverActivated = false;
21699         for (var componentName in this._components) {
21700             if (!this._components.hasOwnProperty(componentName)) {
21701                 continue;
21702             }
21703             var component = this._components[componentName];
21704             if (component.active) {
21705                 component.component.activate();
21706             }
21707         }
21708     };
21709     ComponentService.prototype.activate = function (name) {
21710         this._checkName(name);
21711         this._components[name].active = true;
21712         if (!this._coverActivated) {
21713             this.get(name).activate();
21714         }
21715     };
21716     ComponentService.prototype.configure = function (name, conf) {
21717         this._checkName(name);
21718         this.get(name).configure(conf);
21719     };
21720     ComponentService.prototype.deactivate = function (name) {
21721         this._checkName(name);
21722         this._components[name].active = false;
21723         if (!this._coverActivated) {
21724             this.get(name).deactivate();
21725         }
21726     };
21727     ComponentService.prototype.get = function (name) {
21728         return this._components[name].component;
21729     };
21730     ComponentService.prototype.getCover = function () {
21731         return this._coverComponent;
21732     };
21733     ComponentService.prototype._checkName = function (name) {
21734         if (!(name in this._components)) {
21735             throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
21736         }
21737     };
21738     ComponentService.registeredComponents = {};
21739     return ComponentService;
21740 }());
21741 exports.ComponentService = ComponentService;
21742 exports.default = ComponentService;
21743
21744 },{"../Error":276}],294:[function(require,module,exports){
21745 "use strict";
21746 var __extends = (this && this.__extends) || (function () {
21747     var extendStatics = function (d, b) {
21748         extendStatics = Object.setPrototypeOf ||
21749             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21750             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21751         return extendStatics(d, b);
21752     }
21753     return function (d, b) {
21754         extendStatics(d, b);
21755         function __() { this.constructor = d; }
21756         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21757     };
21758 })();
21759 Object.defineProperty(exports, "__esModule", { value: true });
21760 var rxjs_1 = require("rxjs");
21761 var operators_1 = require("rxjs/operators");
21762 var vd = require("virtual-dom");
21763 var Component_1 = require("../Component");
21764 var Utils_1 = require("../Utils");
21765 var Viewer_1 = require("../Viewer");
21766 var CoverComponent = /** @class */ (function (_super) {
21767     __extends(CoverComponent, _super);
21768     function CoverComponent(name, container, navigator) {
21769         return _super.call(this, name, container, navigator) || this;
21770     }
21771     CoverComponent.prototype._activate = function () {
21772         var _this = this;
21773         this._configuration$.pipe(operators_1.distinctUntilChanged(undefined, function (configuration) {
21774             return configuration.state;
21775         }), operators_1.switchMap(function (configuration) {
21776             return rxjs_1.combineLatest(rxjs_1.of(configuration.state), _this._navigator.stateService.currentNode$);
21777         }), operators_1.switchMap(function (_a) {
21778             var state = _a[0], node = _a[1];
21779             var keySrc$ = rxjs_1.combineLatest(rxjs_1.of(node.key), node.image$.pipe(operators_1.filter(function (image) {
21780                 return !!image;
21781             }), operators_1.map(function (image) {
21782                 return image.src;
21783             })));
21784             return state === Component_1.CoverState.Visible ? keySrc$.pipe(operators_1.first()) : keySrc$;
21785         }), operators_1.distinctUntilChanged(function (_a, _b) {
21786             var k1 = _a[0], s1 = _a[1];
21787             var k2 = _b[0], s2 = _b[1];
21788             return k1 === k2 && s1 === s2;
21789         }), operators_1.map(function (_a) {
21790             var key = _a[0], src = _a[1];
21791             return { key: key, src: src };
21792         }))
21793             .subscribe(this._configurationSubject$);
21794         this._renderSubscription = rxjs_1.combineLatest(this._configuration$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
21795             var configuration = _a[0], size = _a[1];
21796             if (!configuration.key) {
21797                 return { name: _this._name, vnode: vd.h("div", []) };
21798             }
21799             var compactClass = size.width <= 640 || size.height <= 480 ? ".CoverCompact" : "";
21800             if (configuration.state === Component_1.CoverState.Hidden) {
21801                 var doneContainer = vd.h("div.CoverContainer.CoverDone" + compactClass, [_this._getCoverBackgroundVNode(configuration)]);
21802                 return { name: _this._name, vnode: doneContainer };
21803             }
21804             var container = vd.h("div.CoverContainer" + compactClass, [_this._getCoverButtonVNode(configuration)]);
21805             return { name: _this._name, vnode: container };
21806         }))
21807             .subscribe(this._container.domRenderer.render$);
21808     };
21809     CoverComponent.prototype._deactivate = function () {
21810         this._renderSubscription.unsubscribe();
21811         this._keySubscription.unsubscribe();
21812     };
21813     CoverComponent.prototype._getDefaultConfiguration = function () {
21814         return { state: Component_1.CoverState.Visible };
21815     };
21816     CoverComponent.prototype._getCoverButtonVNode = function (configuration) {
21817         var _this = this;
21818         var cover = configuration.state === Component_1.CoverState.Loading ? "div.Cover.CoverLoading" : "div.Cover";
21819         var coverButton = vd.h("div.CoverButton", { onclick: function () { _this.configure({ state: Component_1.CoverState.Loading }); } }, [vd.h("div.CoverButtonIcon", [])]);
21820         var coverLogo = vd.h("a.CoverLogo", { href: Utils_1.Urls.explore, target: "_blank" }, []);
21821         return vd.h(cover, [this._getCoverBackgroundVNode(configuration), coverButton, coverLogo]);
21822     };
21823     CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
21824         var url = conf.src != null ?
21825             conf.src : Utils_1.Urls.thumbnail(conf.key, Viewer_1.ImageSize.Size640);
21826         var properties = { style: { backgroundImage: "url(" + url + ")" } };
21827         var children = [];
21828         if (conf.state === Component_1.CoverState.Loading) {
21829             children.push(vd.h("div.Spinner", {}, []));
21830         }
21831         return vd.h("div.CoverBackground", properties, children);
21832     };
21833     CoverComponent.componentName = "cover";
21834     return CoverComponent;
21835 }(Component_1.Component));
21836 exports.CoverComponent = CoverComponent;
21837 Component_1.ComponentService.registerCover(CoverComponent);
21838 exports.default = CoverComponent;
21839
21840 },{"../Component":274,"../Utils":284,"../Viewer":285,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],295:[function(require,module,exports){
21841 "use strict";
21842 var __extends = (this && this.__extends) || (function () {
21843     var extendStatics = function (d, b) {
21844         extendStatics = Object.setPrototypeOf ||
21845             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21846             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21847         return extendStatics(d, b);
21848     }
21849     return function (d, b) {
21850         extendStatics(d, b);
21851         function __() { this.constructor = d; }
21852         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21853     };
21854 })();
21855 Object.defineProperty(exports, "__esModule", { value: true });
21856 var rxjs_1 = require("rxjs");
21857 var operators_1 = require("rxjs/operators");
21858 var vd = require("virtual-dom");
21859 var Component_1 = require("../Component");
21860 var DebugComponent = /** @class */ (function (_super) {
21861     __extends(DebugComponent, _super);
21862     function DebugComponent() {
21863         var _this = _super !== null && _super.apply(this, arguments) || this;
21864         _this._open$ = new rxjs_1.BehaviorSubject(false);
21865         return _this;
21866     }
21867     DebugComponent.prototype._activate = function () {
21868         var _this = this;
21869         this._disposable = rxjs_1.combineLatest(this._navigator.stateService.currentState$, this._open$, this._navigator.imageLoadingService.loadstatus$).pipe(operators_1.map(function (_a) {
21870             var frame = _a[0], open = _a[1], loadStatus = _a[2];
21871             return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
21872         }))
21873             .subscribe(this._container.domRenderer.render$);
21874     };
21875     DebugComponent.prototype._deactivate = function () {
21876         this._disposable.unsubscribe();
21877     };
21878     DebugComponent.prototype._getDefaultConfiguration = function () {
21879         return {};
21880     };
21881     DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
21882         var ret = [];
21883         ret.push(vd.h("h2", "Node"));
21884         if (frame.state.currentNode) {
21885             ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
21886         }
21887         if (frame.state.previousNode) {
21888             ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
21889         }
21890         ret.push(vd.h("h2", "Loading"));
21891         var total = 0;
21892         var loaded = 0;
21893         var loading = 0;
21894         for (var key in loadStatus) {
21895             if (!loadStatus.hasOwnProperty(key)) {
21896                 continue;
21897             }
21898             var status_1 = loadStatus[key];
21899             total += status_1.loaded;
21900             if (status_1.loaded !== status_1.total) {
21901                 loading++;
21902             }
21903             else {
21904                 loaded++;
21905             }
21906         }
21907         ret.push(vd.h("p", "Loaded Images: " + loaded));
21908         ret.push(vd.h("p", "Loading Images: " + loading));
21909         ret.push(vd.h("p", "Total bytes loaded: " + total));
21910         ret.push(vd.h("h2", "Camera"));
21911         ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
21912         ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
21913         ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
21914         ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
21915         ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
21916         ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
21917         ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
21918         ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
21919         ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
21920         return ret;
21921     };
21922     DebugComponent.prototype._getDebugVNode = function (open, info) {
21923         if (open) {
21924             return vd.h("div.Debug", {}, [
21925                 vd.h("h2", {}, ["Debug"]),
21926                 this._getDebugVNodeButton(open),
21927                 vd.h("pre", {}, info),
21928             ]);
21929         }
21930         else {
21931             return this._getDebugVNodeButton(open);
21932         }
21933     };
21934     DebugComponent.prototype._getDebugVNodeButton = function (open) {
21935         var buttonText = open ? "Disable Debug" : "D";
21936         var buttonCssClass = open ? "" : ".DebugButtonFixed";
21937         if (open) {
21938             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
21939         }
21940         else {
21941             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
21942         }
21943     };
21944     DebugComponent.prototype._closeDebugElement = function (open) {
21945         this._open$.next(false);
21946     };
21947     DebugComponent.prototype._openDebugElement = function () {
21948         this._open$.next(true);
21949     };
21950     DebugComponent.componentName = "debug";
21951     return DebugComponent;
21952 }(Component_1.Component));
21953 exports.DebugComponent = DebugComponent;
21954 Component_1.ComponentService.register(DebugComponent);
21955 exports.default = DebugComponent;
21956
21957 },{"../Component":274,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],296:[function(require,module,exports){
21958 "use strict";
21959 var __extends = (this && this.__extends) || (function () {
21960     var extendStatics = function (d, b) {
21961         extendStatics = Object.setPrototypeOf ||
21962             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21963             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21964         return extendStatics(d, b);
21965     }
21966     return function (d, b) {
21967         extendStatics(d, b);
21968         function __() { this.constructor = d; }
21969         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21970     };
21971 })();
21972 Object.defineProperty(exports, "__esModule", { value: true });
21973 var rxjs_1 = require("rxjs");
21974 var operators_1 = require("rxjs/operators");
21975 var vd = require("virtual-dom");
21976 var Component_1 = require("../Component");
21977 var Utils_1 = require("../Utils");
21978 var ImageComponent = /** @class */ (function (_super) {
21979     __extends(ImageComponent, _super);
21980     function ImageComponent(name, container, navigator, dom) {
21981         var _this = _super.call(this, name, container, navigator) || this;
21982         _this._canvasId = container.id + "-" + _this._name;
21983         _this._dom = !!dom ? dom : new Utils_1.DOM();
21984         return _this;
21985     }
21986     ImageComponent.prototype._activate = function () {
21987         var _this = this;
21988         var canvasSize$ = this._container.domRenderer.element$.pipe(operators_1.map(function (element) {
21989             return _this._dom.document.getElementById(_this._canvasId);
21990         }), operators_1.filter(function (canvas) {
21991             return !!canvas;
21992         }), operators_1.map(function (canvas) {
21993             var adaptableDomRenderer = canvas.parentElement;
21994             var width = adaptableDomRenderer.offsetWidth;
21995             var height = adaptableDomRenderer.offsetHeight;
21996             return [canvas, { height: height, width: width }];
21997         }), operators_1.distinctUntilChanged(function (s1, s2) {
21998             return s1.height === s2.height && s1.width === s2.width;
21999         }, function (_a) {
22000             var canvas = _a[0], size = _a[1];
22001             return size;
22002         }));
22003         this.drawSubscription = rxjs_1.combineLatest(canvasSize$, this._navigator.stateService.currentNode$)
22004             .subscribe(function (_a) {
22005             var _b = _a[0], canvas = _b[0], size = _b[1], node = _a[1];
22006             canvas.width = size.width;
22007             canvas.height = size.height;
22008             canvas
22009                 .getContext("2d")
22010                 .drawImage(node.image, 0, 0, size.width, size.height);
22011         });
22012         this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
22013     };
22014     ImageComponent.prototype._deactivate = function () {
22015         this.drawSubscription.unsubscribe();
22016     };
22017     ImageComponent.prototype._getDefaultConfiguration = function () {
22018         return {};
22019     };
22020     ImageComponent.componentName = "image";
22021     return ImageComponent;
22022 }(Component_1.Component));
22023 exports.ImageComponent = ImageComponent;
22024 Component_1.ComponentService.register(ImageComponent);
22025 exports.default = ImageComponent;
22026
22027
22028 },{"../Component":274,"../Utils":284,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],297:[function(require,module,exports){
22029 "use strict";
22030 var __extends = (this && this.__extends) || (function () {
22031     var extendStatics = function (d, b) {
22032         extendStatics = Object.setPrototypeOf ||
22033             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22034             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22035         return extendStatics(d, b);
22036     }
22037     return function (d, b) {
22038         extendStatics(d, b);
22039         function __() { this.constructor = d; }
22040         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22041     };
22042 })();
22043 Object.defineProperty(exports, "__esModule", { value: true });
22044 var rxjs_1 = require("rxjs");
22045 var operators_1 = require("rxjs/operators");
22046 var vd = require("virtual-dom");
22047 var Component_1 = require("../Component");
22048 var LoadingComponent = /** @class */ (function (_super) {
22049     __extends(LoadingComponent, _super);
22050     function LoadingComponent(name, container, navigator) {
22051         return _super.call(this, name, container, navigator) || this;
22052     }
22053     LoadingComponent.prototype._activate = function () {
22054         var _this = this;
22055         this._loadingSubscription = this._navigator.loadingService.loading$.pipe(operators_1.switchMap(function (loading) {
22056             return loading ?
22057                 _this._navigator.imageLoadingService.loadstatus$ :
22058                 rxjs_1.of({});
22059         }), operators_1.map(function (loadStatus) {
22060             var total = 0;
22061             var loaded = 0;
22062             for (var key in loadStatus) {
22063                 if (!loadStatus.hasOwnProperty(key)) {
22064                     continue;
22065                 }
22066                 var status_1 = loadStatus[key];
22067                 if (status_1.loaded !== status_1.total) {
22068                     loaded += status_1.loaded;
22069                     total += status_1.total;
22070                 }
22071             }
22072             var percentage = 100;
22073             if (total !== 0) {
22074                 percentage = (loaded / total) * 100;
22075             }
22076             return { name: _this._name, vnode: _this._getBarVNode(percentage) };
22077         }))
22078             .subscribe(this._container.domRenderer.render$);
22079     };
22080     LoadingComponent.prototype._deactivate = function () {
22081         this._loadingSubscription.unsubscribe();
22082     };
22083     LoadingComponent.prototype._getDefaultConfiguration = function () {
22084         return {};
22085     };
22086     LoadingComponent.prototype._getBarVNode = function (percentage) {
22087         var loadingBarStyle = {};
22088         var loadingContainerStyle = {};
22089         if (percentage !== 100) {
22090             loadingBarStyle.width = percentage.toFixed(0) + "%";
22091             loadingBarStyle.opacity = "1";
22092         }
22093         else {
22094             loadingBarStyle.width = "100%";
22095             loadingBarStyle.opacity = "0";
22096         }
22097         return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
22098     };
22099     LoadingComponent.componentName = "loading";
22100     return LoadingComponent;
22101 }(Component_1.Component));
22102 exports.LoadingComponent = LoadingComponent;
22103 Component_1.ComponentService.register(LoadingComponent);
22104 exports.default = LoadingComponent;
22105
22106 },{"../Component":274,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],298:[function(require,module,exports){
22107 "use strict";
22108 var __extends = (this && this.__extends) || (function () {
22109     var extendStatics = function (d, b) {
22110         extendStatics = Object.setPrototypeOf ||
22111             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22112             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22113         return extendStatics(d, b);
22114     }
22115     return function (d, b) {
22116         extendStatics(d, b);
22117         function __() { this.constructor = d; }
22118         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22119     };
22120 })();
22121 Object.defineProperty(exports, "__esModule", { value: true });
22122 var rxjs_1 = require("rxjs");
22123 var operators_1 = require("rxjs/operators");
22124 var vd = require("virtual-dom");
22125 var Edge_1 = require("../Edge");
22126 var Error_1 = require("../Error");
22127 var Component_1 = require("../Component");
22128 /**
22129  * @class NavigationComponent
22130  *
22131  * @classdesc Fallback navigation component for environments without WebGL support.
22132  *
22133  * Replaces the functionality in the Direction and Sequence components.
22134  */
22135 var NavigationComponent = /** @class */ (function (_super) {
22136     __extends(NavigationComponent, _super);
22137     /** @ignore */
22138     function NavigationComponent(name, container, navigator) {
22139         var _this = _super.call(this, name, container, navigator) || this;
22140         _this._seqNames = {};
22141         _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Prev]] = "Prev";
22142         _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Next]] = "Next";
22143         _this._spaTopNames = {};
22144         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnLeft]] = "Turnleft";
22145         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepLeft]] = "Left";
22146         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepForward]] = "Forward";
22147         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepRight]] = "Right";
22148         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnRight]] = "Turnright";
22149         _this._spaBottomNames = {};
22150         _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnU]] = "Turnaround";
22151         _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepBackward]] = "Backward";
22152         return _this;
22153     }
22154     NavigationComponent.prototype._activate = function () {
22155         var _this = this;
22156         this._renderSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$, this._configuration$).pipe(operators_1.switchMap(function (_a) {
22157             var node = _a[0], configuration = _a[1];
22158             var sequenceEdges$ = configuration.sequence ?
22159                 node.sequenceEdges$.pipe(operators_1.map(function (status) {
22160                     return status.edges
22161                         .map(function (edge) {
22162                         return edge.data.direction;
22163                     });
22164                 })) :
22165                 rxjs_1.of([]);
22166             var spatialEdges$ = !node.pano && configuration.spatial ?
22167                 node.spatialEdges$.pipe(operators_1.map(function (status) {
22168                     return status.edges
22169                         .map(function (edge) {
22170                         return edge.data.direction;
22171                     });
22172                 })) :
22173                 rxjs_1.of([]);
22174             return rxjs_1.combineLatest(sequenceEdges$, spatialEdges$).pipe(operators_1.map(function (_a) {
22175                 var seq = _a[0], spa = _a[1];
22176                 return seq.concat(spa);
22177             }));
22178         }), operators_1.map(function (edgeDirections) {
22179             var seqs = _this._createArrowRow(_this._seqNames, edgeDirections);
22180             var spaTops = _this._createArrowRow(_this._spaTopNames, edgeDirections);
22181             var spaBottoms = _this._createArrowRow(_this._spaBottomNames, edgeDirections);
22182             var seqContainer = vd.h("div.NavigationSequence", seqs);
22183             var spaTopContainer = vd.h("div.NavigationSpatialTop", spaTops);
22184             var spaBottomContainer = vd.h("div.NavigationSpatialBottom", spaBottoms);
22185             var spaContainer = vd.h("div.NavigationSpatial", [spaTopContainer, spaBottomContainer]);
22186             return { name: _this._name, vnode: vd.h("div.NavigationContainer", [seqContainer, spaContainer]) };
22187         }))
22188             .subscribe(this._container.domRenderer.render$);
22189     };
22190     NavigationComponent.prototype._deactivate = function () {
22191         this._renderSubscription.unsubscribe();
22192     };
22193     NavigationComponent.prototype._getDefaultConfiguration = function () {
22194         return { sequence: true, spatial: true };
22195     };
22196     NavigationComponent.prototype._createArrowRow = function (arrowNames, edgeDirections) {
22197         var arrows = [];
22198         for (var arrowName in arrowNames) {
22199             if (!(arrowNames.hasOwnProperty(arrowName))) {
22200                 continue;
22201             }
22202             var direction = Edge_1.EdgeDirection[arrowName];
22203             if (edgeDirections.indexOf(direction) !== -1) {
22204                 arrows.push(this._createVNode(direction, arrowNames[arrowName], "visible"));
22205             }
22206             else {
22207                 arrows.push(this._createVNode(direction, arrowNames[arrowName], "hidden"));
22208             }
22209         }
22210         return arrows;
22211     };
22212     NavigationComponent.prototype._createVNode = function (direction, name, visibility) {
22213         var _this = this;
22214         return vd.h("span.Direction.Direction" + name, {
22215             onclick: function (ev) {
22216                 _this._navigator.moveDir$(direction)
22217                     .subscribe(undefined, function (error) {
22218                     if (!(error instanceof Error_1.AbortMapillaryError)) {
22219                         console.error(error);
22220                     }
22221                 });
22222             },
22223             style: {
22224                 visibility: visibility,
22225             },
22226         }, []);
22227     };
22228     NavigationComponent.componentName = "navigation";
22229     return NavigationComponent;
22230 }(Component_1.Component));
22231 exports.NavigationComponent = NavigationComponent;
22232 Component_1.ComponentService.register(NavigationComponent);
22233 exports.default = NavigationComponent;
22234
22235 },{"../Component":274,"../Edge":275,"../Error":276,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],299:[function(require,module,exports){
22236 "use strict";
22237 var __extends = (this && this.__extends) || (function () {
22238     var extendStatics = function (d, b) {
22239         extendStatics = Object.setPrototypeOf ||
22240             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22241             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22242         return extendStatics(d, b);
22243     }
22244     return function (d, b) {
22245         extendStatics(d, b);
22246         function __() { this.constructor = d; }
22247         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22248     };
22249 })();
22250 Object.defineProperty(exports, "__esModule", { value: true });
22251 var rxjs_1 = require("rxjs");
22252 var operators_1 = require("rxjs/operators");
22253 var vd = require("virtual-dom");
22254 var Component_1 = require("../Component");
22255 var DescriptionState = /** @class */ (function () {
22256     function DescriptionState() {
22257     }
22258     return DescriptionState;
22259 }());
22260 var RouteState = /** @class */ (function () {
22261     function RouteState() {
22262     }
22263     return RouteState;
22264 }());
22265 var RouteTrack = /** @class */ (function () {
22266     function RouteTrack() {
22267         this.nodeInstructions = [];
22268         this.nodeInstructionsOrdered = [];
22269     }
22270     return RouteTrack;
22271 }());
22272 var RouteComponent = /** @class */ (function (_super) {
22273     __extends(RouteComponent, _super);
22274     function RouteComponent(name, container, navigator) {
22275         return _super.call(this, name, container, navigator) || this;
22276     }
22277     RouteComponent.prototype._activate = function () {
22278         var _this = this;
22279         var slowedStream$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
22280             return (frame.id % 2) === 0;
22281         }), operators_1.filter(function (frame) {
22282             return frame.state.nodesAhead < 15;
22283         }), operators_1.distinctUntilChanged(undefined, function (frame) {
22284             return frame.state.lastNode.key;
22285         }));
22286         var routeTrack$ = rxjs_1.combineLatest(this.configuration$.pipe(operators_1.mergeMap(function (conf) {
22287             return rxjs_1.from(conf.paths);
22288         }), operators_1.distinct(function (p) {
22289             return p.sequenceKey;
22290         }), operators_1.mergeMap(function (path) {
22291             return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey]).pipe(operators_1.map(function (sequenceByKey) {
22292                 return sequenceByKey[path.sequenceKey];
22293             }));
22294         })), this.configuration$).pipe(operators_1.map(function (_a) {
22295             var sequence = _a[0], conf = _a[1];
22296             var i = 0;
22297             var instructionPlaces = [];
22298             for (var _i = 0, _b = conf.paths; _i < _b.length; _i++) {
22299                 var path = _b[_i];
22300                 if (path.sequenceKey === sequence.key) {
22301                     var nodeInstructions = [];
22302                     var saveKey = false;
22303                     for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
22304                         var key = _d[_c];
22305                         if (path.startKey === key) {
22306                             saveKey = true;
22307                         }
22308                         if (saveKey) {
22309                             var description = null;
22310                             for (var _e = 0, _f = path.infoKeys; _e < _f.length; _e++) {
22311                                 var infoKey = _f[_e];
22312                                 if (infoKey.key === key) {
22313                                     description = infoKey.description;
22314                                 }
22315                             }
22316                             nodeInstructions.push({ description: description, key: key });
22317                         }
22318                         if (path.stopKey === key) {
22319                             saveKey = false;
22320                         }
22321                     }
22322                     instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
22323                 }
22324                 i++;
22325             }
22326             return instructionPlaces;
22327         }), operators_1.scan(function (routeTrack, instructionPlaces) {
22328             for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
22329                 var instructionPlace = instructionPlaces_1[_i];
22330                 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
22331             }
22332             for (var place in routeTrack.nodeInstructionsOrdered) {
22333                 if (!routeTrack.nodeInstructionsOrdered.hasOwnProperty(place)) {
22334                     continue;
22335                 }
22336                 var instructionGroup = routeTrack.nodeInstructionsOrdered[place];
22337                 for (var _a = 0, instructionGroup_1 = instructionGroup; _a < instructionGroup_1.length; _a++) {
22338                     var instruction = instructionGroup_1[_a];
22339                     routeTrack.nodeInstructions.push(instruction);
22340                 }
22341             }
22342             return routeTrack;
22343         }, new RouteTrack()));
22344         var cacheNode$ = rxjs_1.combineLatest(slowedStream$, routeTrack$, this.configuration$).pipe(operators_1.map(function (_a) {
22345             var frame = _a[0], routeTrack = _a[1], conf = _a[2];
22346             return { conf: conf, frame: frame, routeTrack: routeTrack };
22347         }), operators_1.scan(function (routeState, rtAndFrame) {
22348             if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
22349                 routeState.routeTrack = rtAndFrame.routeTrack;
22350                 routeState.currentNode = rtAndFrame.frame.state.currentNode;
22351                 routeState.lastNode = rtAndFrame.frame.state.lastNode;
22352                 routeState.playing = true;
22353             }
22354             else {
22355                 _this._navigator.stateService.cutNodes();
22356                 routeState.playing = false;
22357             }
22358             return routeState;
22359         }, new RouteState()), operators_1.filter(function (routeState) {
22360             return routeState.playing;
22361         }), operators_1.filter(function (routeState) {
22362             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
22363                 var nodeInstruction = _a[_i];
22364                 if (!nodeInstruction) {
22365                     continue;
22366                 }
22367                 if (nodeInstruction.key === routeState.lastNode.key) {
22368                     return true;
22369                 }
22370             }
22371             return false;
22372         }), operators_1.distinctUntilChanged(undefined, function (routeState) {
22373             return routeState.lastNode.key;
22374         }), operators_1.mergeMap(function (routeState) {
22375             var i = 0;
22376             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
22377                 var nodeInstruction = _a[_i];
22378                 if (nodeInstruction.key === routeState.lastNode.key) {
22379                     break;
22380                 }
22381                 i++;
22382             }
22383             var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
22384             if (!nextInstruction) {
22385                 return rxjs_1.of(null);
22386             }
22387             return _this._navigator.graphService.cacheNode$(nextInstruction.key);
22388         }));
22389         this._disposable = rxjs_1.combineLatest(cacheNode$, this.configuration$).pipe(operators_1.map(function (_a) {
22390             var node = _a[0], conf = _a[1];
22391             return { conf: conf, node: node };
22392         }), operators_1.filter(function (cAN) {
22393             return cAN.node !== null && cAN.conf.playing;
22394         }), operators_1.pluck("node"))
22395             .subscribe(this._navigator.stateService.appendNode$);
22396         this._disposableDescription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$, routeTrack$, this.configuration$).pipe(operators_1.map(function (_a) {
22397             var node = _a[0], routeTrack = _a[1], conf = _a[2];
22398             if (conf.playing !== undefined && !conf.playing) {
22399                 return "quit";
22400             }
22401             var description = null;
22402             for (var _i = 0, _b = routeTrack.nodeInstructions; _i < _b.length; _i++) {
22403                 var nodeInstruction = _b[_i];
22404                 if (nodeInstruction.key === node.key) {
22405                     description = nodeInstruction.description;
22406                     break;
22407                 }
22408             }
22409             return description;
22410         }), operators_1.scan(function (descriptionState, description) {
22411             if (description !== descriptionState.description && description !== null) {
22412                 descriptionState.description = description;
22413                 descriptionState.showsLeft = 6;
22414             }
22415             else {
22416                 descriptionState.showsLeft--;
22417             }
22418             if (description === "quit") {
22419                 descriptionState.description = null;
22420             }
22421             return descriptionState;
22422         }, new DescriptionState()), operators_1.map(function (descriptionState) {
22423             if (descriptionState.showsLeft > 0 && descriptionState.description) {
22424                 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
22425             }
22426             else {
22427                 return { name: _this._name, vnode: vd.h("div", []) };
22428             }
22429         }))
22430             .subscribe(this._container.domRenderer.render$);
22431     };
22432     RouteComponent.prototype._deactivate = function () {
22433         this._disposable.unsubscribe();
22434         this._disposableDescription.unsubscribe();
22435     };
22436     RouteComponent.prototype._getDefaultConfiguration = function () {
22437         return {};
22438     };
22439     RouteComponent.prototype.play = function () {
22440         this.configure({ playing: true });
22441     };
22442     RouteComponent.prototype.stop = function () {
22443         this.configure({ playing: false });
22444     };
22445     RouteComponent.prototype._getRouteAnnotationNode = function (description) {
22446         return vd.h("div.RouteFrame", {}, [
22447             vd.h("p", { textContent: description }, []),
22448         ]);
22449     };
22450     RouteComponent.componentName = "route";
22451     return RouteComponent;
22452 }(Component_1.Component));
22453 exports.RouteComponent = RouteComponent;
22454 Component_1.ComponentService.register(RouteComponent);
22455 exports.default = RouteComponent;
22456
22457 },{"../Component":274,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],300:[function(require,module,exports){
22458 "use strict";
22459 var __extends = (this && this.__extends) || (function () {
22460     var extendStatics = function (d, b) {
22461         extendStatics = Object.setPrototypeOf ||
22462             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22463             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22464         return extendStatics(d, b);
22465     }
22466     return function (d, b) {
22467         extendStatics(d, b);
22468         function __() { this.constructor = d; }
22469         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22470     };
22471 })();
22472 Object.defineProperty(exports, "__esModule", { value: true });
22473 var rxjs_1 = require("rxjs");
22474 var operators_1 = require("rxjs/operators");
22475 var Component_1 = require("../Component");
22476 var StatsComponent = /** @class */ (function (_super) {
22477     __extends(StatsComponent, _super);
22478     function StatsComponent(name, container, navigator, scheduler) {
22479         var _this = _super.call(this, name, container, navigator) || this;
22480         _this._scheduler = scheduler;
22481         return _this;
22482     }
22483     StatsComponent.prototype._activate = function () {
22484         var _this = this;
22485         this._sequenceSubscription = this._navigator.stateService.currentNode$.pipe(operators_1.scan(function (keys, node) {
22486             var sKey = node.sequenceKey;
22487             keys.report = [];
22488             if (!(sKey in keys.reported)) {
22489                 keys.report = [sKey];
22490                 keys.reported[sKey] = true;
22491             }
22492             return keys;
22493         }, { report: [], reported: {} }), operators_1.filter(function (keys) {
22494             return keys.report.length > 0;
22495         }), operators_1.mergeMap(function (keys) {
22496             return _this._navigator.apiV3.sequenceViewAdd$(keys.report).pipe(operators_1.catchError(function (error, caught) {
22497                 console.error("Failed to report sequence stats (" + keys.report + ")", error);
22498                 return rxjs_1.empty();
22499             }));
22500         }))
22501             .subscribe(function () { });
22502         this._imageSubscription = this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) {
22503             return node.key;
22504         })).pipe(operators_1.buffer(this._navigator.stateService.currentNode$.pipe(operators_1.debounceTime(5000, this._scheduler))), operators_1.scan(function (keys, newKeys) {
22505             keys.report = [];
22506             for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
22507                 var key = newKeys_1[_i];
22508                 if (!(key in keys.reported)) {
22509                     keys.report.push(key);
22510                     keys.reported[key] = true;
22511                 }
22512             }
22513             return keys;
22514         }, { report: [], reported: {} }), operators_1.filter(function (keys) {
22515             return keys.report.length > 0;
22516         }), operators_1.mergeMap(function (keys) {
22517             return _this._navigator.apiV3.imageViewAdd$(keys.report).pipe(operators_1.catchError(function (error, caught) {
22518                 console.error("Failed to report image stats (" + keys.report + ")", error);
22519                 return rxjs_1.empty();
22520             }));
22521         }))
22522             .subscribe(function () { });
22523     };
22524     StatsComponent.prototype._deactivate = function () {
22525         this._sequenceSubscription.unsubscribe();
22526         this._imageSubscription.unsubscribe();
22527     };
22528     StatsComponent.prototype._getDefaultConfiguration = function () {
22529         return {};
22530     };
22531     StatsComponent.componentName = "stats";
22532     return StatsComponent;
22533 }(Component_1.Component));
22534 exports.StatsComponent = StatsComponent;
22535 Component_1.ComponentService.register(StatsComponent);
22536 exports.default = StatsComponent;
22537
22538 },{"../Component":274,"rxjs":26,"rxjs/operators":224}],301:[function(require,module,exports){
22539 "use strict";
22540 var __extends = (this && this.__extends) || (function () {
22541     var extendStatics = function (d, b) {
22542         extendStatics = Object.setPrototypeOf ||
22543             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22544             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22545         return extendStatics(d, b);
22546     }
22547     return function (d, b) {
22548         extendStatics(d, b);
22549         function __() { this.constructor = d; }
22550         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22551     };
22552 })();
22553 Object.defineProperty(exports, "__esModule", { value: true });
22554 var vd = require("virtual-dom");
22555 var rxjs_1 = require("rxjs");
22556 var operators_1 = require("rxjs/operators");
22557 var Component_1 = require("../../Component");
22558 /**
22559  * @class DirectionComponent
22560  * @classdesc Component showing navigation arrows for steps and turns.
22561  */
22562 var DirectionComponent = /** @class */ (function (_super) {
22563     __extends(DirectionComponent, _super);
22564     function DirectionComponent(name, container, navigator, directionDOMRenderer) {
22565         var _this = _super.call(this, name, container, navigator) || this;
22566         _this._renderer = !!directionDOMRenderer ?
22567             directionDOMRenderer :
22568             new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, { height: container.element.offsetHeight, width: container.element.offsetWidth });
22569         _this._hoveredKeySubject$ = new rxjs_1.Subject();
22570         _this._hoveredKey$ = _this._hoveredKeySubject$.pipe(operators_1.share());
22571         return _this;
22572     }
22573     Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
22574         /**
22575          * Get hovered key observable.
22576          *
22577          * @description An observable emitting the key of the node for the direction
22578          * arrow that is being hovered. When the mouse leaves a direction arrow null
22579          * is emitted.
22580          *
22581          * @returns {Observable<string>}
22582          */
22583         get: function () {
22584             return this._hoveredKey$;
22585         },
22586         enumerable: true,
22587         configurable: true
22588     });
22589     /**
22590      * Set highlight key.
22591      *
22592      * @description The arrow pointing towards the node corresponding to the
22593      * highlight key will be highlighted.
22594      *
22595      * @param {string} highlightKey Key of node to be highlighted if existing
22596      * among arrows.
22597      */
22598     DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
22599         this.configure({ highlightKey: highlightKey });
22600     };
22601     /**
22602      * Set min width of container element.
22603      *
22604      * @description  Set min width of the non transformed container element holding
22605      * the navigation arrows. If the min width is larger than the max width the
22606      * min width value will be used.
22607      *
22608      * The container element is automatically resized when the resize
22609      * method on the Viewer class is called.
22610      *
22611      * @param {number} minWidth
22612      */
22613     DirectionComponent.prototype.setMinWidth = function (minWidth) {
22614         this.configure({ minWidth: minWidth });
22615     };
22616     /**
22617      * Set max width of container element.
22618      *
22619      * @description Set max width of the non transformed container element holding
22620      * the navigation arrows. If the min width is larger than the max width the
22621      * min width value will be used.
22622      *
22623      * The container element is automatically resized when the resize
22624      * method on the Viewer class is called.
22625      *
22626      * @param {number} minWidth
22627      */
22628     DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
22629         this.configure({ maxWidth: maxWidth });
22630     };
22631     DirectionComponent.prototype._activate = function () {
22632         var _this = this;
22633         this._configurationSubscription = this._configuration$
22634             .subscribe(function (configuration) {
22635             _this._renderer.setConfiguration(configuration);
22636         });
22637         this._resizeSubscription = this._container.renderService.size$
22638             .subscribe(function (size) {
22639             _this._renderer.resize(size);
22640         });
22641         this._nodeSubscription = this._navigator.stateService.currentNode$.pipe(operators_1.tap(function (node) {
22642             _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
22643             _this._renderer.setNode(node);
22644         }), operators_1.withLatestFrom(this._configuration$), operators_1.switchMap(function (_a) {
22645             var node = _a[0], configuration = _a[1];
22646             return rxjs_1.combineLatest(node.spatialEdges$, configuration.distinguishSequence ?
22647                 _this._navigator.graphService
22648                     .cacheSequence$(node.sequenceKey).pipe(operators_1.catchError(function (error, caught) {
22649                     console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
22650                     return rxjs_1.of(null);
22651                 })) :
22652                 rxjs_1.of(null));
22653         }))
22654             .subscribe(function (_a) {
22655             var edgeStatus = _a[0], sequence = _a[1];
22656             _this._renderer.setEdges(edgeStatus, sequence);
22657         });
22658         this._renderCameraSubscription = this._container.renderService.renderCameraFrame$.pipe(operators_1.tap(function (renderCamera) {
22659             _this._renderer.setRenderCamera(renderCamera);
22660         }), operators_1.map(function () {
22661             return _this._renderer;
22662         }), operators_1.filter(function (renderer) {
22663             return renderer.needsRender;
22664         }), operators_1.map(function (renderer) {
22665             return { name: _this._name, vnode: renderer.render(_this._navigator) };
22666         }))
22667             .subscribe(this._container.domRenderer.render$);
22668         this._hoveredKeySubscription = rxjs_1.combineLatest(this._container.domRenderer.element$, this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$.pipe(operators_1.startWith(null)), this._container.mouseService.mouseUp$.pipe(operators_1.startWith(null))).pipe(operators_1.map(function (_a) {
22669             var element = _a[0];
22670             var elements = element.getElementsByClassName("DirectionsPerspective");
22671             for (var i = 0; i < elements.length; i++) {
22672                 var hovered = elements.item(i).querySelector(":hover");
22673                 if (hovered != null && hovered.hasAttribute("data-key")) {
22674                     return hovered.getAttribute("data-key");
22675                 }
22676             }
22677             return null;
22678         }), operators_1.distinctUntilChanged())
22679             .subscribe(this._hoveredKeySubject$);
22680         this._emitHoveredKeySubscription = this._hoveredKey$
22681             .subscribe(function (key) {
22682             _this.fire(DirectionComponent.hoveredkeychanged, key);
22683         });
22684     };
22685     DirectionComponent.prototype._deactivate = function () {
22686         this._configurationSubscription.unsubscribe();
22687         this._emitHoveredKeySubscription.unsubscribe();
22688         this._hoveredKeySubscription.unsubscribe();
22689         this._nodeSubscription.unsubscribe();
22690         this._renderCameraSubscription.unsubscribe();
22691     };
22692     DirectionComponent.prototype._getDefaultConfiguration = function () {
22693         return {
22694             distinguishSequence: false,
22695             maxWidth: 460,
22696             minWidth: 260,
22697         };
22698     };
22699     /** @inheritdoc */
22700     DirectionComponent.componentName = "direction";
22701     /**
22702      * Event fired when the hovered key changes.
22703      *
22704      * @description Emits the key of the node for the direction
22705      * arrow that is being hovered. When the mouse leaves a
22706      * direction arrow null is emitted.
22707      *
22708      * @event DirectionComponent#hoveredkeychanged
22709      * @type {string} The hovered key, null if no key is hovered.
22710      */
22711     DirectionComponent.hoveredkeychanged = "hoveredkeychanged";
22712     return DirectionComponent;
22713 }(Component_1.Component));
22714 exports.DirectionComponent = DirectionComponent;
22715 Component_1.ComponentService.register(DirectionComponent);
22716 exports.default = DirectionComponent;
22717
22718
22719 },{"../../Component":274,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],302:[function(require,module,exports){
22720 "use strict";
22721 Object.defineProperty(exports, "__esModule", { value: true });
22722 var Geo_1 = require("../../Geo");
22723 /**
22724  * @class DirectionDOMCalculator
22725  * @classdesc Helper class for calculating DOM CSS properties.
22726  */
22727 var DirectionDOMCalculator = /** @class */ (function () {
22728     function DirectionDOMCalculator(configuration, size) {
22729         this._spatial = new Geo_1.Spatial();
22730         this._minThresholdWidth = 320;
22731         this._maxThresholdWidth = 1480;
22732         this._minThresholdHeight = 240;
22733         this._maxThresholdHeight = 820;
22734         this._configure(configuration);
22735         this._resize(size);
22736         this._reset();
22737     }
22738     Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
22739         get: function () {
22740             return this._minWidth;
22741         },
22742         enumerable: true,
22743         configurable: true
22744     });
22745     Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
22746         get: function () {
22747             return this._maxWidth;
22748         },
22749         enumerable: true,
22750         configurable: true
22751     });
22752     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
22753         get: function () {
22754             return this._containerWidth;
22755         },
22756         enumerable: true,
22757         configurable: true
22758     });
22759     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
22760         get: function () {
22761             return this._containerWidthCss;
22762         },
22763         enumerable: true,
22764         configurable: true
22765     });
22766     Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
22767         get: function () {
22768             return this._containerMarginCss;
22769         },
22770         enumerable: true,
22771         configurable: true
22772     });
22773     Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
22774         get: function () {
22775             return this._containerLeftCss;
22776         },
22777         enumerable: true,
22778         configurable: true
22779     });
22780     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
22781         get: function () {
22782             return this._containerHeight;
22783         },
22784         enumerable: true,
22785         configurable: true
22786     });
22787     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
22788         get: function () {
22789             return this._containerHeightCss;
22790         },
22791         enumerable: true,
22792         configurable: true
22793     });
22794     Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
22795         get: function () {
22796             return this._containerBottomCss;
22797         },
22798         enumerable: true,
22799         configurable: true
22800     });
22801     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
22802         get: function () {
22803             return this._stepCircleSize;
22804         },
22805         enumerable: true,
22806         configurable: true
22807     });
22808     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
22809         get: function () {
22810             return this._stepCircleSizeCss;
22811         },
22812         enumerable: true,
22813         configurable: true
22814     });
22815     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
22816         get: function () {
22817             return this._stepCircleMarginCss;
22818         },
22819         enumerable: true,
22820         configurable: true
22821     });
22822     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
22823         get: function () {
22824             return this._turnCircleSize;
22825         },
22826         enumerable: true,
22827         configurable: true
22828     });
22829     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
22830         get: function () {
22831             return this._turnCircleSizeCss;
22832         },
22833         enumerable: true,
22834         configurable: true
22835     });
22836     Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
22837         get: function () {
22838             return this._outerRadius;
22839         },
22840         enumerable: true,
22841         configurable: true
22842     });
22843     Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
22844         get: function () {
22845             return this._innerRadius;
22846         },
22847         enumerable: true,
22848         configurable: true
22849     });
22850     Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
22851         get: function () {
22852             return this._shadowOffset;
22853         },
22854         enumerable: true,
22855         configurable: true
22856     });
22857     /**
22858      * Configures the min and max width values.
22859      *
22860      * @param {IDirectionConfiguration} configuration Configuration
22861      * with min and max width values.
22862      */
22863     DirectionDOMCalculator.prototype.configure = function (configuration) {
22864         this._configure(configuration);
22865         this._reset();
22866     };
22867     /**
22868      * Resizes all properties according to the width and height
22869      * of the size object.
22870      *
22871      * @param {ISize} size The size of the container element.
22872      */
22873     DirectionDOMCalculator.prototype.resize = function (size) {
22874         this._resize(size);
22875         this._reset();
22876     };
22877     /**
22878      * Calculates the coordinates on the unit circle for an angle.
22879      *
22880      * @param {number} angle Angle in radians.
22881      * @returns {Array<number>} The x and y coordinates on the unit circle.
22882      */
22883     DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
22884         return [Math.cos(angle), Math.sin(angle)];
22885     };
22886     /**
22887      * Calculates the coordinates on the unit circle for the
22888      * relative angle between the first and second angle.
22889      *
22890      * @param {number} first Angle in radians.
22891      * @param {number} second Angle in radians.
22892      * @returns {Array<number>} The x and y coordinates on the unit circle
22893      * for the relative angle between the first and second angle.
22894      */
22895     DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
22896         var relativeAngle = this._spatial.wrapAngle(first - second);
22897         return this.angleToCoordinates(relativeAngle);
22898     };
22899     DirectionDOMCalculator.prototype._configure = function (configuration) {
22900         this._minWidth = configuration.minWidth;
22901         this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
22902     };
22903     DirectionDOMCalculator.prototype._resize = function (size) {
22904         this._elementWidth = size.width;
22905         this._elementHeight = size.height;
22906     };
22907     DirectionDOMCalculator.prototype._reset = function () {
22908         this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
22909         this._containerHeight = this._getContainerHeight(this.containerWidth);
22910         this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
22911         this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
22912         this._outerRadius = this._getOuterRadius(this._containerHeight);
22913         this._innerRadius = this._getInnerRadius(this._containerHeight);
22914         this._shadowOffset = 3;
22915         this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
22916         this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
22917         this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
22918         this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
22919         this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
22920         this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
22921         this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
22922         this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
22923     };
22924     DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
22925         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
22926         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
22927         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
22928         coeff = 0.04 * Math.round(25 * coeff);
22929         return this._minWidth + coeff * (this._maxWidth - this._minWidth);
22930     };
22931     DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
22932         return 0.77 * containerWidth;
22933     };
22934     DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
22935         return 0.34 * containerHeight;
22936     };
22937     DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
22938         return 0.3 * containerHeight;
22939     };
22940     DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
22941         return 0.31 * containerHeight;
22942     };
22943     DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
22944         return 0.125 * containerHeight;
22945     };
22946     DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
22947         return value + "px";
22948     };
22949     DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
22950         return value > minWidth ? value : minWidth;
22951     };
22952     return DirectionDOMCalculator;
22953 }());
22954 exports.DirectionDOMCalculator = DirectionDOMCalculator;
22955 exports.default = DirectionDOMCalculator;
22956
22957
22958 },{"../../Geo":277}],303:[function(require,module,exports){
22959 "use strict";
22960 Object.defineProperty(exports, "__esModule", { value: true });
22961 var vd = require("virtual-dom");
22962 var Component_1 = require("../../Component");
22963 var Edge_1 = require("../../Edge");
22964 var Error_1 = require("../../Error");
22965 var Geo_1 = require("../../Geo");
22966 /**
22967  * @class DirectionDOMRenderer
22968  * @classdesc DOM renderer for direction arrows.
22969  */
22970 var DirectionDOMRenderer = /** @class */ (function () {
22971     function DirectionDOMRenderer(configuration, size) {
22972         this._isEdge = false;
22973         this._spatial = new Geo_1.Spatial();
22974         this._calculator = new Component_1.DirectionDOMCalculator(configuration, size);
22975         this._node = null;
22976         this._rotation = { phi: 0, theta: 0 };
22977         this._epsilon = 0.5 * Math.PI / 180;
22978         this._highlightKey = null;
22979         this._distinguishSequence = false;
22980         this._needsRender = false;
22981         this._stepEdges = [];
22982         this._turnEdges = [];
22983         this._panoEdges = [];
22984         this._sequenceEdgeKeys = [];
22985         this._stepDirections = [
22986             Edge_1.EdgeDirection.StepForward,
22987             Edge_1.EdgeDirection.StepBackward,
22988             Edge_1.EdgeDirection.StepLeft,
22989             Edge_1.EdgeDirection.StepRight,
22990         ];
22991         this._turnDirections = [
22992             Edge_1.EdgeDirection.TurnLeft,
22993             Edge_1.EdgeDirection.TurnRight,
22994             Edge_1.EdgeDirection.TurnU,
22995         ];
22996         this._turnNames = {};
22997         this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
22998         this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
22999         this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
23000         // detects IE 8-11, then Edge 20+.
23001         var isIE = !!document.documentMode;
23002         this._isEdge = !isIE && !!window.StyleMedia;
23003     }
23004     Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
23005         /**
23006          * Get needs render.
23007          *
23008          * @returns {boolean} Value indicating whether render should be called.
23009          */
23010         get: function () {
23011             return this._needsRender;
23012         },
23013         enumerable: true,
23014         configurable: true
23015     });
23016     /**
23017      * Renders virtual DOM elements.
23018      *
23019      * @description Calling render resets the needs render property.
23020      */
23021     DirectionDOMRenderer.prototype.render = function (navigator) {
23022         this._needsRender = false;
23023         var rotation = this._rotation;
23024         var steps = [];
23025         var turns = [];
23026         if (this._node.pano) {
23027             steps = steps.concat(this._createPanoArrows(navigator, rotation));
23028         }
23029         else {
23030             steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
23031             steps = steps.concat(this._createStepArrows(navigator, rotation));
23032             turns = turns.concat(this._createTurnArrows(navigator));
23033         }
23034         return this._getContainer(steps, turns, rotation);
23035     };
23036     DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
23037         this._setEdges(edgeStatus, sequence);
23038         this._setNeedsRender();
23039     };
23040     /**
23041      * Set node for which to show edges.
23042      *
23043      * @param {Node} node
23044      */
23045     DirectionDOMRenderer.prototype.setNode = function (node) {
23046         this._node = node;
23047         this._clearEdges();
23048         this._setNeedsRender();
23049     };
23050     /**
23051      * Set the render camera to use for calculating rotations.
23052      *
23053      * @param {RenderCamera} renderCamera
23054      */
23055     DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
23056         var rotation = renderCamera.rotation;
23057         if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
23058             return;
23059         }
23060         this._rotation = rotation;
23061         this._setNeedsRender();
23062     };
23063     /**
23064      * Set configuration values.
23065      *
23066      * @param {IDirectionConfiguration} configuration
23067      */
23068     DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
23069         var needsRender = false;
23070         if (this._highlightKey !== configuration.highlightKey ||
23071             this._distinguishSequence !== configuration.distinguishSequence) {
23072             this._highlightKey = configuration.highlightKey;
23073             this._distinguishSequence = configuration.distinguishSequence;
23074             needsRender = true;
23075         }
23076         if (this._calculator.minWidth !== configuration.minWidth ||
23077             this._calculator.maxWidth !== configuration.maxWidth) {
23078             this._calculator.configure(configuration);
23079             needsRender = true;
23080         }
23081         if (needsRender) {
23082             this._setNeedsRender();
23083         }
23084     };
23085     /**
23086      * Detect the element's width and height and resize
23087      * elements accordingly.
23088      *
23089      * @param {ISize} size Size of vßiewer container element.
23090      */
23091     DirectionDOMRenderer.prototype.resize = function (size) {
23092         this._calculator.resize(size);
23093         this._setNeedsRender();
23094     };
23095     DirectionDOMRenderer.prototype._setNeedsRender = function () {
23096         if (this._node != null) {
23097             this._needsRender = true;
23098         }
23099     };
23100     DirectionDOMRenderer.prototype._clearEdges = function () {
23101         this._stepEdges = [];
23102         this._turnEdges = [];
23103         this._panoEdges = [];
23104         this._sequenceEdgeKeys = [];
23105     };
23106     DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
23107         this._stepEdges = [];
23108         this._turnEdges = [];
23109         this._panoEdges = [];
23110         this._sequenceEdgeKeys = [];
23111         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
23112             var edge = _a[_i];
23113             var direction = edge.data.direction;
23114             if (this._stepDirections.indexOf(direction) > -1) {
23115                 this._stepEdges.push(edge);
23116                 continue;
23117             }
23118             if (this._turnDirections.indexOf(direction) > -1) {
23119                 this._turnEdges.push(edge);
23120                 continue;
23121             }
23122             if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
23123                 this._panoEdges.push(edge);
23124             }
23125         }
23126         if (this._distinguishSequence && sequence != null) {
23127             var edges = this._panoEdges
23128                 .concat(this._stepEdges)
23129                 .concat(this._turnEdges);
23130             for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
23131                 var edge = edges_1[_b];
23132                 var edgeKey = edge.to;
23133                 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
23134                     var sequenceKey = _d[_c];
23135                     if (sequenceKey === edgeKey) {
23136                         this._sequenceEdgeKeys.push(edgeKey);
23137                         break;
23138                     }
23139                 }
23140             }
23141         }
23142     };
23143     DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
23144         var arrows = [];
23145         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
23146             var panoEdge = _a[_i];
23147             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
23148         }
23149         for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
23150             var stepEdge = _c[_b];
23151             arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
23152         }
23153         return arrows;
23154     };
23155     DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
23156         var threshold = Math.PI / 8;
23157         var relativePhi = rotation.phi;
23158         switch (direction) {
23159             case Edge_1.EdgeDirection.StepBackward:
23160                 relativePhi = rotation.phi - Math.PI;
23161                 break;
23162             case Edge_1.EdgeDirection.StepLeft:
23163                 relativePhi = rotation.phi + Math.PI / 2;
23164                 break;
23165             case Edge_1.EdgeDirection.StepRight:
23166                 relativePhi = rotation.phi - Math.PI / 2;
23167                 break;
23168             default:
23169                 break;
23170         }
23171         if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
23172             return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
23173         }
23174         return this._createVNodeDisabled(key, azimuth, rotation);
23175     };
23176     DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
23177         var arrows = [];
23178         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
23179             var panoEdge = _a[_i];
23180             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
23181         }
23182         return arrows;
23183     };
23184     DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
23185         var arrows = [];
23186         for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
23187             var stepEdge = _a[_i];
23188             arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
23189         }
23190         return arrows;
23191     };
23192     DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
23193         var turns = [];
23194         for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
23195             var turnEdge = _a[_i];
23196             var direction = turnEdge.data.direction;
23197             var name_1 = this._turnNames[direction];
23198             turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
23199         }
23200         return turns;
23201     };
23202     DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
23203         var onClick = function (e) {
23204             navigator.moveToKey$(key)
23205                 .subscribe(undefined, function (error) {
23206                 if (!(error instanceof Error_1.AbortMapillaryError)) {
23207                     console.error(error);
23208                 }
23209             });
23210         };
23211         return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
23212     };
23213     DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
23214         var onClick = function (e) {
23215             navigator.moveDir$(direction)
23216                 .subscribe(undefined, function (error) {
23217                 if (!(error instanceof Error_1.AbortMapillaryError)) {
23218                     console.error(error);
23219                 }
23220             });
23221         };
23222         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
23223     };
23224     DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
23225         var onClick = function (e) {
23226             navigator.moveDir$(direction)
23227                 .subscribe(undefined, function (error) {
23228                 if (!(error instanceof Error_1.AbortMapillaryError)) {
23229                     console.error(error);
23230                 }
23231             });
23232         };
23233         var style = {
23234             height: this._calculator.turnCircleSizeCss,
23235             transform: "rotate(0)",
23236             width: this._calculator.turnCircleSizeCss,
23237         };
23238         switch (direction) {
23239             case Edge_1.EdgeDirection.TurnLeft:
23240                 style.left = "5px";
23241                 style.top = "5px";
23242                 break;
23243             case Edge_1.EdgeDirection.TurnRight:
23244                 style.right = "5px";
23245                 style.top = "5px";
23246                 break;
23247             case Edge_1.EdgeDirection.TurnU:
23248                 style.left = "5px";
23249                 style.bottom = "5px";
23250                 break;
23251             default:
23252                 break;
23253         }
23254         var circleProperties = {
23255             attributes: {
23256                 "data-key": key,
23257             },
23258             onclick: onClick,
23259             style: style,
23260         };
23261         var circleClassName = "TurnCircle";
23262         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
23263             circleClassName += "Sequence";
23264         }
23265         if (this._highlightKey === key) {
23266             circleClassName += "Highlight";
23267         }
23268         var turn = vd.h("div." + className, {}, []);
23269         return vd.h("div." + circleClassName, circleProperties, [turn]);
23270     };
23271     DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
23272         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
23273     };
23274     DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
23275         var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
23276         // rotate 90 degrees clockwise and flip over X-axis
23277         var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
23278         var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
23279         var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
23280         var shadowOffset = this._calculator.shadowOffset;
23281         var shadowTranslationX = -shadowOffset * shadowTranslation[1];
23282         var shadowTranslationY = shadowOffset * shadowTranslation[0];
23283         var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
23284         var properties = {
23285             style: {
23286                 "-webkit-filter": filter,
23287                 filter: filter,
23288             },
23289         };
23290         var chevron = vd.h("div." + className, properties, []);
23291         var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
23292         var circleTransform = shiftVertically ?
23293             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
23294             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
23295         var circleProperties = {
23296             attributes: { "data-key": key },
23297             onclick: onClick,
23298             style: {
23299                 height: this._calculator.stepCircleSizeCss,
23300                 marginLeft: this._calculator.stepCircleMarginCss,
23301                 marginTop: this._calculator.stepCircleMarginCss,
23302                 transform: circleTransform,
23303                 width: this._calculator.stepCircleSizeCss,
23304             },
23305         };
23306         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
23307             circleClassName += "Sequence";
23308         }
23309         if (this._highlightKey === key) {
23310             circleClassName += "Highlight";
23311         }
23312         return vd.h("div." + circleClassName, circleProperties, [chevron]);
23313     };
23314     DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
23315         // edge does not handle hover on perspective transforms.
23316         var transform = this._isEdge ?
23317             "rotateX(60deg)" :
23318             "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
23319         var properties = {
23320             oncontextmenu: function (event) { event.preventDefault(); },
23321             style: {
23322                 bottom: this._calculator.containerBottomCss,
23323                 height: this._calculator.containerHeightCss,
23324                 left: this._calculator.containerLeftCss,
23325                 marginLeft: this._calculator.containerMarginCss,
23326                 transform: transform,
23327                 width: this._calculator.containerWidthCss,
23328             },
23329         };
23330         return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
23331     };
23332     return DirectionDOMRenderer;
23333 }());
23334 exports.DirectionDOMRenderer = DirectionDOMRenderer;
23335 exports.default = DirectionDOMRenderer;
23336
23337
23338 },{"../../Component":274,"../../Edge":275,"../../Error":276,"../../Geo":277,"virtual-dom":230}],304:[function(require,module,exports){
23339 "use strict";
23340 var __extends = (this && this.__extends) || (function () {
23341     var extendStatics = function (d, b) {
23342         extendStatics = Object.setPrototypeOf ||
23343             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23344             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23345         return extendStatics(d, b);
23346     }
23347     return function (d, b) {
23348         extendStatics(d, b);
23349         function __() { this.constructor = d; }
23350         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23351     };
23352 })();
23353 Object.defineProperty(exports, "__esModule", { value: true });
23354 var rxjs_1 = require("rxjs");
23355 var operators_1 = require("rxjs/operators");
23356 var Component_1 = require("../../Component");
23357 var Render_1 = require("../../Render");
23358 var Tiles_1 = require("../../Tiles");
23359 var Utils_1 = require("../../Utils");
23360 var ImagePlaneComponent = /** @class */ (function (_super) {
23361     __extends(ImagePlaneComponent, _super);
23362     function ImagePlaneComponent(name, container, navigator) {
23363         var _this = _super.call(this, name, container, navigator) || this;
23364         _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
23365         _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
23366         _this._rendererOperation$ = new rxjs_1.Subject();
23367         _this._rendererCreator$ = new rxjs_1.Subject();
23368         _this._rendererDisposer$ = new rxjs_1.Subject();
23369         _this._renderer$ = _this._rendererOperation$.pipe(operators_1.scan(function (renderer, operation) {
23370             return operation(renderer);
23371         }, null), operators_1.filter(function (renderer) {
23372             return renderer != null;
23373         }), operators_1.distinctUntilChanged(undefined, function (renderer) {
23374             return renderer.frameId;
23375         }));
23376         _this._rendererCreator$.pipe(operators_1.map(function () {
23377             return function (renderer) {
23378                 if (renderer != null) {
23379                     throw new Error("Multiple image plane states can not be created at the same time");
23380                 }
23381                 return new Component_1.ImagePlaneGLRenderer();
23382             };
23383         }))
23384             .subscribe(_this._rendererOperation$);
23385         _this._rendererDisposer$.pipe(operators_1.map(function () {
23386             return function (renderer) {
23387                 renderer.dispose();
23388                 return null;
23389             };
23390         }))
23391             .subscribe(_this._rendererOperation$);
23392         return _this;
23393     }
23394     ImagePlaneComponent.prototype._activate = function () {
23395         var _this = this;
23396         this._rendererSubscription = this._renderer$.pipe(operators_1.map(function (renderer) {
23397             var renderHash = {
23398                 name: _this._name,
23399                 render: {
23400                     frameId: renderer.frameId,
23401                     needsRender: renderer.needsRender,
23402                     render: renderer.render.bind(renderer),
23403                     stage: Render_1.GLRenderStage.Background,
23404                 },
23405             };
23406             renderer.clearNeedsRender();
23407             return renderHash;
23408         }))
23409             .subscribe(this._container.glRenderer.render$);
23410         this._rendererCreator$.next(null);
23411         this._stateSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
23412             return function (renderer) {
23413                 renderer.updateFrame(frame);
23414                 return renderer;
23415             };
23416         }))
23417             .subscribe(this._rendererOperation$);
23418         var textureProvider$ = this._navigator.stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
23419             return frame.state.currentNode.key;
23420         }), operators_1.withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), operators_1.map(function (_a) {
23421             var frame = _a[0], renderer = _a[1], size = _a[2];
23422             var state = frame.state;
23423             var viewportSize = Math.max(size.width, size.height);
23424             var currentNode = state.currentNode;
23425             var currentTransform = state.currentTransform;
23426             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
23427             return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
23428         }), operators_1.publishReplay(1), operators_1.refCount());
23429         this._textureProviderSubscription = textureProvider$.subscribe(function () { });
23430         this._setTextureProviderSubscription = textureProvider$.pipe(operators_1.map(function (provider) {
23431             return function (renderer) {
23432                 renderer.setTextureProvider(provider.key, provider);
23433                 return renderer;
23434             };
23435         }))
23436             .subscribe(this._rendererOperation$);
23437         this._setTileSizeSubscription = this._container.renderService.size$.pipe(operators_1.switchMap(function (size) {
23438             return rxjs_1.combineLatest(textureProvider$, rxjs_1.of(size)).pipe(operators_1.first());
23439         }))
23440             .subscribe(function (_a) {
23441             var provider = _a[0], size = _a[1];
23442             var viewportSize = Math.max(size.width, size.height);
23443             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
23444             provider.setTileSize(tileSize);
23445         });
23446         this._abortTextureProviderSubscription = textureProvider$.pipe(operators_1.pairwise())
23447             .subscribe(function (pair) {
23448             var previous = pair[0];
23449             previous.abort();
23450         });
23451         var roiTrigger$ = rxjs_1.combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(operators_1.debounceTime(250))).pipe(operators_1.map(function (_a) {
23452             var camera = _a[0], size = _a[1];
23453             return [
23454                 camera.camera.position.clone(),
23455                 camera.camera.lookat.clone(),
23456                 camera.zoom.valueOf(),
23457                 size.height.valueOf(),
23458                 size.width.valueOf()
23459             ];
23460         }), operators_1.pairwise(), operators_1.skipWhile(function (pls) {
23461             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
23462         }), operators_1.map(function (pls) {
23463             var samePosition = pls[0][0].equals(pls[1][0]);
23464             var sameLookat = pls[0][1].equals(pls[1][1]);
23465             var sameZoom = pls[0][2] === pls[1][2];
23466             var sameHeight = pls[0][3] === pls[1][3];
23467             var sameWidth = pls[0][4] === pls[1][4];
23468             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
23469         }), operators_1.distinctUntilChanged(), operators_1.filter(function (stalled) {
23470             return stalled;
23471         }), operators_1.switchMap(function (stalled) {
23472             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.first());
23473         }), operators_1.withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$));
23474         this._setRegionOfInterestSubscription = textureProvider$.pipe(operators_1.switchMap(function (provider) {
23475             return roiTrigger$.pipe(operators_1.map(function (_a) {
23476                 var camera = _a[0], size = _a[1], transform = _a[2];
23477                 return [
23478                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
23479                     provider,
23480                 ];
23481             }));
23482         }), operators_1.filter(function (args) {
23483             return !args[1].disposed;
23484         }))
23485             .subscribe(function (args) {
23486             var roi = args[0];
23487             var provider = args[1];
23488             provider.setRegionOfInterest(roi);
23489         });
23490         var hasTexture$ = textureProvider$.pipe(operators_1.switchMap(function (provider) {
23491             return provider.hasTexture$;
23492         }), operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
23493         this._hasTextureSubscription = hasTexture$.subscribe(function () { });
23494         var nodeImage$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
23495             return frame.state.nodesAhead === 0;
23496         }), operators_1.map(function (frame) {
23497             return frame.state.currentNode;
23498         }), operators_1.distinctUntilChanged(undefined, function (node) {
23499             return node.key;
23500         }), operators_1.debounceTime(1000), operators_1.withLatestFrom(hasTexture$), operators_1.filter(function (args) {
23501             return !args[1];
23502         }), operators_1.map(function (args) {
23503             return args[0];
23504         }), operators_1.filter(function (node) {
23505             return node.pano ?
23506                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
23507                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
23508         }), operators_1.switchMap(function (node) {
23509             var baseImageSize = node.pano ?
23510                 Utils_1.Settings.basePanoramaSize :
23511                 Utils_1.Settings.baseImageSize;
23512             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
23513                 return rxjs_1.empty();
23514             }
23515             var image$ = node
23516                 .cacheImage$(Utils_1.Settings.maxImageSize).pipe(operators_1.map(function (n) {
23517                 return [n.image, n];
23518             }));
23519             return image$.pipe(operators_1.takeUntil(hasTexture$.pipe(operators_1.filter(function (hasTexture) {
23520                 return hasTexture;
23521             }))), operators_1.catchError(function (error, caught) {
23522                 console.error("Failed to fetch high res image (" + node.key + ")", error);
23523                 return rxjs_1.empty();
23524             }));
23525         })).pipe(operators_1.publish(), operators_1.refCount());
23526         this._updateBackgroundSubscription = nodeImage$.pipe(operators_1.withLatestFrom(textureProvider$))
23527             .subscribe(function (args) {
23528             if (args[0][1].key !== args[1].key ||
23529                 args[1].disposed) {
23530                 return;
23531             }
23532             args[1].updateBackground(args[0][0]);
23533         });
23534         this._updateTextureImageSubscription = nodeImage$.pipe(operators_1.map(function (imn) {
23535             return function (renderer) {
23536                 renderer.updateTextureImage(imn[0], imn[1]);
23537                 return renderer;
23538             };
23539         }))
23540             .subscribe(this._rendererOperation$);
23541     };
23542     ImagePlaneComponent.prototype._deactivate = function () {
23543         this._rendererDisposer$.next(null);
23544         this._abortTextureProviderSubscription.unsubscribe();
23545         this._hasTextureSubscription.unsubscribe();
23546         this._rendererSubscription.unsubscribe();
23547         this._setRegionOfInterestSubscription.unsubscribe();
23548         this._setTextureProviderSubscription.unsubscribe();
23549         this._setTileSizeSubscription.unsubscribe();
23550         this._stateSubscription.unsubscribe();
23551         this._textureProviderSubscription.unsubscribe();
23552         this._updateBackgroundSubscription.unsubscribe();
23553         this._updateTextureImageSubscription.unsubscribe();
23554     };
23555     ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
23556         return {};
23557     };
23558     ImagePlaneComponent.componentName = "imagePlane";
23559     return ImagePlaneComponent;
23560 }(Component_1.Component));
23561 exports.ImagePlaneComponent = ImagePlaneComponent;
23562 Component_1.ComponentService.register(ImagePlaneComponent);
23563 exports.default = ImagePlaneComponent;
23564
23565 },{"../../Component":274,"../../Render":280,"../../Tiles":283,"../../Utils":284,"rxjs":26,"rxjs/operators":224}],305:[function(require,module,exports){
23566 "use strict";
23567 Object.defineProperty(exports, "__esModule", { value: true });
23568 var Component_1 = require("../../Component");
23569 var ImagePlaneGLRenderer = /** @class */ (function () {
23570     function ImagePlaneGLRenderer() {
23571         this._factory = new Component_1.MeshFactory();
23572         this._scene = new Component_1.MeshScene();
23573         this._alpha = 0;
23574         this._alphaOld = 0;
23575         this._fadeOutSpeed = 0.05;
23576         this._currentKey = null;
23577         this._previousKey = null;
23578         this._providerDisposers = {};
23579         this._frameId = 0;
23580         this._needsRender = false;
23581     }
23582     Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
23583         get: function () {
23584             return this._frameId;
23585         },
23586         enumerable: true,
23587         configurable: true
23588     });
23589     Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
23590         get: function () {
23591             return this._needsRender;
23592         },
23593         enumerable: true,
23594         configurable: true
23595     });
23596     ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
23597         this._needsRender = true;
23598     };
23599     ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
23600         this._updateFrameId(frame.id);
23601         this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
23602         this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
23603         this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
23604     };
23605     ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
23606         var _this = this;
23607         if (key !== this._currentKey) {
23608             return;
23609         }
23610         var createdSubscription = provider.textureCreated$
23611             .subscribe(function (texture) {
23612             _this._updateTexture(texture);
23613         });
23614         var updatedSubscription = provider.textureUpdated$
23615             .subscribe(function (updated) {
23616             _this._needsRender = true;
23617         });
23618         var dispose = function () {
23619             createdSubscription.unsubscribe();
23620             updatedSubscription.unsubscribe();
23621             provider.dispose();
23622         };
23623         if (key in this._providerDisposers) {
23624             var disposeProvider = this._providerDisposers[key];
23625             disposeProvider();
23626             delete this._providerDisposers[key];
23627         }
23628         this._providerDisposers[key] = dispose;
23629     };
23630     ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
23631         this._needsRender = true;
23632         for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
23633             var plane = _a[_i];
23634             var material = plane.material;
23635             var oldTexture = material.uniforms.projectorTex.value;
23636             material.uniforms.projectorTex.value = null;
23637             oldTexture.dispose();
23638             material.uniforms.projectorTex.value = texture;
23639         }
23640     };
23641     ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
23642         if (this._currentKey !== node.key) {
23643             return;
23644         }
23645         this._needsRender = true;
23646         for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
23647             var plane = _a[_i];
23648             var material = plane.material;
23649             var texture = material.uniforms.projectorTex.value;
23650             texture.image = image;
23651             texture.needsUpdate = true;
23652         }
23653     };
23654     ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
23655         var planeAlpha = this._scene.imagePlanesOld.length ? 1 : this._alpha;
23656         for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
23657             var plane = _a[_i];
23658             plane.material.uniforms.opacity.value = planeAlpha;
23659         }
23660         for (var _b = 0, _c = this._scene.imagePlanesOld; _b < _c.length; _b++) {
23661             var plane = _c[_b];
23662             plane.material.uniforms.opacity.value = this._alphaOld;
23663         }
23664         renderer.render(this._scene.scene, perspectiveCamera);
23665         renderer.render(this._scene.sceneOld, perspectiveCamera);
23666         for (var _d = 0, _e = this._scene.imagePlanes; _d < _e.length; _d++) {
23667             var plane = _e[_d];
23668             plane.material.uniforms.opacity.value = this._alpha;
23669         }
23670         renderer.render(this._scene.scene, perspectiveCamera);
23671     };
23672     ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
23673         this._needsRender = false;
23674     };
23675     ImagePlaneGLRenderer.prototype.dispose = function () {
23676         this._scene.clear();
23677     };
23678     ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
23679         this._frameId = frameId;
23680     };
23681     ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
23682         if (alpha === this._alpha) {
23683             return false;
23684         }
23685         this._alpha = alpha;
23686         return true;
23687     };
23688     ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
23689         if (alpha < 1 || this._alphaOld === 0) {
23690             return false;
23691         }
23692         this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
23693         return true;
23694     };
23695     ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
23696         if (state.currentNode == null || state.currentNode.key === this._currentKey) {
23697             return false;
23698         }
23699         var previousKey = state.previousNode != null ? state.previousNode.key : null;
23700         var currentKey = state.currentNode.key;
23701         if (this._previousKey !== previousKey &&
23702             this._previousKey !== currentKey &&
23703             this._previousKey in this._providerDisposers) {
23704             var disposeProvider = this._providerDisposers[this._previousKey];
23705             disposeProvider();
23706             delete this._providerDisposers[this._previousKey];
23707         }
23708         if (previousKey != null) {
23709             if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
23710                 var previousMesh = this._factory.createMesh(state.previousNode, state.previousTransform);
23711                 this._scene.updateImagePlanes([previousMesh]);
23712             }
23713             this._previousKey = previousKey;
23714         }
23715         this._currentKey = currentKey;
23716         var currentMesh = this._factory.createMesh(state.currentNode, state.currentTransform);
23717         this._scene.updateImagePlanes([currentMesh]);
23718         this._alphaOld = 1;
23719         return true;
23720     };
23721     return ImagePlaneGLRenderer;
23722 }());
23723 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
23724 exports.default = ImagePlaneGLRenderer;
23725
23726 },{"../../Component":274}],306:[function(require,module,exports){
23727 "use strict";
23728 Object.defineProperty(exports, "__esModule", { value: true });
23729 var CoverState;
23730 (function (CoverState) {
23731     CoverState[CoverState["Hidden"] = 0] = "Hidden";
23732     CoverState[CoverState["Loading"] = 1] = "Loading";
23733     CoverState[CoverState["Visible"] = 2] = "Visible";
23734 })(CoverState = exports.CoverState || (exports.CoverState = {}));
23735
23736 },{}],307:[function(require,module,exports){
23737 "use strict";
23738 Object.defineProperty(exports, "__esModule", { value: true });
23739 /**
23740  * Enumeration for slider mode.
23741  *
23742  * @enum {number}
23743  * @readonly
23744  *
23745  * @description Modes for specifying how transitions
23746  * between nodes are performed in slider mode. Only
23747  * applicable when the slider component determines
23748  * that transitions with motion is possilble. When it
23749  * is not, the stationary mode will be applied.
23750  */
23751 var SliderMode;
23752 (function (SliderMode) {
23753     /**
23754      * Transitions with motion.
23755      *
23756      * @description The slider component moves the
23757      * camera between the node origins.
23758      *
23759      * In this mode it is not possible to zoom or pan.
23760      *
23761      * The slider component falls back to stationary
23762      * mode when it determines that the pair of nodes
23763      * does not have a strong enough relation.
23764      */
23765     SliderMode[SliderMode["Motion"] = 0] = "Motion";
23766     /**
23767      * Stationary transitions.
23768      *
23769      * @description The camera is stationary.
23770      *
23771      * In this mode it is possible to zoom and pan.
23772      */
23773     SliderMode[SliderMode["Stationary"] = 1] = "Stationary";
23774 })(SliderMode = exports.SliderMode || (exports.SliderMode = {}));
23775
23776 },{}],308:[function(require,module,exports){
23777 "use strict";
23778 Object.defineProperty(exports, "__esModule", { value: true });
23779 var ICoverConfiguration_1 = require("./ICoverConfiguration");
23780 exports.CoverState = ICoverConfiguration_1.CoverState;
23781 var ISliderConfiguration_1 = require("./ISliderConfiguration");
23782 exports.SliderMode = ISliderConfiguration_1.SliderMode;
23783
23784 },{"./ICoverConfiguration":306,"./ISliderConfiguration":307}],309:[function(require,module,exports){
23785 "use strict";
23786 var __extends = (this && this.__extends) || (function () {
23787     var extendStatics = function (d, b) {
23788         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 extendStatics(d, b);
23792     }
23793     return function (d, b) {
23794         extendStatics(d, b);
23795         function __() { this.constructor = d; }
23796         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23797     };
23798 })();
23799 Object.defineProperty(exports, "__esModule", { value: true });
23800 var operators_1 = require("rxjs/operators");
23801 var Component_1 = require("../../Component");
23802 var Edge_1 = require("../../Edge");
23803 /**
23804  * The `KeyPlayHandler` allows the user to control the play behavior
23805  * using the following key commands:
23806  *
23807  * `Spacebar`: Start or stop playing.
23808  * `SHIFT` + `D`: Switch direction.
23809  * `<`: Decrease speed.
23810  * `>`: Increase speed.
23811  *
23812  * @example
23813  * ```
23814  * var keyboardComponent = viewer.getComponent("keyboard");
23815  *
23816  * keyboardComponent.keyPlay.disable();
23817  * keyboardComponent.keyPlay.enable();
23818  *
23819  * var isEnabled = keyboardComponent.keyPlay.isEnabled;
23820  * ```
23821  */
23822 var KeyPlayHandler = /** @class */ (function (_super) {
23823     __extends(KeyPlayHandler, _super);
23824     function KeyPlayHandler() {
23825         return _super !== null && _super.apply(this, arguments) || this;
23826     }
23827     KeyPlayHandler.prototype._enable = function () {
23828         var _this = this;
23829         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(this._navigator.playService.playing$, this._navigator.playService.direction$, this._navigator.playService.speed$, this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
23830             return node.sequenceEdges$;
23831         }))))
23832             .subscribe(function (_a) {
23833             var event = _a[0], playing = _a[1], direction = _a[2], speed = _a[3], status = _a[4];
23834             if (event.altKey || event.ctrlKey || event.metaKey) {
23835                 return;
23836             }
23837             switch (event.key) {
23838                 case "D":
23839                     if (!event.shiftKey) {
23840                         return;
23841                     }
23842                     var newDirection = playing ?
23843                         null : direction === Edge_1.EdgeDirection.Next ?
23844                         Edge_1.EdgeDirection.Prev : direction === Edge_1.EdgeDirection.Prev ?
23845                         Edge_1.EdgeDirection.Next : null;
23846                     if (newDirection != null) {
23847                         _this._navigator.playService.setDirection(newDirection);
23848                     }
23849                     break;
23850                 case " ":
23851                     if (event.shiftKey) {
23852                         return;
23853                     }
23854                     if (playing) {
23855                         _this._navigator.playService.stop();
23856                     }
23857                     else {
23858                         for (var _i = 0, _b = status.edges; _i < _b.length; _i++) {
23859                             var edge = _b[_i];
23860                             if (edge.data.direction === direction) {
23861                                 _this._navigator.playService.play();
23862                             }
23863                         }
23864                     }
23865                     break;
23866                 case "<":
23867                     _this._navigator.playService.setSpeed(speed - 0.05);
23868                     break;
23869                 case ">":
23870                     _this._navigator.playService.setSpeed(speed + 0.05);
23871                     break;
23872                 default:
23873                     return;
23874             }
23875             event.preventDefault();
23876         });
23877     };
23878     KeyPlayHandler.prototype._disable = function () {
23879         this._keyDownSubscription.unsubscribe();
23880     };
23881     KeyPlayHandler.prototype._getConfiguration = function (enable) {
23882         return { keyZoom: enable };
23883     };
23884     return KeyPlayHandler;
23885 }(Component_1.HandlerBase));
23886 exports.KeyPlayHandler = KeyPlayHandler;
23887 exports.default = KeyPlayHandler;
23888
23889 },{"../../Component":274,"../../Edge":275,"rxjs/operators":224}],310:[function(require,module,exports){
23890 "use strict";
23891 var __extends = (this && this.__extends) || (function () {
23892     var extendStatics = function (d, b) {
23893         extendStatics = Object.setPrototypeOf ||
23894             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23895             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23896         return extendStatics(d, b);
23897     }
23898     return function (d, b) {
23899         extendStatics(d, b);
23900         function __() { this.constructor = d; }
23901         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23902     };
23903 })();
23904 Object.defineProperty(exports, "__esModule", { value: true });
23905 var operators_1 = require("rxjs/operators");
23906 var Component_1 = require("../../Component");
23907 var Edge_1 = require("../../Edge");
23908 var Error_1 = require("../../Error");
23909 /**
23910  * The `KeySequenceNavigationHandler` allows the user to navigate through a sequence using the
23911  * following key commands:
23912  *
23913  * `ALT` + `Up Arrow`: Navigate to next image in the sequence.
23914  * `ALT` + `Down Arrow`: Navigate to previous image in sequence.
23915  *
23916  * @example
23917  * ```
23918  * var keyboardComponent = viewer.getComponent("keyboard");
23919  *
23920  * keyboardComponent.keySequenceNavigation.disable();
23921  * keyboardComponent.keySequenceNavigation.enable();
23922  *
23923  * var isEnabled = keyboardComponent.keySequenceNavigation.isEnabled;
23924  * ```
23925  */
23926 var KeySequenceNavigationHandler = /** @class */ (function (_super) {
23927     __extends(KeySequenceNavigationHandler, _super);
23928     function KeySequenceNavigationHandler() {
23929         return _super !== null && _super.apply(this, arguments) || this;
23930     }
23931     KeySequenceNavigationHandler.prototype._enable = function () {
23932         var _this = this;
23933         var sequenceEdges$ = this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
23934             return node.sequenceEdges$;
23935         }));
23936         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(sequenceEdges$))
23937             .subscribe(function (_a) {
23938             var event = _a[0], edgeStatus = _a[1];
23939             var direction = null;
23940             switch (event.keyCode) {
23941                 case 38: // up
23942                     direction = Edge_1.EdgeDirection.Next;
23943                     break;
23944                 case 40: // down
23945                     direction = Edge_1.EdgeDirection.Prev;
23946                     break;
23947                 default:
23948                     return;
23949             }
23950             event.preventDefault();
23951             if (!event.altKey || event.shiftKey || !edgeStatus.cached) {
23952                 return;
23953             }
23954             for (var _i = 0, _b = edgeStatus.edges; _i < _b.length; _i++) {
23955                 var edge = _b[_i];
23956                 if (edge.data.direction === direction) {
23957                     _this._navigator.moveToKey$(edge.to)
23958                         .subscribe(undefined, function (error) {
23959                         if (!(error instanceof Error_1.AbortMapillaryError)) {
23960                             console.error(error);
23961                         }
23962                     });
23963                     return;
23964                 }
23965             }
23966         });
23967     };
23968     KeySequenceNavigationHandler.prototype._disable = function () {
23969         this._keyDownSubscription.unsubscribe();
23970     };
23971     KeySequenceNavigationHandler.prototype._getConfiguration = function (enable) {
23972         return { keySequenceNavigation: enable };
23973     };
23974     return KeySequenceNavigationHandler;
23975 }(Component_1.HandlerBase));
23976 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler;
23977 exports.default = KeySequenceNavigationHandler;
23978
23979 },{"../../Component":274,"../../Edge":275,"../../Error":276,"rxjs/operators":224}],311:[function(require,module,exports){
23980 "use strict";
23981 var __extends = (this && this.__extends) || (function () {
23982     var extendStatics = function (d, b) {
23983         extendStatics = Object.setPrototypeOf ||
23984             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23985             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23986         return extendStatics(d, b);
23987     }
23988     return function (d, b) {
23989         extendStatics(d, b);
23990         function __() { this.constructor = d; }
23991         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23992     };
23993 })();
23994 Object.defineProperty(exports, "__esModule", { value: true });
23995 var operators_1 = require("rxjs/operators");
23996 var Component_1 = require("../../Component");
23997 var Edge_1 = require("../../Edge");
23998 var Error_1 = require("../../Error");
23999 /**
24000  * The `KeySpatialNavigationHandler` allows the user to navigate through a sequence using the
24001  * following key commands:
24002  *
24003  * `Up Arrow`: Step forward.
24004  * `Down Arrow`: Step backward.
24005  * `Left Arrow`: Step to the left.
24006  * `Rigth Arrow`: Step to the right.
24007  * `SHIFT` + `Down Arrow`: Turn around.
24008  * `SHIFT` + `Left Arrow`: Turn to the left.
24009  * `SHIFT` + `Rigth Arrow`: Turn to the right.
24010  *
24011  * @example
24012  * ```
24013  * var keyboardComponent = viewer.getComponent("keyboard");
24014  *
24015  * keyboardComponent.keySpatialNavigation.disable();
24016  * keyboardComponent.keySpatialNavigation.enable();
24017  *
24018  * var isEnabled = keyboardComponent.keySpatialNavigation.isEnabled;
24019  * ```
24020  */
24021 var KeySpatialNavigationHandler = /** @class */ (function (_super) {
24022     __extends(KeySpatialNavigationHandler, _super);
24023     /** @ignore */
24024     function KeySpatialNavigationHandler(component, container, navigator, spatial) {
24025         var _this = _super.call(this, component, container, navigator) || this;
24026         _this._spatial = spatial;
24027         return _this;
24028     }
24029     KeySpatialNavigationHandler.prototype._enable = function () {
24030         var _this = this;
24031         var spatialEdges$ = this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
24032             return node.spatialEdges$;
24033         }));
24034         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(spatialEdges$, this._navigator.stateService.currentState$))
24035             .subscribe(function (_a) {
24036             var event = _a[0], edgeStatus = _a[1], frame = _a[2];
24037             var pano = frame.state.currentNode.pano;
24038             var direction = null;
24039             switch (event.keyCode) {
24040                 case 37: // left
24041                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
24042                     break;
24043                 case 38: // up
24044                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
24045                     break;
24046                 case 39: // right
24047                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
24048                     break;
24049                 case 40: // down
24050                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
24051                     break;
24052                 default:
24053                     return;
24054             }
24055             event.preventDefault();
24056             if (event.altKey || !edgeStatus.cached ||
24057                 (event.shiftKey && pano)) {
24058                 return;
24059             }
24060             if (!pano) {
24061                 _this._moveDir(direction, edgeStatus);
24062             }
24063             else {
24064                 var shifts = {};
24065                 shifts[Edge_1.EdgeDirection.StepBackward] = Math.PI;
24066                 shifts[Edge_1.EdgeDirection.StepForward] = 0;
24067                 shifts[Edge_1.EdgeDirection.StepLeft] = Math.PI / 2;
24068                 shifts[Edge_1.EdgeDirection.StepRight] = -Math.PI / 2;
24069                 var phi = _this._rotationFromCamera(frame.state.camera).phi;
24070                 var navigationAngle = _this._spatial.wrapAngle(phi + shifts[direction]);
24071                 var threshold = Math.PI / 4;
24072                 var edges = edgeStatus.edges.filter(function (e) {
24073                     return e.data.direction === Edge_1.EdgeDirection.Pano || e.data.direction === direction;
24074                 });
24075                 var smallestAngle = Number.MAX_VALUE;
24076                 var toKey = null;
24077                 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
24078                     var edge = edges_1[_i];
24079                     var angle = Math.abs(_this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
24080                     if (angle < Math.min(smallestAngle, threshold)) {
24081                         smallestAngle = angle;
24082                         toKey = edge.to;
24083                     }
24084                 }
24085                 if (toKey == null) {
24086                     return;
24087                 }
24088                 _this._moveToKey(toKey);
24089             }
24090         });
24091     };
24092     KeySpatialNavigationHandler.prototype._disable = function () {
24093         this._keyDownSubscription.unsubscribe();
24094     };
24095     KeySpatialNavigationHandler.prototype._getConfiguration = function (enable) {
24096         return { keySpatialNavigation: enable };
24097     };
24098     KeySpatialNavigationHandler.prototype._moveDir = function (direction, edgeStatus) {
24099         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
24100             var edge = _a[_i];
24101             if (edge.data.direction === direction) {
24102                 this._moveToKey(edge.to);
24103                 return;
24104             }
24105         }
24106     };
24107     KeySpatialNavigationHandler.prototype._moveToKey = function (key) {
24108         this._navigator.moveToKey$(key)
24109             .subscribe(undefined, function (error) {
24110             if (!(error instanceof Error_1.AbortMapillaryError)) {
24111                 console.error(error);
24112             }
24113         });
24114     };
24115     KeySpatialNavigationHandler.prototype._rotationFromCamera = function (camera) {
24116         var direction = camera.lookat.clone().sub(camera.position);
24117         var upProjection = direction.clone().dot(camera.up);
24118         var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
24119         var phi = Math.atan2(planeProjection.y, planeProjection.x);
24120         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
24121         return { phi: phi, theta: theta };
24122     };
24123     return KeySpatialNavigationHandler;
24124 }(Component_1.HandlerBase));
24125 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler;
24126 exports.default = KeySpatialNavigationHandler;
24127
24128 },{"../../Component":274,"../../Edge":275,"../../Error":276,"rxjs/operators":224}],312:[function(require,module,exports){
24129 "use strict";
24130 var __extends = (this && this.__extends) || (function () {
24131     var extendStatics = function (d, b) {
24132         extendStatics = Object.setPrototypeOf ||
24133             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24134             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24135         return extendStatics(d, b);
24136     }
24137     return function (d, b) {
24138         extendStatics(d, b);
24139         function __() { this.constructor = d; }
24140         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24141     };
24142 })();
24143 Object.defineProperty(exports, "__esModule", { value: true });
24144 var operators_1 = require("rxjs/operators");
24145 var Component_1 = require("../../Component");
24146 /**
24147  * The `KeyZoomHandler` allows the user to zoom in and out using the
24148  * following key commands:
24149  *
24150  * `+`: Zoom in.
24151  * `-`: Zoom out.
24152  *
24153  * @example
24154  * ```
24155  * var keyboardComponent = viewer.getComponent("keyboard");
24156  *
24157  * keyboardComponent.keyZoom.disable();
24158  * keyboardComponent.keyZoom.enable();
24159  *
24160  * var isEnabled = keyboardComponent.keyZoom.isEnabled;
24161  * ```
24162  */
24163 var KeyZoomHandler = /** @class */ (function (_super) {
24164     __extends(KeyZoomHandler, _super);
24165     /** @ignore */
24166     function KeyZoomHandler(component, container, navigator, viewportCoords) {
24167         var _this = _super.call(this, component, container, navigator) || this;
24168         _this._viewportCoords = viewportCoords;
24169         return _this;
24170     }
24171     KeyZoomHandler.prototype._enable = function () {
24172         var _this = this;
24173         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
24174             .subscribe(function (_a) {
24175             var event = _a[0], render = _a[1], transform = _a[2];
24176             if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
24177                 return;
24178             }
24179             var delta = 0;
24180             switch (event.key) {
24181                 case "+":
24182                     delta = 1;
24183                     break;
24184                 case "-":
24185                     delta = -1;
24186                     break;
24187                 default:
24188                     return;
24189             }
24190             event.preventDefault();
24191             var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
24192             var reference = transform.projectBasic(unprojected.toArray());
24193             _this._navigator.stateService.zoomIn(delta, reference);
24194         });
24195     };
24196     KeyZoomHandler.prototype._disable = function () {
24197         this._keyDownSubscription.unsubscribe();
24198     };
24199     KeyZoomHandler.prototype._getConfiguration = function (enable) {
24200         return { keyZoom: enable };
24201     };
24202     return KeyZoomHandler;
24203 }(Component_1.HandlerBase));
24204 exports.KeyZoomHandler = KeyZoomHandler;
24205 exports.default = KeyZoomHandler;
24206
24207 },{"../../Component":274,"rxjs/operators":224}],313:[function(require,module,exports){
24208 "use strict";
24209 var __extends = (this && this.__extends) || (function () {
24210     var extendStatics = function (d, b) {
24211         extendStatics = Object.setPrototypeOf ||
24212             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24213             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24214         return extendStatics(d, b);
24215     }
24216     return function (d, b) {
24217         extendStatics(d, b);
24218         function __() { this.constructor = d; }
24219         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24220     };
24221 })();
24222 Object.defineProperty(exports, "__esModule", { value: true });
24223 var Component_1 = require("../../Component");
24224 var Geo_1 = require("../../Geo");
24225 /**
24226  * @class KeyboardComponent
24227  *
24228  * @classdesc Component for keyboard event handling.
24229  *
24230  * To retrive and use the keyboard component
24231  *
24232  * @example
24233  * ```
24234  * var viewer = new Mapillary.Viewer(
24235  *     "<element-id>",
24236  *     "<client-id>",
24237  *     "<my key>");
24238  *
24239  * var keyboardComponent = viewer.getComponent("keyboard");
24240  * ```
24241  */
24242 var KeyboardComponent = /** @class */ (function (_super) {
24243     __extends(KeyboardComponent, _super);
24244     /** @ignore */
24245     function KeyboardComponent(name, container, navigator) {
24246         var _this = _super.call(this, name, container, navigator) || this;
24247         _this._keyPlayHandler = new Component_1.KeyPlayHandler(_this, container, navigator);
24248         _this._keySequenceNavigationHandler = new Component_1.KeySequenceNavigationHandler(_this, container, navigator);
24249         _this._keySpatialNavigationHandler = new Component_1.KeySpatialNavigationHandler(_this, container, navigator, new Geo_1.Spatial());
24250         _this._keyZoomHandler = new Component_1.KeyZoomHandler(_this, container, navigator, new Geo_1.ViewportCoords());
24251         return _this;
24252     }
24253     Object.defineProperty(KeyboardComponent.prototype, "keyPlay", {
24254         /**
24255          * Get key play.
24256          *
24257          * @returns {KeyPlayHandler} The key play handler.
24258          */
24259         get: function () {
24260             return this._keyPlayHandler;
24261         },
24262         enumerable: true,
24263         configurable: true
24264     });
24265     Object.defineProperty(KeyboardComponent.prototype, "keySequenceNavigation", {
24266         /**
24267          * Get key sequence navigation.
24268          *
24269          * @returns {KeySequenceNavigationHandler} The key sequence navigation handler.
24270          */
24271         get: function () {
24272             return this._keySequenceNavigationHandler;
24273         },
24274         enumerable: true,
24275         configurable: true
24276     });
24277     Object.defineProperty(KeyboardComponent.prototype, "keySpatialNavigation", {
24278         /**
24279          * Get spatial.
24280          *
24281          * @returns {KeySpatialNavigationHandler} The spatial handler.
24282          */
24283         get: function () {
24284             return this._keySpatialNavigationHandler;
24285         },
24286         enumerable: true,
24287         configurable: true
24288     });
24289     Object.defineProperty(KeyboardComponent.prototype, "keyZoom", {
24290         /**
24291          * Get key zoom.
24292          *
24293          * @returns {KeyZoomHandler} The key zoom handler.
24294          */
24295         get: function () {
24296             return this._keyZoomHandler;
24297         },
24298         enumerable: true,
24299         configurable: true
24300     });
24301     KeyboardComponent.prototype._activate = function () {
24302         var _this = this;
24303         this._configurationSubscription = this._configuration$
24304             .subscribe(function (configuration) {
24305             if (configuration.keyPlay) {
24306                 _this._keyPlayHandler.enable();
24307             }
24308             else {
24309                 _this._keyPlayHandler.disable();
24310             }
24311             if (configuration.keySequenceNavigation) {
24312                 _this._keySequenceNavigationHandler.enable();
24313             }
24314             else {
24315                 _this._keySequenceNavigationHandler.disable();
24316             }
24317             if (configuration.keySpatialNavigation) {
24318                 _this._keySpatialNavigationHandler.enable();
24319             }
24320             else {
24321                 _this._keySpatialNavigationHandler.disable();
24322             }
24323             if (configuration.keyZoom) {
24324                 _this._keyZoomHandler.enable();
24325             }
24326             else {
24327                 _this._keyZoomHandler.disable();
24328             }
24329         });
24330     };
24331     KeyboardComponent.prototype._deactivate = function () {
24332         this._configurationSubscription.unsubscribe();
24333         this._keyPlayHandler.disable();
24334         this._keySequenceNavigationHandler.disable();
24335         this._keySpatialNavigationHandler.disable();
24336         this._keyZoomHandler.disable();
24337     };
24338     KeyboardComponent.prototype._getDefaultConfiguration = function () {
24339         return { keyPlay: true, keySequenceNavigation: true, keySpatialNavigation: true, keyZoom: true };
24340     };
24341     KeyboardComponent.componentName = "keyboard";
24342     return KeyboardComponent;
24343 }(Component_1.Component));
24344 exports.KeyboardComponent = KeyboardComponent;
24345 Component_1.ComponentService.register(KeyboardComponent);
24346 exports.default = KeyboardComponent;
24347
24348 },{"../../Component":274,"../../Geo":277}],314:[function(require,module,exports){
24349 "use strict";
24350 Object.defineProperty(exports, "__esModule", { value: true });
24351 var MarkerComponent_1 = require("./MarkerComponent");
24352 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
24353 var SimpleMarker_1 = require("./marker/SimpleMarker");
24354 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
24355 var CircleMarker_1 = require("./marker/CircleMarker");
24356 exports.CircleMarker = CircleMarker_1.CircleMarker;
24357
24358 },{"./MarkerComponent":315,"./marker/CircleMarker":318,"./marker/SimpleMarker":320}],315:[function(require,module,exports){
24359 "use strict";
24360 var __extends = (this && this.__extends) || (function () {
24361     var extendStatics = function (d, b) {
24362         extendStatics = Object.setPrototypeOf ||
24363             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24364             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24365         return extendStatics(d, b);
24366     }
24367     return function (d, b) {
24368         extendStatics(d, b);
24369         function __() { this.constructor = d; }
24370         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24371     };
24372 })();
24373 Object.defineProperty(exports, "__esModule", { value: true });
24374 var rxjs_1 = require("rxjs");
24375 var operators_1 = require("rxjs/operators");
24376 var THREE = require("three");
24377 var when = require("when");
24378 var Component_1 = require("../../Component");
24379 var Render_1 = require("../../Render");
24380 var Graph_1 = require("../../Graph");
24381 var Geo_1 = require("../../Geo");
24382 /**
24383  * @class MarkerComponent
24384  *
24385  * @classdesc Component for showing and editing 3D marker objects.
24386  *
24387  * The `add` method is used for adding new markers or replacing
24388  * markers already in the set.
24389  *
24390  * If a marker already in the set has the same
24391  * id as one of the markers added, the old marker will be removed and
24392  * the added marker will take its place.
24393  *
24394  * It is not possible to update markers in the set by updating any properties
24395  * directly on the marker object. Markers need to be replaced by
24396  * re-adding them for updates to geographic position or configuration
24397  * to be reflected.
24398  *
24399  * Markers added to the marker component can be either interactive
24400  * or non-interactive. Different marker types define their behavior.
24401  * Markers with interaction support can be configured with options
24402  * to respond to dragging inside the viewer and be detected when
24403  * retrieving markers from pixel points with the `getMarkerIdAt` method.
24404  *
24405  * To retrive and use the marker component
24406  *
24407  * @example
24408  * ```
24409  * var viewer = new Mapillary.Viewer(
24410  *     "<element-id>",
24411  *     "<client-id>",
24412  *     "<my key>",
24413  *     { component: { marker: true } });
24414  *
24415  * var markerComponent = viewer.getComponent("marker");
24416  * ```
24417  */
24418 var MarkerComponent = /** @class */ (function (_super) {
24419     __extends(MarkerComponent, _super);
24420     /** @ignore */
24421     function MarkerComponent(name, container, navigator) {
24422         var _this = _super.call(this, name, container, navigator) || this;
24423         _this._relativeGroundAltitude = -2;
24424         _this._geoCoords = new Geo_1.GeoCoords();
24425         _this._graphCalculator = new Graph_1.GraphCalculator();
24426         _this._markerScene = new Component_1.MarkerScene();
24427         _this._markerSet = new Component_1.MarkerSet();
24428         _this._viewportCoords = new Geo_1.ViewportCoords();
24429         return _this;
24430     }
24431     /**
24432      * Add markers to the marker set or replace markers in the marker set.
24433      *
24434      * @description If a marker already in the set has the same
24435      * id as one of the markers added, the old marker will be removed
24436      * the added marker will take its place.
24437      *
24438      * Any marker inside the visible bounding bbox
24439      * will be initialized and placed in the viewer.
24440      *
24441      * @param {Array<Marker>} markers - Markers to add.
24442      *
24443      * @example ```markerComponent.add([marker1, marker2]);```
24444      */
24445     MarkerComponent.prototype.add = function (markers) {
24446         this._markerSet.add(markers);
24447     };
24448     /**
24449      * Returns the marker in the marker set with the specified id, or
24450      * undefined if the id matches no marker.
24451      *
24452      * @param {string} markerId - Id of the marker.
24453      *
24454      * @example ```var marker = markerComponent.get("markerId");```
24455      *
24456      */
24457     MarkerComponent.prototype.get = function (markerId) {
24458         return this._markerSet.get(markerId);
24459     };
24460     /**
24461      * Returns an array of all markers.
24462      *
24463      * @example ```var markers = markerComponent.getAll();```
24464      */
24465     MarkerComponent.prototype.getAll = function () {
24466         return this._markerSet.getAll();
24467     };
24468     /**
24469      * Returns the id of the interactive marker closest to the current camera
24470      * position at the specified point.
24471      *
24472      * @description Notice that the pixelPoint argument requires x, y
24473      * coordinates from pixel space.
24474      *
24475      * With this function, you can use the coordinates provided by mouse
24476      * events to get information out of the marker component.
24477      *
24478      * If no interactive geometry of an interactive marker exist at the pixel
24479      * point, `null` will be returned.
24480      *
24481      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
24482      * @returns {string} Id of the interactive marker closest to the camera. If no
24483      * interactive marker exist at the pixel point, `null` will be returned.
24484      *
24485      * @example
24486      * ```
24487      * markerComponent.getMarkerIdAt([100, 100])
24488      *     .then((markerId) => { console.log(markerId); });
24489      * ```
24490      */
24491     MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
24492         var _this = this;
24493         return when.promise(function (resolve, reject) {
24494             _this._container.renderService.renderCamera$.pipe(operators_1.first(), operators_1.map(function (render) {
24495                 var viewport = _this._viewportCoords
24496                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
24497                 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
24498                 return id;
24499             }))
24500                 .subscribe(function (id) {
24501                 resolve(id);
24502             }, function (error) {
24503                 reject(error);
24504             });
24505         });
24506     };
24507     /**
24508      * Check if a marker exist in the marker set.
24509      *
24510      * @param {string} markerId - Id of the marker.
24511      *
24512      * @example ```var markerExists = markerComponent.has("markerId");```
24513      */
24514     MarkerComponent.prototype.has = function (markerId) {
24515         return this._markerSet.has(markerId);
24516     };
24517     /**
24518      * Remove markers with the specified ids from the marker set.
24519      *
24520      * @param {Array<string>} markerIds - Ids for markers to remove.
24521      *
24522      * @example ```markerComponent.remove(["id-1", "id-2"]);```
24523      */
24524     MarkerComponent.prototype.remove = function (markerIds) {
24525         this._markerSet.remove(markerIds);
24526     };
24527     /**
24528      * Remove all markers from the marker set.
24529      *
24530      * @example ```markerComponent.removeAll();```
24531      */
24532     MarkerComponent.prototype.removeAll = function () {
24533         this._markerSet.removeAll();
24534     };
24535     MarkerComponent.prototype._activate = function () {
24536         var _this = this;
24537         var groundAltitude$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
24538             return frame.state.camera.position.z + _this._relativeGroundAltitude;
24539         }), operators_1.distinctUntilChanged(function (a1, a2) {
24540             return Math.abs(a1 - a2) < 0.01;
24541         }), operators_1.publishReplay(1), operators_1.refCount());
24542         var geoInitiated$ = rxjs_1.combineLatest(groundAltitude$, this._navigator.stateService.reference$).pipe(operators_1.first(), operators_1.map(function () { }), operators_1.publishReplay(1), operators_1.refCount());
24543         var clampedConfiguration$ = this._configuration$.pipe(operators_1.map(function (configuration) {
24544             return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
24545         }));
24546         var currentlatLon$ = this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) { return node.latLon; }), operators_1.publishReplay(1), operators_1.refCount());
24547         var visibleBBox$ = rxjs_1.combineLatest(clampedConfiguration$, currentlatLon$).pipe(operators_1.map(function (_a) {
24548             var configuration = _a[0], latLon = _a[1];
24549             return _this._graphCalculator
24550                 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
24551         }), operators_1.publishReplay(1), operators_1.refCount());
24552         var visibleMarkers$ = rxjs_1.combineLatest(rxjs_1.concat(rxjs_1.of(this._markerSet), this._markerSet.changed$), visibleBBox$).pipe(operators_1.map(function (_a) {
24553             var set = _a[0], bbox = _a[1];
24554             return set.search(bbox);
24555         }));
24556         this._setChangedSubscription = geoInitiated$.pipe(operators_1.switchMap(function () {
24557             return visibleMarkers$.pipe(operators_1.withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$));
24558         }))
24559             .subscribe(function (_a) {
24560             var markers = _a[0], reference = _a[1], alt = _a[2];
24561             var geoCoords = _this._geoCoords;
24562             var markerScene = _this._markerScene;
24563             var sceneMarkers = markerScene.markers;
24564             var markersToRemove = Object.assign({}, sceneMarkers);
24565             for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
24566                 var marker = markers_1[_i];
24567                 if (marker.id in sceneMarkers) {
24568                     delete markersToRemove[marker.id];
24569                 }
24570                 else {
24571                     var point3d = geoCoords
24572                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24573                     markerScene.add(marker, point3d);
24574                 }
24575             }
24576             for (var id in markersToRemove) {
24577                 if (!markersToRemove.hasOwnProperty(id)) {
24578                     continue;
24579                 }
24580                 markerScene.remove(id);
24581             }
24582         });
24583         this._markersUpdatedSubscription = geoInitiated$.pipe(operators_1.switchMap(function () {
24584             return _this._markerSet.updated$.pipe(operators_1.withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$));
24585         }))
24586             .subscribe(function (_a) {
24587             var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
24588             var geoCoords = _this._geoCoords;
24589             var markerScene = _this._markerScene;
24590             for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
24591                 var marker = markers_2[_i];
24592                 var exists = markerScene.has(marker.id);
24593                 var visible = marker.latLon.lat > sw.lat &&
24594                     marker.latLon.lat < ne.lat &&
24595                     marker.latLon.lon > sw.lon &&
24596                     marker.latLon.lon < ne.lon;
24597                 if (visible) {
24598                     var point3d = geoCoords
24599                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24600                     markerScene.add(marker, point3d);
24601                 }
24602                 else if (!visible && exists) {
24603                     markerScene.remove(marker.id);
24604                 }
24605             }
24606         });
24607         this._referenceSubscription = this._navigator.stateService.reference$.pipe(operators_1.skip(1), operators_1.withLatestFrom(groundAltitude$))
24608             .subscribe(function (_a) {
24609             var reference = _a[0], alt = _a[1];
24610             var geoCoords = _this._geoCoords;
24611             var markerScene = _this._markerScene;
24612             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
24613                 var marker = _b[_i];
24614                 var point3d = geoCoords
24615                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24616                 markerScene.update(marker.id, point3d);
24617             }
24618         });
24619         this._adjustHeightSubscription = groundAltitude$.pipe(operators_1.skip(1), operators_1.withLatestFrom(this._navigator.stateService.reference$, currentlatLon$))
24620             .subscribe(function (_a) {
24621             var alt = _a[0], reference = _a[1], latLon = _a[2];
24622             var geoCoords = _this._geoCoords;
24623             var markerScene = _this._markerScene;
24624             var position = geoCoords
24625                 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24626             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
24627                 var marker = _b[_i];
24628                 var point3d = geoCoords
24629                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24630                 var distanceX = point3d[0] - position[0];
24631                 var distanceY = point3d[1] - position[1];
24632                 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
24633                 if (groundDistance > 50) {
24634                     continue;
24635                 }
24636                 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
24637             }
24638         });
24639         this._renderSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
24640             var scene = _this._markerScene;
24641             return {
24642                 name: _this._name,
24643                 render: {
24644                     frameId: frame.id,
24645                     needsRender: scene.needsRender,
24646                     render: scene.render.bind(scene),
24647                     stage: Render_1.GLRenderStage.Foreground,
24648                 },
24649             };
24650         }))
24651             .subscribe(this._container.glRenderer.render$);
24652         var hoveredMarkerId$ = rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$).pipe(operators_1.map(function (_a) {
24653             var render = _a[0], event = _a[1];
24654             var element = _this._container.element;
24655             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
24656             var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
24657             var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
24658             return markerId;
24659         }), operators_1.publishReplay(1), operators_1.refCount());
24660         var draggingStarted$ = this._container.mouseService
24661             .filtered$(this._name, this._container.mouseService.mouseDragStart$).pipe(operators_1.map(function (event) {
24662             return true;
24663         }));
24664         var draggingStopped$ = this._container.mouseService
24665             .filtered$(this._name, this._container.mouseService.mouseDragEnd$).pipe(operators_1.map(function (event) {
24666             return false;
24667         }));
24668         var filteredDragging$ = rxjs_1.merge(draggingStarted$, draggingStopped$).pipe(operators_1.startWith(false));
24669         this._dragEventSubscription = rxjs_1.merge(draggingStarted$.pipe(operators_1.withLatestFrom(hoveredMarkerId$)), rxjs_1.combineLatest(draggingStopped$, rxjs_1.of(null))).pipe(operators_1.startWith([false, null]), operators_1.pairwise())
24670             .subscribe(function (_a) {
24671             var previous = _a[0], current = _a[1];
24672             var dragging = current[0];
24673             var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
24674             var id = dragging ? current[1] : previous[1];
24675             var marker = _this._markerScene.get(id);
24676             var markerEvent = { marker: marker, target: _this, type: eventType };
24677             _this.fire(eventType, markerEvent);
24678         });
24679         var mouseDown$ = rxjs_1.merge(this._container.mouseService.mouseDown$.pipe(operators_1.map(function (event) { return true; })), this._container.mouseService.documentMouseUp$.pipe(operators_1.map(function (event) { return false; }))).pipe(operators_1.startWith(false));
24680         this._mouseClaimSubscription = rxjs_1.combineLatest(this._container.mouseService.active$, hoveredMarkerId$.pipe(operators_1.distinctUntilChanged()), mouseDown$, filteredDragging$).pipe(operators_1.map(function (_a) {
24681             var active = _a[0], markerId = _a[1], mouseDown = _a[2], filteredDragging = _a[3];
24682             return (!active && markerId != null && mouseDown) || filteredDragging;
24683         }), operators_1.distinctUntilChanged())
24684             .subscribe(function (claim) {
24685             if (claim) {
24686                 _this._container.mouseService.claimMouse(_this._name, 1);
24687                 _this._container.mouseService.claimWheel(_this._name, 1);
24688             }
24689             else {
24690                 _this._container.mouseService.unclaimMouse(_this._name);
24691                 _this._container.mouseService.unclaimWheel(_this._name);
24692             }
24693         });
24694         var offset$ = this._container.mouseService
24695             .filtered$(this._name, this._container.mouseService.mouseDragStart$).pipe(operators_1.withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$), operators_1.map(function (_a) {
24696             var e = _a[0], id = _a[1], r = _a[2];
24697             var marker = _this._markerScene.get(id);
24698             var element = _this._container.element;
24699             var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
24700             var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
24701             var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
24702             return [marker, offset, r];
24703         }), operators_1.publishReplay(1), operators_1.refCount());
24704         this._updateMarkerSubscription = this._container.mouseService
24705             .filtered$(this._name, this._container.mouseService.mouseDrag$).pipe(operators_1.withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$))
24706             .subscribe(function (_a) {
24707             var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
24708             if (!_this._markerScene.has(marker.id)) {
24709                 return;
24710             }
24711             var element = _this._container.element;
24712             var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
24713             var groundX = canvasX - offset[0];
24714             var groundY = canvasY - offset[1];
24715             var _d = _this._viewportCoords
24716                 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
24717             var direction = new THREE.Vector3(viewportX, viewportY, 1)
24718                 .unproject(render.perspective)
24719                 .sub(render.perspective.position)
24720                 .normalize();
24721             var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
24722             if (distance < 0) {
24723                 return;
24724             }
24725             var intersection = direction
24726                 .clone()
24727                 .multiplyScalar(distance)
24728                 .add(render.perspective.position);
24729             intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
24730             var _e = _this._geoCoords
24731                 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
24732             _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
24733             _this._markerSet.update(marker);
24734             var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
24735             _this.fire(MarkerComponent.changed, markerEvent);
24736         });
24737     };
24738     MarkerComponent.prototype._deactivate = function () {
24739         this._adjustHeightSubscription.unsubscribe();
24740         this._dragEventSubscription.unsubscribe();
24741         this._markersUpdatedSubscription.unsubscribe();
24742         this._mouseClaimSubscription.unsubscribe();
24743         this._referenceSubscription.unsubscribe();
24744         this._renderSubscription.unsubscribe();
24745         this._setChangedSubscription.unsubscribe();
24746         this._updateMarkerSubscription.unsubscribe();
24747         this._markerScene.clear();
24748     };
24749     MarkerComponent.prototype._getDefaultConfiguration = function () {
24750         return { visibleBBoxSize: 100 };
24751     };
24752     MarkerComponent.componentName = "marker";
24753     /**
24754      * Fired when the position of a marker is changed.
24755      * @event
24756      * @type {IMarkerEvent} markerEvent - Marker event data.
24757      * @example
24758      * ```
24759      * markerComponent.on("changed", function(e) {
24760      *     console.log(e.marker.id, e.marker.latLon);
24761      * });
24762      * ```
24763      */
24764     MarkerComponent.changed = "changed";
24765     /**
24766      * Fired when a marker drag interaction starts.
24767      * @event
24768      * @type {IMarkerEvent} markerEvent - Marker event data.
24769      * @example
24770      * ```
24771      * markerComponent.on("dragstart", function(e) {
24772      *     console.log(e.marker.id, e.marker.latLon);
24773      * });
24774      * ```
24775      */
24776     MarkerComponent.dragstart = "dragstart";
24777     /**
24778      * Fired when a marker drag interaction ends.
24779      * @event
24780      * @type {IMarkerEvent} markerEvent - Marker event data.
24781      * @example
24782      * ```
24783      * markerComponent.on("dragend", function(e) {
24784      *     console.log(e.marker.id, e.marker.latLon);
24785      * });
24786      * ```
24787      */
24788     MarkerComponent.dragend = "dragend";
24789     return MarkerComponent;
24790 }(Component_1.Component));
24791 exports.MarkerComponent = MarkerComponent;
24792 Component_1.ComponentService.register(MarkerComponent);
24793 exports.default = MarkerComponent;
24794
24795
24796 },{"../../Component":274,"../../Geo":277,"../../Graph":278,"../../Render":280,"rxjs":26,"rxjs/operators":224,"three":225,"when":271}],316:[function(require,module,exports){
24797 "use strict";
24798 Object.defineProperty(exports, "__esModule", { value: true });
24799 var THREE = require("three");
24800 var MarkerScene = /** @class */ (function () {
24801     function MarkerScene(scene, raycaster) {
24802         this._needsRender = false;
24803         this._interactiveObjects = [];
24804         this._markers = {};
24805         this._objectMarkers = {};
24806         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
24807         this._scene = !!scene ? scene : new THREE.Scene();
24808     }
24809     Object.defineProperty(MarkerScene.prototype, "markers", {
24810         get: function () {
24811             return this._markers;
24812         },
24813         enumerable: true,
24814         configurable: true
24815     });
24816     Object.defineProperty(MarkerScene.prototype, "needsRender", {
24817         get: function () {
24818             return this._needsRender;
24819         },
24820         enumerable: true,
24821         configurable: true
24822     });
24823     MarkerScene.prototype.add = function (marker, position) {
24824         if (marker.id in this._markers) {
24825             this._dispose(marker.id);
24826         }
24827         marker.createGeometry(position);
24828         this._scene.add(marker.geometry);
24829         this._markers[marker.id] = marker;
24830         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
24831             var interactiveObject = _a[_i];
24832             this._interactiveObjects.push(interactiveObject);
24833             this._objectMarkers[interactiveObject.uuid] = marker.id;
24834         }
24835         this._needsRender = true;
24836     };
24837     MarkerScene.prototype.clear = function () {
24838         for (var id in this._markers) {
24839             if (!this._markers.hasOwnProperty) {
24840                 continue;
24841             }
24842             this._dispose(id);
24843         }
24844         this._needsRender = true;
24845     };
24846     MarkerScene.prototype.get = function (id) {
24847         return this._markers[id];
24848     };
24849     MarkerScene.prototype.getAll = function () {
24850         var _this = this;
24851         return Object
24852             .keys(this._markers)
24853             .map(function (id) { return _this._markers[id]; });
24854     };
24855     MarkerScene.prototype.has = function (id) {
24856         return id in this._markers;
24857     };
24858     MarkerScene.prototype.intersectObjects = function (_a, camera) {
24859         var viewportX = _a[0], viewportY = _a[1];
24860         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
24861         var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
24862         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
24863             var intersect = intersects_1[_i];
24864             if (intersect.object.uuid in this._objectMarkers) {
24865                 return this._objectMarkers[intersect.object.uuid];
24866             }
24867         }
24868         return null;
24869     };
24870     MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
24871         if (!(id in this._markers)) {
24872             return;
24873         }
24874         this._markers[id].lerpAltitude(alt, alpha);
24875         this._needsRender = true;
24876     };
24877     MarkerScene.prototype.remove = function (id) {
24878         if (!(id in this._markers)) {
24879             return;
24880         }
24881         this._dispose(id);
24882         this._needsRender = true;
24883     };
24884     MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
24885         renderer.render(this._scene, perspectiveCamera);
24886         this._needsRender = false;
24887     };
24888     MarkerScene.prototype.update = function (id, position, latLon) {
24889         if (!(id in this._markers)) {
24890             return;
24891         }
24892         var marker = this._markers[id];
24893         marker.updatePosition(position, latLon);
24894         this._needsRender = true;
24895     };
24896     MarkerScene.prototype._dispose = function (id) {
24897         var marker = this._markers[id];
24898         this._scene.remove(marker.geometry);
24899         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
24900             var interactiveObject = _a[_i];
24901             var index = this._interactiveObjects.indexOf(interactiveObject);
24902             if (index !== -1) {
24903                 this._interactiveObjects.splice(index, 1);
24904             }
24905             else {
24906                 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
24907             }
24908             delete this._objectMarkers[interactiveObject.uuid];
24909         }
24910         marker.disposeGeometry();
24911         delete this._markers[id];
24912     };
24913     return MarkerScene;
24914 }());
24915 exports.MarkerScene = MarkerScene;
24916 exports.default = MarkerScene;
24917
24918 },{"three":225}],317:[function(require,module,exports){
24919 "use strict";
24920 Object.defineProperty(exports, "__esModule", { value: true });
24921 var rbush = require("rbush");
24922 var rxjs_1 = require("rxjs");
24923 var MarkerSet = /** @class */ (function () {
24924     function MarkerSet() {
24925         this._hash = {};
24926         this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
24927         this._indexChanged$ = new rxjs_1.Subject();
24928         this._updated$ = new rxjs_1.Subject();
24929     }
24930     Object.defineProperty(MarkerSet.prototype, "changed$", {
24931         get: function () {
24932             return this._indexChanged$;
24933         },
24934         enumerable: true,
24935         configurable: true
24936     });
24937     Object.defineProperty(MarkerSet.prototype, "updated$", {
24938         get: function () {
24939             return this._updated$;
24940         },
24941         enumerable: true,
24942         configurable: true
24943     });
24944     MarkerSet.prototype.add = function (markers) {
24945         var updated = [];
24946         var hash = this._hash;
24947         var index = this._index;
24948         for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
24949             var marker = markers_1[_i];
24950             var id = marker.id;
24951             if (id in hash) {
24952                 index.remove(hash[id]);
24953                 updated.push(marker);
24954             }
24955             var item = {
24956                 lat: marker.latLon.lat,
24957                 lon: marker.latLon.lon,
24958                 marker: marker,
24959             };
24960             hash[id] = item;
24961             index.insert(item);
24962         }
24963         if (updated.length > 0) {
24964             this._updated$.next(updated);
24965         }
24966         if (markers.length > updated.length) {
24967             this._indexChanged$.next(this);
24968         }
24969     };
24970     MarkerSet.prototype.has = function (id) {
24971         return id in this._hash;
24972     };
24973     MarkerSet.prototype.get = function (id) {
24974         return this.has(id) ? this._hash[id].marker : undefined;
24975     };
24976     MarkerSet.prototype.getAll = function () {
24977         return this._index
24978             .all()
24979             .map(function (indexItem) {
24980             return indexItem.marker;
24981         });
24982     };
24983     MarkerSet.prototype.remove = function (ids) {
24984         var hash = this._hash;
24985         var index = this._index;
24986         var changed = false;
24987         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
24988             var id = ids_1[_i];
24989             if (!(id in hash)) {
24990                 continue;
24991             }
24992             var item = hash[id];
24993             index.remove(item);
24994             delete hash[id];
24995             changed = true;
24996         }
24997         if (changed) {
24998             this._indexChanged$.next(this);
24999         }
25000     };
25001     MarkerSet.prototype.removeAll = function () {
25002         this._hash = {};
25003         this._index.clear();
25004         this._indexChanged$.next(this);
25005     };
25006     MarkerSet.prototype.search = function (_a) {
25007         var sw = _a[0], ne = _a[1];
25008         return this._index
25009             .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
25010             .map(function (indexItem) {
25011             return indexItem.marker;
25012         });
25013     };
25014     MarkerSet.prototype.update = function (marker) {
25015         var hash = this._hash;
25016         var index = this._index;
25017         var id = marker.id;
25018         if (!(id in hash)) {
25019             return;
25020         }
25021         index.remove(hash[id]);
25022         var item = {
25023             lat: marker.latLon.lat,
25024             lon: marker.latLon.lon,
25025             marker: marker,
25026         };
25027         hash[id] = item;
25028         index.insert(item);
25029     };
25030     return MarkerSet;
25031 }());
25032 exports.MarkerSet = MarkerSet;
25033 exports.default = MarkerSet;
25034
25035 },{"rbush":25,"rxjs":26}],318:[function(require,module,exports){
25036 "use strict";
25037 var __extends = (this && this.__extends) || (function () {
25038     var extendStatics = function (d, b) {
25039         extendStatics = Object.setPrototypeOf ||
25040             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25041             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25042         return extendStatics(d, b);
25043     }
25044     return function (d, b) {
25045         extendStatics(d, b);
25046         function __() { this.constructor = d; }
25047         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25048     };
25049 })();
25050 Object.defineProperty(exports, "__esModule", { value: true });
25051 var THREE = require("three");
25052 var Component_1 = require("../../../Component");
25053 /**
25054  * @class CircleMarker
25055  *
25056  * @classdesc Non-interactive marker with a flat circle shape. The circle
25057  * marker can not be configured to be interactive.
25058  *
25059  * Circle marker properties can not be updated after creation.
25060  *
25061  * To create and add one `CircleMarker` with default configuration
25062  * and one with configuration use
25063  *
25064  * @example
25065  * ```
25066  * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
25067  *     "id-1",
25068  *     { lat: 0, lon: 0, });
25069  *
25070  * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
25071  *     "id-2",
25072  *     { lat: 0, lon: 0, },
25073  *     {
25074  *         color: "#0Ff",
25075  *         opacity: 0.3,
25076  *         radius: 0.7,
25077  *     });
25078  *
25079  * markerComponent.add([defaultMarker, configuredMarker]);
25080  * ```
25081  */
25082 var CircleMarker = /** @class */ (function (_super) {
25083     __extends(CircleMarker, _super);
25084     function CircleMarker(id, latLon, options) {
25085         var _this = _super.call(this, id, latLon) || this;
25086         options = !!options ? options : {};
25087         _this._color = options.color != null ? options.color : 0xffffff;
25088         _this._opacity = options.opacity != null ? options.opacity : 0.4;
25089         _this._radius = options.radius != null ? options.radius : 1;
25090         return _this;
25091     }
25092     CircleMarker.prototype._createGeometry = function (position) {
25093         var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
25094             color: this._color,
25095             opacity: this._opacity,
25096             transparent: true,
25097         }));
25098         circle.up.fromArray([0, 0, 1]);
25099         circle.renderOrder = -1;
25100         var group = new THREE.Object3D();
25101         group.add(circle);
25102         group.position.fromArray(position);
25103         this._geometry = group;
25104     };
25105     CircleMarker.prototype._disposeGeometry = function () {
25106         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
25107             var mesh = _a[_i];
25108             mesh.geometry.dispose();
25109             mesh.material.dispose();
25110         }
25111     };
25112     CircleMarker.prototype._getInteractiveObjects = function () {
25113         return [];
25114     };
25115     return CircleMarker;
25116 }(Component_1.Marker));
25117 exports.CircleMarker = CircleMarker;
25118 exports.default = CircleMarker;
25119
25120 },{"../../../Component":274,"three":225}],319:[function(require,module,exports){
25121 "use strict";
25122 Object.defineProperty(exports, "__esModule", { value: true });
25123 /**
25124  * @class Marker
25125  *
25126  * @classdesc Represents an abstract marker class that should be extended
25127  * by marker implementations used in the marker component.
25128  */
25129 var Marker = /** @class */ (function () {
25130     function Marker(id, latLon) {
25131         this._id = id;
25132         this._latLon = latLon;
25133     }
25134     Object.defineProperty(Marker.prototype, "id", {
25135         /**
25136          * Get id.
25137          * @returns {string} The id of the marker.
25138          */
25139         get: function () {
25140             return this._id;
25141         },
25142         enumerable: true,
25143         configurable: true
25144     });
25145     Object.defineProperty(Marker.prototype, "geometry", {
25146         /**
25147          * Get geometry.
25148          *
25149          * @ignore
25150          */
25151         get: function () {
25152             return this._geometry;
25153         },
25154         enumerable: true,
25155         configurable: true
25156     });
25157     Object.defineProperty(Marker.prototype, "latLon", {
25158         /**
25159          * Get lat lon.
25160          * @returns {ILatLon} The geographic coordinates of the marker.
25161          */
25162         get: function () {
25163             return this._latLon;
25164         },
25165         enumerable: true,
25166         configurable: true
25167     });
25168     /** @ignore */
25169     Marker.prototype.createGeometry = function (position) {
25170         if (!!this._geometry) {
25171             return;
25172         }
25173         this._createGeometry(position);
25174         // update matrix world if raycasting occurs before first render
25175         this._geometry.updateMatrixWorld(true);
25176     };
25177     /** @ignore */
25178     Marker.prototype.disposeGeometry = function () {
25179         if (!this._geometry) {
25180             return;
25181         }
25182         this._disposeGeometry();
25183         this._geometry = undefined;
25184     };
25185     /** @ignore */
25186     Marker.prototype.getInteractiveObjects = function () {
25187         if (!this._geometry) {
25188             return [];
25189         }
25190         return this._getInteractiveObjects();
25191     };
25192     /** @ignore */
25193     Marker.prototype.lerpAltitude = function (alt, alpha) {
25194         if (!this._geometry) {
25195             return;
25196         }
25197         this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
25198     };
25199     /** @ignore */
25200     Marker.prototype.updatePosition = function (position, latLon) {
25201         if (!!latLon) {
25202             this._latLon.lat = latLon.lat;
25203             this._latLon.lon = latLon.lon;
25204         }
25205         if (!this._geometry) {
25206             return;
25207         }
25208         this._geometry.position.fromArray(position);
25209         this._geometry.updateMatrixWorld(true);
25210     };
25211     return Marker;
25212 }());
25213 exports.Marker = Marker;
25214 exports.default = Marker;
25215
25216 },{}],320:[function(require,module,exports){
25217 "use strict";
25218 var __extends = (this && this.__extends) || (function () {
25219     var extendStatics = function (d, b) {
25220         extendStatics = Object.setPrototypeOf ||
25221             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25222             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25223         return extendStatics(d, b);
25224     }
25225     return function (d, b) {
25226         extendStatics(d, b);
25227         function __() { this.constructor = d; }
25228         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25229     };
25230 })();
25231 Object.defineProperty(exports, "__esModule", { value: true });
25232 var THREE = require("three");
25233 var Component_1 = require("../../../Component");
25234 /**
25235  * @class SimpleMarker
25236  *
25237  * @classdesc Interactive marker with ice cream shape. The sphere
25238  * inside the ice cream can be configured to be interactive.
25239  *
25240  * Simple marker properties can not be updated after creation.
25241  *
25242  * To create and add one `SimpleMarker` with default configuration
25243  * (non-interactive) and one interactive with configuration use
25244  *
25245  * @example
25246  * ```
25247  * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
25248  *     "id-1",
25249  *     { lat: 0, lon: 0, });
25250  *
25251  * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
25252  *     "id-2",
25253  *     { lat: 0, lon: 0, },
25254  *     {
25255  *         ballColor: "#00f",
25256  *         ballOpacity: 0.5,
25257  *         color: "#00f",
25258  *         interactive: true,
25259  *         opacity: 0.3,
25260  *         radius: 0.7,
25261  *     });
25262  *
25263  * markerComponent.add([defaultMarker, interactiveMarker]);
25264  * ```
25265  */
25266 var SimpleMarker = /** @class */ (function (_super) {
25267     __extends(SimpleMarker, _super);
25268     function SimpleMarker(id, latLon, options) {
25269         var _this = _super.call(this, id, latLon) || this;
25270         options = !!options ? options : {};
25271         _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
25272         _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
25273         _this._circleToRayAngle = 2;
25274         _this._color = options.color != null ? options.color : 0xff0000;
25275         _this._interactive = !!options.interactive;
25276         _this._opacity = options.opacity != null ? options.opacity : 0.4;
25277         _this._radius = options.radius != null ? options.radius : 1;
25278         return _this;
25279     }
25280     SimpleMarker.prototype._createGeometry = function (position) {
25281         var radius = this._radius;
25282         var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
25283             color: this._color,
25284             opacity: this._opacity,
25285             transparent: true,
25286         }));
25287         cone.renderOrder = 1;
25288         var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
25289             color: this._ballColor,
25290             opacity: this._ballOpacity,
25291             transparent: true,
25292         }));
25293         ball.position.z = this._markerHeight(radius);
25294         var group = new THREE.Object3D();
25295         group.add(ball);
25296         group.add(cone);
25297         group.position.fromArray(position);
25298         this._geometry = group;
25299     };
25300     SimpleMarker.prototype._disposeGeometry = function () {
25301         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
25302             var mesh = _a[_i];
25303             mesh.geometry.dispose();
25304             mesh.material.dispose();
25305         }
25306     };
25307     SimpleMarker.prototype._getInteractiveObjects = function () {
25308         return this._interactive ? [this._geometry.children[0]] : [];
25309     };
25310     SimpleMarker.prototype._markerHeight = function (radius) {
25311         var t = Math.tan(Math.PI - this._circleToRayAngle);
25312         return radius * Math.sqrt(1 + t * t);
25313     };
25314     SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
25315         var geometry = new THREE.Geometry();
25316         widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
25317         heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
25318         var height = this._markerHeight(radius);
25319         var vertices = [];
25320         for (var y = 0; y <= heightSegments; ++y) {
25321             var verticesRow = [];
25322             for (var x = 0; x <= widthSegments; ++x) {
25323                 var u = x / widthSegments * Math.PI * 2;
25324                 var v = y / heightSegments * Math.PI;
25325                 var r = void 0;
25326                 if (v < this._circleToRayAngle) {
25327                     r = radius;
25328                 }
25329                 else {
25330                     var t = Math.tan(v - this._circleToRayAngle);
25331                     r = radius * Math.sqrt(1 + t * t);
25332                 }
25333                 var vertex = new THREE.Vector3();
25334                 vertex.x = r * Math.cos(u) * Math.sin(v);
25335                 vertex.y = r * Math.sin(u) * Math.sin(v);
25336                 vertex.z = r * Math.cos(v) + height;
25337                 geometry.vertices.push(vertex);
25338                 verticesRow.push(geometry.vertices.length - 1);
25339             }
25340             vertices.push(verticesRow);
25341         }
25342         for (var y = 0; y < heightSegments; ++y) {
25343             for (var x = 0; x < widthSegments; ++x) {
25344                 var v1 = vertices[y][x + 1];
25345                 var v2 = vertices[y][x];
25346                 var v3 = vertices[y + 1][x];
25347                 var v4 = vertices[y + 1][x + 1];
25348                 var n1 = geometry.vertices[v1].clone().normalize();
25349                 var n2 = geometry.vertices[v2].clone().normalize();
25350                 var n3 = geometry.vertices[v3].clone().normalize();
25351                 var n4 = geometry.vertices[v4].clone().normalize();
25352                 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
25353                 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
25354             }
25355         }
25356         geometry.computeFaceNormals();
25357         geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
25358         return geometry;
25359     };
25360     return SimpleMarker;
25361 }(Component_1.Marker));
25362 exports.SimpleMarker = SimpleMarker;
25363 exports.default = SimpleMarker;
25364
25365 },{"../../../Component":274,"three":225}],321:[function(require,module,exports){
25366 "use strict";
25367 var __extends = (this && this.__extends) || (function () {
25368     var extendStatics = function (d, b) {
25369         extendStatics = Object.setPrototypeOf ||
25370             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25371             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25372         return extendStatics(d, b);
25373     }
25374     return function (d, b) {
25375         extendStatics(d, b);
25376         function __() { this.constructor = d; }
25377         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25378     };
25379 })();
25380 Object.defineProperty(exports, "__esModule", { value: true });
25381 var rxjs_1 = require("rxjs");
25382 var operators_1 = require("rxjs/operators");
25383 var Component_1 = require("../../Component");
25384 /**
25385  * The `BounceHandler` ensures that the viewer bounces back to the image
25386  * when drag panning outside of the image edge.
25387  */
25388 var BounceHandler = /** @class */ (function (_super) {
25389     __extends(BounceHandler, _super);
25390     function BounceHandler(component, container, navigator, viewportCoords, spatial) {
25391         var _this = _super.call(this, component, container, navigator) || this;
25392         _this._spatial = spatial;
25393         _this._viewportCoords = viewportCoords;
25394         return _this;
25395     }
25396     BounceHandler.prototype._enable = function () {
25397         var _this = this;
25398         var inTransition$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
25399             return frame.state.alpha < 1;
25400         }));
25401         this._bounceSubscription = rxjs_1.combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$).pipe(operators_1.map(function (noForce) {
25402             return noForce[0] || noForce[1] || noForce[2] || noForce[3];
25403         }), operators_1.distinctUntilChanged(), operators_1.switchMap(function (noForce) {
25404             return noForce ?
25405                 rxjs_1.empty() :
25406                 rxjs_1.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.pipe(operators_1.first()));
25407         }))
25408             .subscribe(function (_a) {
25409             var render = _a[0], transform = _a[1];
25410             if (!transform.hasValidScale && render.camera.focal < 0.1) {
25411                 return;
25412             }
25413             if (render.perspective.aspect === 0 || render.perspective.aspect === Number.POSITIVE_INFINITY) {
25414                 return;
25415             }
25416             var distances = Component_1.ImageBoundary.viewportDistances(transform, render.perspective, _this._viewportCoords);
25417             if (Math.max.apply(Math, distances) < 0.01) {
25418                 return;
25419             }
25420             var horizontalDistance = distances[1] - distances[3];
25421             var verticalDistance = distances[0] - distances[2];
25422             var currentDirection = _this._viewportCoords
25423                 .unprojectFromViewport(0, 0, render.perspective)
25424                 .sub(render.perspective.position);
25425             var directionPhi = _this._viewportCoords
25426                 .unprojectFromViewport(horizontalDistance, 0, render.perspective)
25427                 .sub(render.perspective.position);
25428             var directionTheta = _this._viewportCoords
25429                 .unprojectFromViewport(0, verticalDistance, render.perspective)
25430                 .sub(render.perspective.position);
25431             var phi = (horizontalDistance > 0 ? 1 : -1) * directionPhi.angleTo(currentDirection);
25432             var theta = (verticalDistance > 0 ? 1 : -1) * directionTheta.angleTo(currentDirection);
25433             var threshold = Math.PI / 60;
25434             var coeff = 1e-1;
25435             phi = _this._spatial.clamp(coeff * phi, -threshold, threshold);
25436             theta = _this._spatial.clamp(coeff * theta, -threshold, threshold);
25437             _this._navigator.stateService.rotateUnbounded({ phi: phi, theta: theta });
25438         });
25439     };
25440     BounceHandler.prototype._disable = function () {
25441         this._bounceSubscription.unsubscribe();
25442     };
25443     BounceHandler.prototype._getConfiguration = function () {
25444         return {};
25445     };
25446     return BounceHandler;
25447 }(Component_1.HandlerBase));
25448 exports.BounceHandler = BounceHandler;
25449 exports.default = BounceHandler;
25450
25451 },{"../../Component":274,"rxjs":26,"rxjs/operators":224}],322:[function(require,module,exports){
25452 "use strict";
25453 var __extends = (this && this.__extends) || (function () {
25454     var extendStatics = function (d, b) {
25455         extendStatics = Object.setPrototypeOf ||
25456             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25457             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25458         return extendStatics(d, b);
25459     }
25460     return function (d, b) {
25461         extendStatics(d, b);
25462         function __() { this.constructor = d; }
25463         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25464     };
25465 })();
25466 Object.defineProperty(exports, "__esModule", { value: true });
25467 var rxjs_1 = require("rxjs");
25468 var operators_1 = require("rxjs/operators");
25469 var Component_1 = require("../../Component");
25470 /**
25471  * The `DoubleClickZoomHandler` allows the user to zoom the viewer image at a point by double clicking.
25472  *
25473  * @example
25474  * ```
25475  * var mouseComponent = viewer.getComponent("mouse");
25476  *
25477  * mouseComponent.doubleClickZoom.disable();
25478  * mouseComponent.doubleClickZoom.enable();
25479  *
25480  * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
25481  * ```
25482  */
25483 var DoubleClickZoomHandler = /** @class */ (function (_super) {
25484     __extends(DoubleClickZoomHandler, _super);
25485     /** @ignore */
25486     function DoubleClickZoomHandler(component, container, navigator, viewportCoords) {
25487         var _this = _super.call(this, component, container, navigator) || this;
25488         _this._viewportCoords = viewportCoords;
25489         return _this;
25490     }
25491     DoubleClickZoomHandler.prototype._enable = function () {
25492         var _this = this;
25493         this._zoomSubscription = rxjs_1.merge(this._container.mouseService
25494             .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$.pipe(operators_1.map(function (e) {
25495             var touch = e.touches[0];
25496             return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
25497         }))).pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
25498             .subscribe(function (_a) {
25499             var event = _a[0], render = _a[1], transform = _a[2];
25500             var element = _this._container.element;
25501             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
25502             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25503             var reference = transform.projectBasic(unprojected.toArray());
25504             var delta = !!event.shiftKey ? -1 : 1;
25505             _this._navigator.stateService.zoomIn(delta, reference);
25506         });
25507     };
25508     DoubleClickZoomHandler.prototype._disable = function () {
25509         this._zoomSubscription.unsubscribe();
25510     };
25511     DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
25512         return { doubleClickZoom: enable };
25513     };
25514     return DoubleClickZoomHandler;
25515 }(Component_1.HandlerBase));
25516 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
25517 exports.default = DoubleClickZoomHandler;
25518
25519 },{"../../Component":274,"rxjs":26,"rxjs/operators":224}],323:[function(require,module,exports){
25520 "use strict";
25521 var __extends = (this && this.__extends) || (function () {
25522     var extendStatics = function (d, b) {
25523         extendStatics = Object.setPrototypeOf ||
25524             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25525             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25526         return extendStatics(d, b);
25527     }
25528     return function (d, b) {
25529         extendStatics(d, b);
25530         function __() { this.constructor = d; }
25531         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25532     };
25533 })();
25534 Object.defineProperty(exports, "__esModule", { value: true });
25535 var rxjs_1 = require("rxjs");
25536 var operators_1 = require("rxjs/operators");
25537 var Component_1 = require("../../Component");
25538 /**
25539  * The `DragPanHandler` allows the user to pan the viewer image by clicking and dragging the cursor.
25540  *
25541  * @example
25542  * ```
25543  * var mouseComponent = viewer.getComponent("mouse");
25544  *
25545  * mouseComponent.dragPan.disable();
25546  * mouseComponent.dragPan.enable();
25547  *
25548  * var isEnabled = mouseComponent.dragPan.isEnabled;
25549  * ```
25550  */
25551 var DragPanHandler = /** @class */ (function (_super) {
25552     __extends(DragPanHandler, _super);
25553     /** @ignore */
25554     function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
25555         var _this = _super.call(this, component, container, navigator) || this;
25556         _this._spatial = spatial;
25557         _this._viewportCoords = viewportCoords;
25558         return _this;
25559     }
25560     DragPanHandler.prototype._enable = function () {
25561         var _this = this;
25562         var draggingStarted$ = this._container.mouseService
25563             .filtered$(this._component.name, this._container.mouseService.mouseDragStart$).pipe(operators_1.map(function () {
25564             return true;
25565         }), operators_1.share());
25566         var draggingStopped$ = this._container.mouseService
25567             .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$).pipe(operators_1.map(function () {
25568             return false;
25569         }), operators_1.share());
25570         this._activeMouseSubscription = rxjs_1.merge(draggingStarted$, draggingStopped$)
25571             .subscribe(this._container.mouseService.activate$);
25572         var documentMouseMove$ = rxjs_1.merge(draggingStarted$, draggingStopped$).pipe(operators_1.switchMap(function (dragging) {
25573             return dragging ?
25574                 _this._container.mouseService.documentMouseMove$ :
25575                 rxjs_1.empty();
25576         }));
25577         this._preventDefaultSubscription = rxjs_1.merge(documentMouseMove$, this._container.touchService.touchMove$)
25578             .subscribe(function (event) {
25579             event.preventDefault(); // prevent selection of content outside the viewer
25580         });
25581         var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$.pipe(operators_1.map(function () {
25582             return true;
25583         }));
25584         var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$.pipe(operators_1.map(function () {
25585             return false;
25586         }));
25587         this._activeTouchSubscription = rxjs_1.merge(touchMovingStarted$, touchMovingStopped$)
25588             .subscribe(this._container.touchService.activate$);
25589         var rotation$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
25590             return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
25591         }), operators_1.distinctUntilChanged(), operators_1.switchMap(function (enable) {
25592             if (!enable) {
25593                 return rxjs_1.empty();
25594             }
25595             var mouseDrag$ = Component_1.MouseOperator.filteredPairwiseMouseDrag$(_this._component.name, _this._container.mouseService);
25596             var singleTouchDrag$ = rxjs_1.merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.pipe(operators_1.map(function () { return null; }))).pipe(operators_1.map(function (event) {
25597                 return event != null && event.touches.length > 0 ?
25598                     event.touches[0] : null;
25599             }), operators_1.pairwise(), operators_1.filter(function (pair) {
25600                 return pair[0] != null && pair[1] != null;
25601             }));
25602             return rxjs_1.merge(mouseDrag$, singleTouchDrag$);
25603         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
25604             var events = _a[0], render = _a[1], transform = _a[2];
25605             var previousEvent = events[0];
25606             var event = events[1];
25607             var movementX = event.clientX - previousEvent.clientX;
25608             var movementY = event.clientY - previousEvent.clientY;
25609             var element = _this._container.element;
25610             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
25611             var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
25612                 .sub(render.perspective.position);
25613             var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
25614                 .sub(render.perspective.position);
25615             var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
25616                 .sub(render.perspective.position);
25617             var phi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
25618             var theta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
25619             var distances = Component_1.ImageBoundary.viewportDistances(transform, render.perspective, _this._viewportCoords);
25620             if (distances[0] > 0 && theta < 0) {
25621                 theta /= Math.max(1, 2e2 * distances[0]);
25622             }
25623             if (distances[2] > 0 && theta > 0) {
25624                 theta /= Math.max(1, 2e2 * distances[2]);
25625             }
25626             if (distances[1] > 0 && phi < 0) {
25627                 phi /= Math.max(1, 2e2 * distances[1]);
25628             }
25629             if (distances[3] > 0 && phi > 0) {
25630                 phi /= Math.max(1, 2e2 * distances[3]);
25631             }
25632             return { phi: phi, theta: theta };
25633         }), operators_1.share());
25634         this._rotateWithoutInertiaSubscription = rotation$
25635             .subscribe(function (rotation) {
25636             _this._navigator.stateService.rotateWithoutInertia(rotation);
25637         });
25638         this._rotateSubscription = rotation$.pipe(operators_1.scan(function (rotationBuffer, rotation) {
25639             _this._drainBuffer(rotationBuffer);
25640             rotationBuffer.push([Date.now(), rotation]);
25641             return rotationBuffer;
25642         }, []), operators_1.sample(rxjs_1.merge(this._container.mouseService.filtered$(this._component.name, this._container.mouseService.mouseDragEnd$), this._container.touchService.singleTouchDragEnd$)), operators_1.map(function (rotationBuffer) {
25643             var drainedBuffer = _this._drainBuffer(rotationBuffer.slice());
25644             var rotation = { phi: 0, theta: 0 };
25645             for (var _i = 0, drainedBuffer_1 = drainedBuffer; _i < drainedBuffer_1.length; _i++) {
25646                 var bufferedRotation = drainedBuffer_1[_i];
25647                 rotation.phi += bufferedRotation[1].phi;
25648                 rotation.theta += bufferedRotation[1].theta;
25649             }
25650             var count = drainedBuffer.length;
25651             if (count > 0) {
25652                 rotation.phi /= count;
25653                 rotation.theta /= count;
25654             }
25655             var threshold = Math.PI / 18;
25656             rotation.phi = _this._spatial.clamp(rotation.phi, -threshold, threshold);
25657             rotation.theta = _this._spatial.clamp(rotation.theta, -threshold, threshold);
25658             return rotation;
25659         }))
25660             .subscribe(function (rotation) {
25661             _this._navigator.stateService.rotate(rotation);
25662         });
25663     };
25664     DragPanHandler.prototype._disable = function () {
25665         this._activeMouseSubscription.unsubscribe();
25666         this._activeTouchSubscription.unsubscribe();
25667         this._preventDefaultSubscription.unsubscribe();
25668         this._rotateSubscription.unsubscribe();
25669         this._rotateWithoutInertiaSubscription.unsubscribe();
25670         this._activeMouseSubscription = null;
25671         this._activeTouchSubscription = null;
25672         this._preventDefaultSubscription = null;
25673         this._rotateSubscription = null;
25674     };
25675     DragPanHandler.prototype._getConfiguration = function (enable) {
25676         return { dragPan: enable };
25677     };
25678     DragPanHandler.prototype._drainBuffer = function (buffer) {
25679         var cutoff = 50;
25680         var now = Date.now();
25681         while (buffer.length > 0 && now - buffer[0][0] > cutoff) {
25682             buffer.shift();
25683         }
25684         return buffer;
25685     };
25686     return DragPanHandler;
25687 }(Component_1.HandlerBase));
25688 exports.DragPanHandler = DragPanHandler;
25689 exports.default = DragPanHandler;
25690
25691 },{"../../Component":274,"rxjs":26,"rxjs/operators":224}],324:[function(require,module,exports){
25692 "use strict";
25693 var __extends = (this && this.__extends) || (function () {
25694     var extendStatics = function (d, b) {
25695         extendStatics = Object.setPrototypeOf ||
25696             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25697             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25698         return extendStatics(d, b);
25699     }
25700     return function (d, b) {
25701         extendStatics(d, b);
25702         function __() { this.constructor = d; }
25703         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25704     };
25705 })();
25706 Object.defineProperty(exports, "__esModule", { value: true });
25707 var THREE = require("three");
25708 var rxjs_1 = require("rxjs");
25709 var operators_1 = require("rxjs/operators");
25710 var Component_1 = require("../../Component");
25711 var State_1 = require("../../State");
25712 var EarthControlHandler = /** @class */ (function (_super) {
25713     __extends(EarthControlHandler, _super);
25714     function EarthControlHandler(component, container, navigator, viewportCoords, spatial) {
25715         var _this = _super.call(this, component, container, navigator) || this;
25716         _this._spatial = spatial;
25717         _this._viewportCoords = viewportCoords;
25718         return _this;
25719     }
25720     EarthControlHandler.prototype._enable = function () {
25721         var _this = this;
25722         var earth$ = this._navigator.stateService.state$.pipe(operators_1.map(function (state) {
25723             return state === State_1.State.Earth;
25724         }), operators_1.share());
25725         this._preventDefaultSubscription = earth$.pipe(operators_1.switchMap(function (earth) {
25726             return earth ?
25727                 _this._container.mouseService.mouseWheel$ :
25728                 rxjs_1.empty();
25729         }))
25730             .subscribe(function (event) {
25731             event.preventDefault();
25732         });
25733         this._truckSubscription = earth$.pipe(operators_1.switchMap(function (earth) {
25734             if (!earth) {
25735                 return rxjs_1.empty();
25736             }
25737             return Component_1.MouseOperator.filteredPairwiseMouseDrag$(_this._component.name, _this._container.mouseService).pipe(operators_1.filter(function (_a) {
25738                 var e1 = _a[0], e2 = _a[1];
25739                 return !(e1.ctrlKey && e2.ctrlKey);
25740             }));
25741         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
25742             var _b = _a[0], previous = _b[0], current = _b[1], render = _a[1], transform = _a[2];
25743             var planeNormal = [0, 0, 1];
25744             var planePoint = transform.unprojectBasic([0.5, 0.5], 0);
25745             planePoint[2] -= 2;
25746             var currentIntersection = _this._planeIntersection(current, planeNormal, planePoint, render.perspective, _this._container.element);
25747             var previousIntersection = _this._planeIntersection(previous, planeNormal, planePoint, render.perspective, _this._container.element);
25748             if (!currentIntersection || !previousIntersection) {
25749                 return null;
25750             }
25751             var direction = new THREE.Vector3()
25752                 .subVectors(currentIntersection, previousIntersection)
25753                 .multiplyScalar(-1)
25754                 .toArray();
25755             return direction;
25756         }), operators_1.filter(function (direction) {
25757             return !!direction;
25758         }))
25759             .subscribe(function (direction) {
25760             _this._navigator.stateService.truck(direction);
25761         });
25762         this._orbitSubscription = earth$.pipe(operators_1.switchMap(function (earth) {
25763             if (!earth) {
25764                 return rxjs_1.empty();
25765             }
25766             return Component_1.MouseOperator.filteredPairwiseMouseDrag$(_this._component.name, _this._container.mouseService).pipe(operators_1.filter(function (_a) {
25767                 var e1 = _a[0], e2 = _a[1];
25768                 return e1.ctrlKey && e2.ctrlKey;
25769             }));
25770         }), operators_1.map(function (_a) {
25771             var previous = _a[0], current = _a[1];
25772             var _b = _this._eventToViewport(current, _this._container.element), currentX = _b[0], currentY = _b[1];
25773             var _c = _this._eventToViewport(previous, _this._container.element), previousX = _c[0], previousY = _c[1];
25774             var phi = (previousX - currentX) * Math.PI;
25775             var theta = (currentY - previousY) * Math.PI / 2;
25776             return { phi: phi, theta: theta };
25777         }))
25778             .subscribe(function (rotation) {
25779             _this._navigator.stateService.orbit(rotation);
25780         });
25781         this._dollySubscription = earth$.pipe(operators_1.switchMap(function (earth) {
25782             if (!earth) {
25783                 return rxjs_1.empty();
25784             }
25785             return _this._container.mouseService
25786                 .filteredWheel$(_this._component.name, _this._container.mouseService.mouseWheel$);
25787         }), operators_1.map(function (event) {
25788             var delta = event.deltaY;
25789             if (event.deltaMode === 1) {
25790                 delta = 40 * delta;
25791             }
25792             else if (event.deltaMode === 2) {
25793                 delta = 800 * delta;
25794             }
25795             var canvasSize = _this._viewportCoords.containerToCanvas(_this._container.element);
25796             return -delta / canvasSize[1];
25797         }))
25798             .subscribe(function (delta) {
25799             _this._navigator.stateService.dolly(delta);
25800         });
25801     };
25802     EarthControlHandler.prototype._disable = function () {
25803         this._dollySubscription.unsubscribe();
25804         this._orbitSubscription.unsubscribe();
25805         this._preventDefaultSubscription.unsubscribe();
25806         this._truckSubscription.unsubscribe();
25807     };
25808     EarthControlHandler.prototype._getConfiguration = function () {
25809         return {};
25810     };
25811     EarthControlHandler.prototype._eventToViewport = function (event, element) {
25812         var previousCanvas = this._viewportCoords.canvasPosition(event, element);
25813         return this._viewportCoords.canvasToViewport(previousCanvas[0], previousCanvas[1], element);
25814     };
25815     EarthControlHandler.prototype._planeIntersection = function (event, planeNormal, planePoint, camera, element) {
25816         var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
25817         var direction = this._viewportCoords
25818             .unprojectFromCanvas(canvasX, canvasY, element, camera)
25819             .sub(camera.position)
25820             .normalize();
25821         if (Math.abs(this._spatial.angleToPlane(direction.toArray(), planeNormal)) < Math.PI / 90) {
25822             return null;
25823         }
25824         var l0 = camera.position.clone();
25825         var n = new THREE.Vector3().fromArray(planeNormal);
25826         var p0 = new THREE.Vector3().fromArray(planePoint);
25827         var d = new THREE.Vector3().subVectors(p0, l0).dot(n) / direction.clone().dot(n);
25828         var intersection = new THREE.Vector3().addVectors(l0, direction.multiplyScalar(d));
25829         if (this._viewportCoords.worldToCamera(intersection.toArray(), camera)[2] > 0) {
25830             return null;
25831         }
25832         return intersection;
25833     };
25834     return EarthControlHandler;
25835 }(Component_1.HandlerBase));
25836 exports.EarthControlHandler = EarthControlHandler;
25837 exports.default = EarthControlHandler;
25838
25839 },{"../../Component":274,"../../State":281,"rxjs":26,"rxjs/operators":224,"three":225}],325:[function(require,module,exports){
25840 "use strict";
25841 Object.defineProperty(exports, "__esModule", { value: true });
25842 var Geo_1 = require("../../../src/Geo");
25843 function basicBoundaryPoints(pointsPerSide) {
25844     var points = [];
25845     var os = [[0, 0], [1, 0], [1, 1], [0, 1]];
25846     var ds = [[1, 0], [0, 1], [-1, 0], [0, -1]];
25847     for (var side = 0; side < 4; ++side) {
25848         var o = os[side];
25849         var d = ds[side];
25850         for (var i = 0; i < pointsPerSide; ++i) {
25851             points.push([o[0] + d[0] * i / pointsPerSide,
25852                 o[1] + d[1] * i / pointsPerSide]);
25853         }
25854     }
25855     return points;
25856 }
25857 function insideViewport(x, y) {
25858     return x >= -1 && x <= 1 && y >= -1 && y <= 1;
25859 }
25860 function insideBasic(x, y) {
25861     return x >= 0 && x <= 1 && y >= 0 && y <= 1;
25862 }
25863 function viewportDistances(transform, perspective, viewportCoords) {
25864     var boundaryPointsBasic = basicBoundaryPoints(100);
25865     var boundaryPointsViewport = boundaryPointsBasic
25866         .map(function (basic) {
25867         return viewportCoords.basicToViewportSafe(basic[0], basic[1], transform, perspective);
25868     });
25869     var visibleBoundaryPoints = [];
25870     var viewportSides = [
25871         { x: -1, y: 1 },
25872         { x: 1, y: 1 },
25873         { x: 1, y: -1 },
25874         { x: -1, y: -1 }
25875     ];
25876     var intersections = [false, false, false, false];
25877     for (var i = 0; i < boundaryPointsViewport.length; i++) {
25878         var p1 = boundaryPointsViewport[i];
25879         var p2 = boundaryPointsViewport[(i + 1) % boundaryPointsViewport.length];
25880         if (p1 === null) {
25881             continue;
25882         }
25883         if (p2 === null) {
25884             if (insideViewport(p1[0], p1[1])) {
25885                 visibleBoundaryPoints.push(p1);
25886             }
25887             continue;
25888         }
25889         var x1 = p1[0], y1 = p1[1];
25890         var x2 = p2[0], y2 = p2[1];
25891         if (insideViewport(x1, y1)) {
25892             if (insideViewport(x2, y2)) {
25893                 visibleBoundaryPoints.push(p1);
25894             }
25895             else {
25896                 for (var side = 0; side < 4; side++) {
25897                     var s1 = { p1: { x: x1, y: y1 }, p2: { x: x2, y: y2 } };
25898                     var s2 = { p1: viewportSides[side], p2: viewportSides[(side + 1) % 4] };
25899                     var intersecting = Geo_1.Lines.segmentsIntersect(s1, s2);
25900                     if (intersecting) {
25901                         var intersection = Geo_1.Lines.segmentIntersection(s1, s2);
25902                         visibleBoundaryPoints.push(p1, [intersection.x, intersection.y]);
25903                         intersections[side] = true;
25904                     }
25905                 }
25906             }
25907         }
25908     }
25909     var _a = viewportCoords.viewportToBasic(-1, 1, transform, perspective), topLeftBasicX = _a[0], topLeftBasicY = _a[1];
25910     var _b = viewportCoords.viewportToBasic(1, 1, transform, perspective), topRightBasicX = _b[0], topRightBasicY = _b[1];
25911     var _c = viewportCoords.viewportToBasic(1, -1, transform, perspective), bottomRightBasicX = _c[0], bottomRightBasicY = _c[1];
25912     var _d = viewportCoords.viewportToBasic(-1, -1, transform, perspective), bottomLeftBasicX = _d[0], bottomLeftBasicY = _d[1];
25913     if (insideBasic(topLeftBasicX, topLeftBasicY)) {
25914         intersections[3] = intersections[0] = true;
25915     }
25916     if (insideBasic(topRightBasicX, topRightBasicY)) {
25917         intersections[0] = intersections[1] = true;
25918     }
25919     if (insideBasic(bottomRightBasicX, bottomRightBasicY)) {
25920         intersections[1] = intersections[2] = true;
25921     }
25922     if (insideBasic(bottomLeftBasicX, bottomLeftBasicY)) {
25923         intersections[2] = intersections[3] = true;
25924     }
25925     var maximums = [-1, -1, 1, 1];
25926     for (var _i = 0, visibleBoundaryPoints_1 = visibleBoundaryPoints; _i < visibleBoundaryPoints_1.length; _i++) {
25927         var visibleBoundaryPoint = visibleBoundaryPoints_1[_i];
25928         var x = visibleBoundaryPoint[0];
25929         var y = visibleBoundaryPoint[1];
25930         if (x > maximums[1]) {
25931             maximums[1] = x;
25932         }
25933         if (x < maximums[3]) {
25934             maximums[3] = x;
25935         }
25936         if (y > maximums[0]) {
25937             maximums[0] = y;
25938         }
25939         if (y < maximums[2]) {
25940             maximums[2] = y;
25941         }
25942     }
25943     var boundary = [1, 1, -1, -1];
25944     var distances = [];
25945     for (var side = 0; side < 4; side++) {
25946         if (intersections[side]) {
25947             distances.push(0);
25948             continue;
25949         }
25950         distances.push(Math.abs(boundary[side] - maximums[side]));
25951     }
25952     return distances;
25953 }
25954 exports.viewportDistances = viewportDistances;
25955
25956 },{"../../../src/Geo":277}],326:[function(require,module,exports){
25957 "use strict";
25958 var __extends = (this && this.__extends) || (function () {
25959     var extendStatics = function (d, b) {
25960         extendStatics = Object.setPrototypeOf ||
25961             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25962             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25963         return extendStatics(d, b);
25964     }
25965     return function (d, b) {
25966         extendStatics(d, b);
25967         function __() { this.constructor = d; }
25968         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25969     };
25970 })();
25971 Object.defineProperty(exports, "__esModule", { value: true });
25972 var Component_1 = require("../../Component");
25973 var Geo_1 = require("../../Geo");
25974 /**
25975  * @class MouseComponent
25976  *
25977  * @classdesc Component handling mouse and touch events for camera movement.
25978  *
25979  * To retrive and use the mouse component
25980  *
25981  * @example
25982  * ```
25983  * var viewer = new Mapillary.Viewer(
25984  *     "<element-id>",
25985  *     "<client-id>",
25986  *     "<my key>");
25987  *
25988  * var mouseComponent = viewer.getComponent("mouse");
25989  * ```
25990  */
25991 var MouseComponent = /** @class */ (function (_super) {
25992     __extends(MouseComponent, _super);
25993     /** @ignore */
25994     function MouseComponent(name, container, navigator) {
25995         var _this = _super.call(this, name, container, navigator) || this;
25996         var spatial = new Geo_1.Spatial();
25997         var viewportCoords = new Geo_1.ViewportCoords();
25998         _this._bounceHandler = new Component_1.BounceHandler(_this, container, navigator, viewportCoords, spatial);
25999         _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
26000         _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
26001         _this._earthControlHandler = new Component_1.EarthControlHandler(_this, container, navigator, viewportCoords, spatial);
26002         _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
26003         _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
26004         return _this;
26005     }
26006     Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
26007         /**
26008          * Get double click zoom.
26009          *
26010          * @returns {DoubleClickZoomHandler} The double click zoom handler.
26011          */
26012         get: function () {
26013             return this._doubleClickZoomHandler;
26014         },
26015         enumerable: true,
26016         configurable: true
26017     });
26018     Object.defineProperty(MouseComponent.prototype, "dragPan", {
26019         /**
26020          * Get drag pan.
26021          *
26022          * @returns {DragPanHandler} The drag pan handler.
26023          */
26024         get: function () {
26025             return this._dragPanHandler;
26026         },
26027         enumerable: true,
26028         configurable: true
26029     });
26030     Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
26031         /**
26032          * Get scroll zoom.
26033          *
26034          * @returns {ScrollZoomHandler} The scroll zoom handler.
26035          */
26036         get: function () {
26037             return this._scrollZoomHandler;
26038         },
26039         enumerable: true,
26040         configurable: true
26041     });
26042     Object.defineProperty(MouseComponent.prototype, "touchZoom", {
26043         /**
26044          * Get touch zoom.
26045          *
26046          * @returns {TouchZoomHandler} The touch zoom handler.
26047          */
26048         get: function () {
26049             return this._touchZoomHandler;
26050         },
26051         enumerable: true,
26052         configurable: true
26053     });
26054     MouseComponent.prototype._activate = function () {
26055         var _this = this;
26056         this._bounceHandler.enable();
26057         this._earthControlHandler.enable();
26058         this._configurationSubscription = this._configuration$
26059             .subscribe(function (configuration) {
26060             if (configuration.doubleClickZoom) {
26061                 _this._doubleClickZoomHandler.enable();
26062             }
26063             else {
26064                 _this._doubleClickZoomHandler.disable();
26065             }
26066             if (configuration.dragPan) {
26067                 _this._dragPanHandler.enable();
26068             }
26069             else {
26070                 _this._dragPanHandler.disable();
26071             }
26072             if (configuration.scrollZoom) {
26073                 _this._scrollZoomHandler.enable();
26074             }
26075             else {
26076                 _this._scrollZoomHandler.disable();
26077             }
26078             if (configuration.touchZoom) {
26079                 _this._touchZoomHandler.enable();
26080             }
26081             else {
26082                 _this._touchZoomHandler.disable();
26083             }
26084         });
26085         this._container.mouseService.claimMouse(this._name, 0);
26086     };
26087     MouseComponent.prototype._deactivate = function () {
26088         this._container.mouseService.unclaimMouse(this._name);
26089         this._configurationSubscription.unsubscribe();
26090         this._bounceHandler.disable();
26091         this._doubleClickZoomHandler.disable();
26092         this._dragPanHandler.disable();
26093         this._earthControlHandler.disable();
26094         this._scrollZoomHandler.disable();
26095         this._touchZoomHandler.disable();
26096     };
26097     MouseComponent.prototype._getDefaultConfiguration = function () {
26098         return { doubleClickZoom: false, dragPan: true, scrollZoom: true, touchZoom: true };
26099     };
26100     /** @inheritdoc */
26101     MouseComponent.componentName = "mouse";
26102     return MouseComponent;
26103 }(Component_1.Component));
26104 exports.MouseComponent = MouseComponent;
26105 Component_1.ComponentService.register(MouseComponent);
26106 exports.default = MouseComponent;
26107
26108 },{"../../Component":274,"../../Geo":277}],327:[function(require,module,exports){
26109 "use strict";
26110 var __extends = (this && this.__extends) || (function () {
26111     var extendStatics = function (d, b) {
26112         extendStatics = Object.setPrototypeOf ||
26113             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26114             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26115         return extendStatics(d, b);
26116     }
26117     return function (d, b) {
26118         extendStatics(d, b);
26119         function __() { this.constructor = d; }
26120         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26121     };
26122 })();
26123 Object.defineProperty(exports, "__esModule", { value: true });
26124 var operators_1 = require("rxjs/operators");
26125 var Component_1 = require("../../Component");
26126 /**
26127  * The `ScrollZoomHandler` allows the user to zoom the viewer image by scrolling.
26128  *
26129  * @example
26130  * ```
26131  * var mouseComponent = viewer.getComponent("mouse");
26132  *
26133  * mouseComponent.scrollZoom.disable();
26134  * mouseComponent.scrollZoom.enable();
26135  *
26136  * var isEnabled = mouseComponent.scrollZoom.isEnabled;
26137  * ```
26138  */
26139 var ScrollZoomHandler = /** @class */ (function (_super) {
26140     __extends(ScrollZoomHandler, _super);
26141     /** @ignore */
26142     function ScrollZoomHandler(component, container, navigator, viewportCoords) {
26143         var _this = _super.call(this, component, container, navigator) || this;
26144         _this._viewportCoords = viewportCoords;
26145         return _this;
26146     }
26147     ScrollZoomHandler.prototype._enable = function () {
26148         var _this = this;
26149         this._container.mouseService.claimWheel(this._component.name, 0);
26150         this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
26151             .subscribe(function (event) {
26152             event.preventDefault();
26153         });
26154         this._zoomSubscription = this._container.mouseService
26155             .filteredWheel$(this._component.name, this._container.mouseService.mouseWheel$).pipe(operators_1.withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
26156             return [w, f];
26157         }), operators_1.filter(function (args) {
26158             var state = args[1].state;
26159             return state.currentNode.fullPano || state.nodesAhead < 1;
26160         }), operators_1.map(function (args) {
26161             return args[0];
26162         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
26163             return [w, r, t];
26164         }))
26165             .subscribe(function (args) {
26166             var event = args[0];
26167             var render = args[1];
26168             var transform = args[2];
26169             var element = _this._container.element;
26170             var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
26171             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
26172             var reference = transform.projectBasic(unprojected.toArray());
26173             var deltaY = event.deltaY;
26174             if (event.deltaMode === 1) {
26175                 deltaY = 40 * deltaY;
26176             }
26177             else if (event.deltaMode === 2) {
26178                 deltaY = 800 * deltaY;
26179             }
26180             var canvasSize = _this._viewportCoords.containerToCanvas(element);
26181             var zoom = -3 * deltaY / canvasSize[1];
26182             _this._navigator.stateService.zoomIn(zoom, reference);
26183         });
26184     };
26185     ScrollZoomHandler.prototype._disable = function () {
26186         this._container.mouseService.unclaimWheel(this._component.name);
26187         this._preventDefaultSubscription.unsubscribe();
26188         this._zoomSubscription.unsubscribe();
26189         this._preventDefaultSubscription = null;
26190         this._zoomSubscription = null;
26191     };
26192     ScrollZoomHandler.prototype._getConfiguration = function (enable) {
26193         return { scrollZoom: enable };
26194     };
26195     return ScrollZoomHandler;
26196 }(Component_1.HandlerBase));
26197 exports.ScrollZoomHandler = ScrollZoomHandler;
26198 exports.default = ScrollZoomHandler;
26199
26200 },{"../../Component":274,"rxjs/operators":224}],328:[function(require,module,exports){
26201 "use strict";
26202 var __extends = (this && this.__extends) || (function () {
26203     var extendStatics = function (d, b) {
26204         extendStatics = Object.setPrototypeOf ||
26205             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26206             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26207         return extendStatics(d, b);
26208     }
26209     return function (d, b) {
26210         extendStatics(d, b);
26211         function __() { this.constructor = d; }
26212         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26213     };
26214 })();
26215 Object.defineProperty(exports, "__esModule", { value: true });
26216 var rxjs_1 = require("rxjs");
26217 var operators_1 = require("rxjs/operators");
26218 var Component_1 = require("../../Component");
26219 /**
26220  * The `TouchZoomHandler` allows the user to zoom the viewer image by pinching on a touchscreen.
26221  *
26222  * @example
26223  * ```
26224  * var mouseComponent = viewer.getComponent("mouse");
26225  *
26226  * mouseComponent.touchZoom.disable();
26227  * mouseComponent.touchZoom.enable();
26228  *
26229  * var isEnabled = mouseComponent.touchZoom.isEnabled;
26230  * ```
26231  */
26232 var TouchZoomHandler = /** @class */ (function (_super) {
26233     __extends(TouchZoomHandler, _super);
26234     /** @ignore */
26235     function TouchZoomHandler(component, container, navigator, viewportCoords) {
26236         var _this = _super.call(this, component, container, navigator) || this;
26237         _this._viewportCoords = viewportCoords;
26238         return _this;
26239     }
26240     TouchZoomHandler.prototype._enable = function () {
26241         var _this = this;
26242         this._preventDefaultSubscription = this._container.touchService.pinch$
26243             .subscribe(function (pinch) {
26244             pinch.originalEvent.preventDefault();
26245         });
26246         var pinchStarted$ = this._container.touchService.pinchStart$.pipe(operators_1.map(function (event) {
26247             return true;
26248         }));
26249         var pinchStopped$ = this._container.touchService.pinchEnd$.pipe(operators_1.map(function (event) {
26250             return false;
26251         }));
26252         this._activeSubscription = rxjs_1.merge(pinchStarted$, pinchStopped$)
26253             .subscribe(this._container.touchService.activate$);
26254         this._zoomSubscription = this._container.touchService.pinch$.pipe(operators_1.withLatestFrom(this._navigator.stateService.currentState$), operators_1.filter(function (args) {
26255             var state = args[1].state;
26256             return state.currentNode.fullPano || state.nodesAhead < 1;
26257         }), operators_1.map(function (args) {
26258             return args[0];
26259         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
26260             .subscribe(function (_a) {
26261             var pinch = _a[0], render = _a[1], transform = _a[2];
26262             var element = _this._container.element;
26263             var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
26264             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
26265             var reference = transform.projectBasic(unprojected.toArray());
26266             var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
26267             var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
26268             _this._navigator.stateService.zoomIn(zoom, reference);
26269         });
26270     };
26271     TouchZoomHandler.prototype._disable = function () {
26272         this._activeSubscription.unsubscribe();
26273         this._preventDefaultSubscription.unsubscribe();
26274         this._zoomSubscription.unsubscribe();
26275         this._preventDefaultSubscription = null;
26276         this._zoomSubscription = null;
26277     };
26278     TouchZoomHandler.prototype._getConfiguration = function (enable) {
26279         return { touchZoom: enable };
26280     };
26281     return TouchZoomHandler;
26282 }(Component_1.HandlerBase));
26283 exports.TouchZoomHandler = TouchZoomHandler;
26284 exports.default = TouchZoomHandler;
26285
26286 },{"../../Component":274,"rxjs":26,"rxjs/operators":224}],329:[function(require,module,exports){
26287 "use strict";
26288 Object.defineProperty(exports, "__esModule", { value: true });
26289 var Popup_1 = require("./popup/Popup");
26290 exports.Popup = Popup_1.Popup;
26291 var PopupComponent_1 = require("./PopupComponent");
26292 exports.PopupComponent = PopupComponent_1.PopupComponent;
26293
26294 },{"./PopupComponent":330,"./popup/Popup":331}],330:[function(require,module,exports){
26295 "use strict";
26296 var __extends = (this && this.__extends) || (function () {
26297     var extendStatics = function (d, b) {
26298         extendStatics = Object.setPrototypeOf ||
26299             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26300             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26301         return extendStatics(d, b);
26302     }
26303     return function (d, b) {
26304         extendStatics(d, b);
26305         function __() { this.constructor = d; }
26306         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26307     };
26308 })();
26309 Object.defineProperty(exports, "__esModule", { value: true });
26310 var rxjs_1 = require("rxjs");
26311 var operators_1 = require("rxjs/operators");
26312 var Component_1 = require("../../Component");
26313 var Utils_1 = require("../../Utils");
26314 /**
26315  * @class PopupComponent
26316  *
26317  * @classdesc Component for showing HTML popup objects.
26318  *
26319  * The `add` method is used for adding new popups. Popups are removed by reference.
26320  *
26321  * It is not possible to update popups in the set by updating any properties
26322  * directly on the popup object. Popups need to be replaced by
26323  * removing them and creating new ones with relevant changed properties and
26324  * adding those instead.
26325  *
26326  * Popups are only relevant to a single image because they are based on
26327  * 2D basic image coordinates. Popups related to a certain image should
26328  * be removed when the viewer is moved to another node.
26329  *
26330  * To retrive and use the popup component
26331  *
26332  * @example
26333  * ```
26334  * var viewer = new Mapillary.Viewer(
26335  *     "<element-id>",
26336  *     "<client-id>",
26337  *     "<my key>",
26338  *     { component: { popup: true } });
26339  *
26340  * var popupComponent = viewer.getComponent("popup");
26341  * ```
26342  */
26343 var PopupComponent = /** @class */ (function (_super) {
26344     __extends(PopupComponent, _super);
26345     /** @ignore */
26346     function PopupComponent(name, container, navigator, dom) {
26347         var _this = _super.call(this, name, container, navigator) || this;
26348         _this._dom = !!dom ? dom : new Utils_1.DOM();
26349         _this._popups = [];
26350         _this._added$ = new rxjs_1.Subject();
26351         _this._popups$ = new rxjs_1.Subject();
26352         return _this;
26353     }
26354     /**
26355      * Add popups to the popups set.
26356      *
26357      * @description Adding a new popup never replaces an old one
26358      * because they are stored by reference. Adding an already
26359      * existing popup has no effect.
26360      *
26361      * @param {Array<Popup>} popups - Popups to add.
26362      *
26363      * @example ```popupComponent.add([popup1, popup2]);```
26364      */
26365     PopupComponent.prototype.add = function (popups) {
26366         for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) {
26367             var popup = popups_1[_i];
26368             if (this._popups.indexOf(popup) !== -1) {
26369                 continue;
26370             }
26371             this._popups.push(popup);
26372             if (this._activated) {
26373                 popup.setParentContainer(this._popupContainer);
26374             }
26375         }
26376         this._added$.next(popups);
26377         this._popups$.next(this._popups);
26378     };
26379     /**
26380      * Returns an array of all popups.
26381      *
26382      * @example ```var popups = popupComponent.getAll();```
26383      */
26384     PopupComponent.prototype.getAll = function () {
26385         return this._popups.slice();
26386     };
26387     /**
26388      * Remove popups based on reference from the popup set.
26389      *
26390      * @param {Array<Popup>} popups - Popups to remove.
26391      *
26392      * @example ```popupComponent.remove([popup1, popup2]);```
26393      */
26394     PopupComponent.prototype.remove = function (popups) {
26395         for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) {
26396             var popup = popups_2[_i];
26397             this._remove(popup);
26398         }
26399         this._popups$.next(this._popups);
26400     };
26401     /**
26402      * Remove all popups from the popup set.
26403      *
26404      * @example ```popupComponent.removeAll();```
26405      */
26406     PopupComponent.prototype.removeAll = function () {
26407         for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) {
26408             var popup = _a[_i];
26409             this._remove(popup);
26410         }
26411         this._popups$.next(this._popups);
26412     };
26413     PopupComponent.prototype._activate = function () {
26414         var _this = this;
26415         this._popupContainer = this._dom.createElement("div", "mapillary-js-popup-container", this._container.element);
26416         for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
26417             var popup = _a[_i];
26418             popup.setParentContainer(this._popupContainer);
26419         }
26420         this._updateAllSubscription = rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
26421             .subscribe(function (_a) {
26422             var renderCamera = _a[0], size = _a[1], transform = _a[2];
26423             for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) {
26424                 var popup = _b[_i];
26425                 popup.update(renderCamera, size, transform);
26426             }
26427         });
26428         var changed$ = this._popups$.pipe(operators_1.startWith(this._popups), operators_1.switchMap(function (popups) {
26429             return rxjs_1.from(popups).pipe(operators_1.mergeMap(function (popup) {
26430                 return popup.changed$;
26431             }));
26432         }), operators_1.map(function (popup) {
26433             return [popup];
26434         }));
26435         this._updateAddedChangedSubscription = rxjs_1.merge(this._added$, changed$).pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$))
26436             .subscribe(function (_a) {
26437             var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3];
26438             for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) {
26439                 var popup = popups_3[_i];
26440                 popup.update(renderCamera, size, transform);
26441             }
26442         });
26443     };
26444     PopupComponent.prototype._deactivate = function () {
26445         this._updateAllSubscription.unsubscribe();
26446         this._updateAddedChangedSubscription.unsubscribe();
26447         for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
26448             var popup = _a[_i];
26449             popup.remove();
26450         }
26451         this._container.element.removeChild(this._popupContainer);
26452         delete this._popupContainer;
26453     };
26454     PopupComponent.prototype._getDefaultConfiguration = function () {
26455         return {};
26456     };
26457     PopupComponent.prototype._remove = function (popup) {
26458         var index = this._popups.indexOf(popup);
26459         if (index === -1) {
26460             return;
26461         }
26462         var removed = this._popups.splice(index, 1)[0];
26463         if (this._activated) {
26464             removed.remove();
26465         }
26466     };
26467     PopupComponent.componentName = "popup";
26468     return PopupComponent;
26469 }(Component_1.Component));
26470 exports.PopupComponent = PopupComponent;
26471 Component_1.ComponentService.register(PopupComponent);
26472 exports.default = PopupComponent;
26473
26474 },{"../../Component":274,"../../Utils":284,"rxjs":26,"rxjs/operators":224}],331:[function(require,module,exports){
26475 "use strict";
26476 Object.defineProperty(exports, "__esModule", { value: true });
26477 var rxjs_1 = require("rxjs");
26478 var Geo_1 = require("../../../Geo");
26479 var Utils_1 = require("../../../Utils");
26480 var Viewer_1 = require("../../../Viewer");
26481 /**
26482  * @class Popup
26483  *
26484  * @classdesc Popup instance for rendering custom HTML content
26485  * on top of images. Popups are based on 2D basic image coordinates
26486  * (see the {@link Viewer} class documentation for more information about coordinate
26487  * systems) and a certain popup is therefore only relevant to a single image.
26488  * Popups related to a certain image should be removed when moving
26489  * to another image.
26490  *
26491  * A popup must have both its content and its point or rect set to be
26492  * rendered. Popup options can not be updated after creation but the
26493  * basic point or rect as well as its content can be changed by calling
26494  * the appropriate methods.
26495  *
26496  * To create and add one `Popup` with default configuration
26497  * (tooltip visuals and automatic float) and one with specific options
26498  * use
26499  *
26500  * @example
26501  * ```
26502  * var defaultSpan = document.createElement('span');
26503  * defaultSpan.innerHTML = 'hello default';
26504  *
26505  * var defaultPopup = new Mapillary.PopupComponent.Popup();
26506  * defaultPopup.setDOMContent(defaultSpan);
26507  * defaultPopup.setBasicPoint([0.3, 0.3]);
26508  *
26509  * var cleanSpan = document.createElement('span');
26510  * cleanSpan.innerHTML = 'hello clean';
26511  *
26512  * var cleanPopup = new Mapillary.PopupComponent.Popup({
26513  *     clean: true,
26514  *     float: Mapillary.Alignment.Top,
26515  *     offset: 10,
26516  *     opacity: 0.7,
26517  * });
26518  *
26519  * cleanPopup.setDOMContent(cleanSpan);
26520  * cleanPopup.setBasicPoint([0.6, 0.6]);
26521  *
26522  * popupComponent.add([defaultPopup, cleanPopup]);
26523  * ```
26524  *
26525  * @description Implementation of API methods and API documentation inspired
26526  * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js
26527  */
26528 var Popup = /** @class */ (function () {
26529     function Popup(options, viewportCoords, dom) {
26530         this._options = {};
26531         options = !!options ? options : {};
26532         this._options.capturePointer = options.capturePointer === false ?
26533             options.capturePointer : true;
26534         this._options.clean = options.clean;
26535         this._options.float = options.float;
26536         this._options.offset = options.offset;
26537         this._options.opacity = options.opacity;
26538         this._options.position = options.position;
26539         this._dom = !!dom ? dom : new Utils_1.DOM();
26540         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
26541         this._notifyChanged$ = new rxjs_1.Subject();
26542     }
26543     Object.defineProperty(Popup.prototype, "changed$", {
26544         /**
26545          * @description Internal observable used by the component to
26546          * render the popup when its position or content has changed.
26547          * @ignore
26548          */
26549         get: function () {
26550             return this._notifyChanged$;
26551         },
26552         enumerable: true,
26553         configurable: true
26554     });
26555     /**
26556      * @description Internal method used by the component to
26557      * remove all references to the popup.
26558      * @ignore
26559      */
26560     Popup.prototype.remove = function () {
26561         if (this._content && this._content.parentNode) {
26562             this._content.parentNode.removeChild(this._content);
26563         }
26564         if (this._container) {
26565             this._container.parentNode.removeChild(this._container);
26566             delete this._container;
26567         }
26568         if (this._parentContainer) {
26569             delete this._parentContainer;
26570         }
26571     };
26572     /**
26573      * Sets a 2D basic image coordinates point to the popup's anchor, and
26574      * moves the popup to it.
26575      *
26576      * @description Overwrites any previously set point or rect.
26577      *
26578      * @param {Array<number>} basicPoint - Point in 2D basic image coordinates.
26579      *
26580      * @example
26581      * ```
26582      * var popup = new Mapillary.PopupComponent.Popup();
26583      * popup.setText('hello image');
26584      * popup.setBasicPoint([0.3, 0.3]);
26585      *
26586      * popupComponent.add([popup]);
26587      * ```
26588      */
26589     Popup.prototype.setBasicPoint = function (basicPoint) {
26590         this._point = basicPoint.slice();
26591         this._rect = null;
26592         this._notifyChanged$.next(this);
26593     };
26594     /**
26595      * Sets a 2D basic image coordinates rect to the popup's anchor, and
26596      * moves the popup to it.
26597      *
26598      * @description Overwrites any previously set point or rect.
26599      *
26600      * @param {Array<number>} basicRect - Rect in 2D basic image
26601      * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) .
26602      *
26603      * @example
26604      * ```
26605      * var popup = new Mapillary.PopupComponent.Popup();
26606      * popup.setText('hello image');
26607      * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]);
26608      *
26609      * popupComponent.add([popup]);
26610      * ```
26611      */
26612     Popup.prototype.setBasicRect = function (basicRect) {
26613         this._rect = basicRect.slice();
26614         this._point = null;
26615         this._notifyChanged$.next(this);
26616     };
26617     /**
26618      * Sets the popup's content to the element provided as a DOM node.
26619      *
26620      * @param {Node} htmlNode - A DOM node to be used as content for the popup.
26621      *
26622      * @example
26623      * ```
26624      * var div = document.createElement('div');
26625      * div.innerHTML = 'hello image';
26626      *
26627      * var popup = new Mapillary.PopupComponent.Popup();
26628      * popup.setDOMContent(div);
26629      * popup.setBasicPoint([0.3, 0.3]);
26630      *
26631      * popupComponent.add([popup]);
26632      * ```
26633      */
26634     Popup.prototype.setDOMContent = function (htmlNode) {
26635         if (this._content && this._content.parentNode) {
26636             this._content.parentNode.removeChild(this._content);
26637         }
26638         var className = "mapillaryjs-popup-content" +
26639             (this._options.clean === true ? "-clean" : "") +
26640             (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
26641         this._content = this._dom.createElement("div", className, this._container);
26642         this._content.appendChild(htmlNode);
26643         this._notifyChanged$.next(this);
26644     };
26645     /**
26646      * Sets the popup's content to the HTML provided as a string.
26647      *
26648      * @description This method does not perform HTML filtering or sanitization,
26649      * and must be used only with trusted content. Consider Popup#setText if the
26650      * content is an untrusted text string.
26651      *
26652      * @param {string} html - A string representing HTML content for the popup.
26653      *
26654      * @example
26655      * ```
26656      * var popup = new Mapillary.PopupComponent.Popup();
26657      * popup.setHTML('<div>hello image</div>');
26658      * popup.setBasicPoint([0.3, 0.3]);
26659      *
26660      * popupComponent.add([popup]);
26661      * ```
26662      */
26663     Popup.prototype.setHTML = function (html) {
26664         var frag = this._dom.document.createDocumentFragment();
26665         var temp = this._dom.createElement("body");
26666         var child;
26667         temp.innerHTML = html;
26668         while (true) {
26669             child = temp.firstChild;
26670             if (!child) {
26671                 break;
26672             }
26673             frag.appendChild(child);
26674         }
26675         this.setDOMContent(frag);
26676     };
26677     /**
26678      * Sets the popup's content to a string of text.
26679      *
26680      * @description This function creates a Text node in the DOM, so it cannot insert raw HTML.
26681      * Use this method for security against XSS if the popup content is user-provided.
26682      *
26683      * @param {string} text - Textual content for the popup.
26684      *
26685      * @example
26686      * ```
26687      * var popup = new Mapillary.PopupComponent.Popup();
26688      * popup.setText('hello image');
26689      * popup.setBasicPoint([0.3, 0.3]);
26690      *
26691      * popupComponent.add([popup]);
26692      * ```
26693      */
26694     Popup.prototype.setText = function (text) {
26695         this.setDOMContent(this._dom.document.createTextNode(text));
26696     };
26697     /**
26698      * @description Internal method for attaching the popup to
26699      * its parent container so that it is rendered in the DOM tree.
26700      * @ignore
26701      */
26702     Popup.prototype.setParentContainer = function (parentContainer) {
26703         this._parentContainer = parentContainer;
26704     };
26705     /**
26706      * @description Internal method for updating the rendered
26707      * position of the popup called by the popup component.
26708      * @ignore
26709      */
26710     Popup.prototype.update = function (renderCamera, size, transform) {
26711         var _a;
26712         if (!this._parentContainer || !this._content) {
26713             return;
26714         }
26715         if (!this._point && !this._rect) {
26716             return;
26717         }
26718         if (!this._container) {
26719             this._container = this._dom.createElement("div", "mapillaryjs-popup", this._parentContainer);
26720             var showTip = this._options.clean !== true &&
26721                 this._options.float !== Viewer_1.Alignment.Center;
26722             if (showTip) {
26723                 var tipClassName = "mapillaryjs-popup-tip" +
26724                     (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
26725                 this._tip = this._dom.createElement("div", tipClassName, this._container);
26726                 this._dom.createElement("div", "mapillaryjs-popup-tip-inner", this._tip);
26727             }
26728             this._container.appendChild(this._content);
26729             this._parentContainer.appendChild(this._container);
26730             if (this._options.opacity != null) {
26731                 this._container.style.opacity = this._options.opacity.toString();
26732             }
26733         }
26734         var pointPixel = null;
26735         var position = this._alignmentToPopupAligment(this._options.position);
26736         var float = this._alignmentToPopupAligment(this._options.float);
26737         var classList = this._container.classList;
26738         if (this._point != null) {
26739             pointPixel =
26740                 this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26741         }
26742         else {
26743             var alignments = ["center", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"];
26744             var appliedPosition = null;
26745             for (var _i = 0, alignments_1 = alignments; _i < alignments_1.length; _i++) {
26746                 var alignment = alignments_1[_i];
26747                 if (classList.contains("mapillaryjs-popup-float-" + alignment)) {
26748                     appliedPosition = alignment;
26749                     break;
26750                 }
26751             }
26752             _a = this._rectToPixel(this._rect, position, appliedPosition, renderCamera, size, transform), pointPixel = _a[0], position = _a[1];
26753             if (!float) {
26754                 float = position;
26755             }
26756         }
26757         if (pointPixel == null) {
26758             this._container.style.display = "none";
26759             return;
26760         }
26761         this._container.style.display = "";
26762         if (!float) {
26763             var width = this._container.offsetWidth;
26764             var height = this._container.offsetHeight;
26765             var floats = this._pixelToFloats(pointPixel, size, width, height);
26766             float = floats.length === 0 ? "top" : floats.join("-");
26767         }
26768         var offset = this._normalizeOffset(this._options.offset);
26769         pointPixel = [pointPixel[0] + offset[float][0], pointPixel[1] + offset[float][1]];
26770         pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])];
26771         var floatTranslate = {
26772             "bottom": "translate(-50%,0)",
26773             "bottom-left": "translate(-100%,0)",
26774             "bottom-right": "translate(0,0)",
26775             "center": "translate(-50%,-50%)",
26776             "left": "translate(-100%,-50%)",
26777             "right": "translate(0,-50%)",
26778             "top": "translate(-50%,-100%)",
26779             "top-left": "translate(-100%,-100%)",
26780             "top-right": "translate(0,-100%)",
26781         };
26782         for (var key in floatTranslate) {
26783             if (!floatTranslate.hasOwnProperty(key)) {
26784                 continue;
26785             }
26786             classList.remove("mapillaryjs-popup-float-" + key);
26787         }
26788         classList.add("mapillaryjs-popup-float-" + float);
26789         this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)";
26790     };
26791     Popup.prototype._rectToPixel = function (rect, position, appliedPosition, renderCamera, size, transform) {
26792         if (!position) {
26793             var width = this._container.offsetWidth;
26794             var height = this._container.offsetHeight;
26795             var floatOffsets = {
26796                 "bottom": [0, height / 2],
26797                 "bottom-left": [-width / 2, height / 2],
26798                 "bottom-right": [width / 2, height / 2],
26799                 "left": [-width / 2, 0],
26800                 "right": [width / 2, 0],
26801                 "top": [0, -height / 2],
26802                 "top-left": [-width / 2, -height / 2],
26803                 "top-right": [width / 2, -height / 2],
26804             };
26805             var automaticPositions = ["top", "bottom", "left", "right"];
26806             var largestVisibleArea = [0, null, null];
26807             for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) {
26808                 var automaticPosition = automaticPositions_1[_i];
26809                 var autoPointBasic = this._pointFromRectPosition(rect, automaticPosition);
26810                 var autoPointPixel = this._viewportCoords.basicToCanvasSafe(autoPointBasic[0], autoPointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26811                 if (autoPointPixel == null) {
26812                     continue;
26813                 }
26814                 var floatOffset = floatOffsets[automaticPosition];
26815                 var offsetedPosition = [autoPointPixel[0] + floatOffset[0], autoPointPixel[1] + floatOffset[1]];
26816                 var staticCoeff = appliedPosition != null && appliedPosition === automaticPosition ? 1 : 0.7;
26817                 var floats = this._pixelToFloats(offsetedPosition, size, width / staticCoeff, height / (2 * staticCoeff));
26818                 if (floats.length === 0 &&
26819                     autoPointPixel[0] > 0 &&
26820                     autoPointPixel[0] < size.width &&
26821                     autoPointPixel[1] > 0 &&
26822                     autoPointPixel[1] < size.height) {
26823                     return [autoPointPixel, automaticPosition];
26824                 }
26825                 var minX = Math.max(offsetedPosition[0] - width / 2, 0);
26826                 var maxX = Math.min(offsetedPosition[0] + width / 2, size.width);
26827                 var minY = Math.max(offsetedPosition[1] - height / 2, 0);
26828                 var maxY = Math.min(offsetedPosition[1] + height / 2, size.height);
26829                 var visibleX = Math.max(0, maxX - minX);
26830                 var visibleY = Math.max(0, maxY - minY);
26831                 var visibleArea = staticCoeff * visibleX * visibleY;
26832                 if (visibleArea > largestVisibleArea[0]) {
26833                     largestVisibleArea[0] = visibleArea;
26834                     largestVisibleArea[1] = autoPointPixel;
26835                     largestVisibleArea[2] = automaticPosition;
26836                 }
26837             }
26838             if (largestVisibleArea[0] > 0) {
26839                 return [largestVisibleArea[1], largestVisibleArea[2]];
26840             }
26841         }
26842         var pointBasic = this._pointFromRectPosition(rect, position);
26843         var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26844         return [pointPixel, position != null ? position : "top"];
26845     };
26846     Popup.prototype._alignmentToPopupAligment = function (float) {
26847         switch (float) {
26848             case Viewer_1.Alignment.Bottom:
26849                 return "bottom";
26850             case Viewer_1.Alignment.BottomLeft:
26851                 return "bottom-left";
26852             case Viewer_1.Alignment.BottomRight:
26853                 return "bottom-right";
26854             case Viewer_1.Alignment.Center:
26855                 return "center";
26856             case Viewer_1.Alignment.Left:
26857                 return "left";
26858             case Viewer_1.Alignment.Right:
26859                 return "right";
26860             case Viewer_1.Alignment.Top:
26861                 return "top";
26862             case Viewer_1.Alignment.TopLeft:
26863                 return "top-left";
26864             case Viewer_1.Alignment.TopRight:
26865                 return "top-right";
26866             default:
26867                 return null;
26868         }
26869     };
26870     Popup.prototype._normalizeOffset = function (offset) {
26871         if (offset == null) {
26872             return this._normalizeOffset(0);
26873         }
26874         if (typeof offset === "number") {
26875             // input specifies a radius
26876             var sideOffset = offset;
26877             var sign = sideOffset >= 0 ? 1 : -1;
26878             var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(sideOffset, 2)));
26879             return {
26880                 "bottom": [0, sideOffset],
26881                 "bottom-left": [-cornerOffset, cornerOffset],
26882                 "bottom-right": [cornerOffset, cornerOffset],
26883                 "center": [0, 0],
26884                 "left": [-sideOffset, 0],
26885                 "right": [sideOffset, 0],
26886                 "top": [0, -sideOffset],
26887                 "top-left": [-cornerOffset, -cornerOffset],
26888                 "top-right": [cornerOffset, -cornerOffset],
26889             };
26890         }
26891         else {
26892             // input specifes a value for each position
26893             return {
26894                 "bottom": offset.bottom || [0, 0],
26895                 "bottom-left": offset.bottomLeft || [0, 0],
26896                 "bottom-right": offset.bottomRight || [0, 0],
26897                 "center": offset.center || [0, 0],
26898                 "left": offset.left || [0, 0],
26899                 "right": offset.right || [0, 0],
26900                 "top": offset.top || [0, 0],
26901                 "top-left": offset.topLeft || [0, 0],
26902                 "top-right": offset.topRight || [0, 0],
26903             };
26904         }
26905     };
26906     Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) {
26907         var floats = [];
26908         if (pointPixel[1] < height) {
26909             floats.push("bottom");
26910         }
26911         else if (pointPixel[1] > size.height - height) {
26912             floats.push("top");
26913         }
26914         if (pointPixel[0] < width / 2) {
26915             floats.push("right");
26916         }
26917         else if (pointPixel[0] > size.width - width / 2) {
26918             floats.push("left");
26919         }
26920         return floats;
26921     };
26922     Popup.prototype._pointFromRectPosition = function (rect, position) {
26923         var x0 = rect[0];
26924         var x1 = rect[0] < rect[2] ? rect[2] : rect[2] + 1;
26925         var y0 = rect[1];
26926         var y1 = rect[3];
26927         switch (position) {
26928             case "bottom":
26929                 return [(x0 + x1) / 2, y1];
26930             case "bottom-left":
26931                 return [x0, y1];
26932             case "bottom-right":
26933                 return [x1, y1];
26934             case "center":
26935                 return [(x0 + x1) / 2, (y0 + y1) / 2];
26936             case "left":
26937                 return [x0, (y0 + y1) / 2];
26938             case "right":
26939                 return [x1, (y0 + y1) / 2];
26940             case "top":
26941                 return [(x0 + x1) / 2, y0];
26942             case "top-left":
26943                 return [x0, y0];
26944             case "top-right":
26945                 return [x1, y0];
26946             default:
26947                 return [(x0 + x1) / 2, y1];
26948         }
26949     };
26950     return Popup;
26951 }());
26952 exports.Popup = Popup;
26953 exports.default = Popup;
26954
26955
26956 },{"../../../Geo":277,"../../../Utils":284,"../../../Viewer":285,"rxjs":26}],332:[function(require,module,exports){
26957 "use strict";
26958 var __extends = (this && this.__extends) || (function () {
26959     var extendStatics = function (d, b) {
26960         extendStatics = Object.setPrototypeOf ||
26961             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26962             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26963         return extendStatics(d, b);
26964     }
26965     return function (d, b) {
26966         extendStatics(d, b);
26967         function __() { this.constructor = d; }
26968         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26969     };
26970 })();
26971 Object.defineProperty(exports, "__esModule", { value: true });
26972 var rxjs_1 = require("rxjs");
26973 var operators_1 = require("rxjs/operators");
26974 var Component_1 = require("../../Component");
26975 var Edge_1 = require("../../Edge");
26976 var Graph_1 = require("../../Graph");
26977 /**
26978  * @class SequenceComponent
26979  * @classdesc Component showing navigation arrows for sequence directions
26980  * as well as playing button. Exposes an API to start and stop play.
26981  */
26982 var SequenceComponent = /** @class */ (function (_super) {
26983     __extends(SequenceComponent, _super);
26984     function SequenceComponent(name, container, navigator, renderer, scheduler) {
26985         var _this = _super.call(this, name, container, navigator) || this;
26986         _this._sequenceDOMRenderer = !!renderer ? renderer : new Component_1.SequenceDOMRenderer(container);
26987         _this._scheduler = scheduler;
26988         _this._containerWidth$ = new rxjs_1.Subject();
26989         _this._hoveredKeySubject$ = new rxjs_1.Subject();
26990         _this._hoveredKey$ = _this._hoveredKeySubject$.pipe(operators_1.share());
26991         _this._navigator.playService.playing$.pipe(operators_1.skip(1), operators_1.withLatestFrom(_this._configuration$))
26992             .subscribe(function (_a) {
26993             var playing = _a[0], configuration = _a[1];
26994             _this.fire(SequenceComponent.playingchanged, playing);
26995             if (playing === configuration.playing) {
26996                 return;
26997             }
26998             if (playing) {
26999                 _this.play();
27000             }
27001             else {
27002                 _this.stop();
27003             }
27004         });
27005         _this._navigator.playService.direction$.pipe(operators_1.skip(1), operators_1.withLatestFrom(_this._configuration$))
27006             .subscribe(function (_a) {
27007             var direction = _a[0], configuration = _a[1];
27008             if (direction !== configuration.direction) {
27009                 _this.setDirection(direction);
27010             }
27011         });
27012         return _this;
27013     }
27014     Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
27015         /**
27016          * Get hovered key observable.
27017          *
27018          * @description An observable emitting the key of the node for the direction
27019          * arrow that is being hovered. When the mouse leaves a direction arrow null
27020          * is emitted.
27021          *
27022          * @returns {Observable<string>}
27023          */
27024         get: function () {
27025             return this._hoveredKey$;
27026         },
27027         enumerable: true,
27028         configurable: true
27029     });
27030     /**
27031      * Start playing.
27032      *
27033      * @fires PlayerComponent#playingchanged
27034      */
27035     SequenceComponent.prototype.play = function () {
27036         this.configure({ playing: true });
27037     };
27038     /**
27039      * Stop playing.
27040      *
27041      * @fires PlayerComponent#playingchanged
27042      */
27043     SequenceComponent.prototype.stop = function () {
27044         this.configure({ playing: false });
27045     };
27046     /**
27047      * Set the direction to follow when playing.
27048      *
27049      * @param {EdgeDirection} direction - The direction that will be followed when playing.
27050      */
27051     SequenceComponent.prototype.setDirection = function (direction) {
27052         this.configure({ direction: direction });
27053     };
27054     /**
27055      * Set highlight key.
27056      *
27057      * @description The arrow pointing towards the node corresponding to the
27058      * highlight key will be highlighted.
27059      *
27060      * @param {string} highlightKey Key of node to be highlighted if existing.
27061      */
27062     SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
27063         this.configure({ highlightKey: highlightKey });
27064     };
27065     /**
27066      * Set max width of container element.
27067      *
27068      * @description Set max width of the container element holding
27069      * the sequence navigation elements. If the min width is larger than the
27070      * max width the min width value will be used.
27071      *
27072      * The container element is automatically resized when the resize
27073      * method on the Viewer class is called.
27074      *
27075      * @param {number} minWidth
27076      */
27077     SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
27078         this.configure({ maxWidth: maxWidth });
27079     };
27080     /**
27081      * Set min width of container element.
27082      *
27083      * @description Set min width of the container element holding
27084      * the sequence navigation elements. If the min width is larger than the
27085      * max width the min width value will be used.
27086      *
27087      * The container element is automatically resized when the resize
27088      * method on the Viewer class is called.
27089      *
27090      * @param {number} minWidth
27091      */
27092     SequenceComponent.prototype.setMinWidth = function (minWidth) {
27093         this.configure({ minWidth: minWidth });
27094     };
27095     /**
27096      * Set the value indicating whether the sequence UI elements should be visible.
27097      *
27098      * @param {boolean} visible
27099      */
27100     SequenceComponent.prototype.setVisible = function (visible) {
27101         this.configure({ visible: visible });
27102     };
27103     SequenceComponent.prototype._activate = function () {
27104         var _this = this;
27105         this._sequenceDOMRenderer.activate();
27106         var edgeStatus$ = this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
27107             return node.sequenceEdges$;
27108         }), operators_1.publishReplay(1), operators_1.refCount());
27109         var sequence$ = this._navigator.stateService.currentNode$.pipe(operators_1.distinctUntilChanged(undefined, function (node) {
27110             return node.sequenceKey;
27111         }), operators_1.switchMap(function (node) {
27112             return rxjs_1.concat(rxjs_1.of(null), _this._navigator.graphService.cacheSequence$(node.sequenceKey).pipe(operators_1.retry(3), operators_1.catchError(function (e) {
27113                 console.error("Failed to cache sequence", e);
27114                 return rxjs_1.of(null);
27115             })));
27116         }), operators_1.startWith(null), operators_1.publishReplay(1), operators_1.refCount());
27117         this._sequenceSubscription = sequence$.subscribe();
27118         var rendererKey$ = this._sequenceDOMRenderer.index$.pipe(operators_1.withLatestFrom(sequence$), operators_1.map(function (_a) {
27119             var index = _a[0], sequence = _a[1];
27120             return sequence != null ? sequence.keys[index] : null;
27121         }), operators_1.filter(function (key) {
27122             return !!key;
27123         }), operators_1.distinctUntilChanged(), operators_1.publish(), operators_1.refCount());
27124         this._moveSubscription = rxjs_1.merge(rendererKey$.pipe(operators_1.debounceTime(100, this._scheduler)), rendererKey$.pipe(operators_1.auditTime(400, this._scheduler))).pipe(operators_1.distinctUntilChanged(), operators_1.switchMap(function (key) {
27125             return _this._navigator.moveToKey$(key).pipe(operators_1.catchError(function (e) {
27126                 return rxjs_1.empty();
27127             }));
27128         }))
27129             .subscribe();
27130         this._setSequenceGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.filter(function (changing) {
27131             return changing;
27132         }))
27133             .subscribe(function () {
27134             _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Sequence);
27135         });
27136         this._setSpatialGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.filter(function (changing) {
27137             return !changing;
27138         }))
27139             .subscribe(function () {
27140             _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Spatial);
27141         });
27142         this._navigator.graphService.graphMode$.pipe(operators_1.switchMap(function (mode) {
27143             return mode === Graph_1.GraphMode.Spatial ?
27144                 _this._navigator.stateService.currentNode$.pipe(operators_1.take(2)) :
27145                 rxjs_1.empty();
27146         }), operators_1.filter(function (node) {
27147             return !node.spatialEdges.cached;
27148         }), operators_1.switchMap(function (node) {
27149             return _this._navigator.graphService.cacheNode$(node.key).pipe(operators_1.catchError(function (e) {
27150                 return rxjs_1.empty();
27151             }));
27152         }))
27153             .subscribe();
27154         this._stopSubscription = this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.filter(function (changing) {
27155             return changing;
27156         }))
27157             .subscribe(function () {
27158             _this._navigator.playService.stop();
27159         });
27160         this._cacheSequenceNodesSubscription = rxjs_1.combineLatest(this._navigator.graphService.graphMode$, this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.startWith(false), operators_1.distinctUntilChanged())).pipe(operators_1.withLatestFrom(this._navigator.stateService.currentNode$), operators_1.switchMap(function (_a) {
27161             var _b = _a[0], mode = _b[0], changing = _b[1], node = _a[1];
27162             return changing && mode === Graph_1.GraphMode.Sequence ?
27163                 _this._navigator.graphService.cacheSequenceNodes$(node.sequenceKey, node.key).pipe(operators_1.retry(3), operators_1.catchError(function (error) {
27164                     console.error("Failed to cache sequence nodes.", error);
27165                     return rxjs_1.empty();
27166                 })) :
27167                 rxjs_1.empty();
27168         }))
27169             .subscribe();
27170         var position$ = sequence$.pipe(operators_1.switchMap(function (sequence) {
27171             if (!sequence) {
27172                 return rxjs_1.of({ index: null, max: null });
27173             }
27174             var firstCurrentKey = true;
27175             return _this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.startWith(false), operators_1.distinctUntilChanged(), operators_1.switchMap(function (changingPosition) {
27176                 var skipCount = !changingPosition && firstCurrentKey ? 0 : 1;
27177                 firstCurrentKey = false;
27178                 return changingPosition ?
27179                     rendererKey$ :
27180                     _this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) {
27181                         return node.key;
27182                     }), operators_1.distinctUntilChanged(), operators_1.skip(skipCount));
27183             }), operators_1.map(function (key) {
27184                 var index = sequence.keys.indexOf(key);
27185                 if (index === -1) {
27186                     return { index: null, max: null };
27187                 }
27188                 return { index: index, max: sequence.keys.length - 1 };
27189             }));
27190         }));
27191         this._renderSubscription = rxjs_1.combineLatest(edgeStatus$, this._configuration$, this._containerWidth$, this._sequenceDOMRenderer.changed$.pipe(operators_1.startWith(this._sequenceDOMRenderer)), this._navigator.playService.speed$, position$).pipe(operators_1.map(function (_a) {
27192             var edgeStatus = _a[0], configuration = _a[1], containerWidth = _a[2], renderer = _a[3], speed = _a[4], position = _a[5];
27193             var vNode = _this._sequenceDOMRenderer
27194                 .render(edgeStatus, configuration, containerWidth, speed, position.index, position.max, _this, _this._navigator);
27195             return { name: _this._name, vnode: vNode };
27196         }))
27197             .subscribe(this._container.domRenderer.render$);
27198         this._setSpeedSubscription = this._sequenceDOMRenderer.speed$
27199             .subscribe(function (speed) {
27200             _this._navigator.playService.setSpeed(speed);
27201         });
27202         this._setDirectionSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
27203             return configuration.direction;
27204         }), operators_1.distinctUntilChanged())
27205             .subscribe(function (direction) {
27206             _this._navigator.playService.setDirection(direction);
27207         });
27208         this._containerWidthSubscription = rxjs_1.combineLatest(this._container.renderService.size$, this._configuration$.pipe(operators_1.distinctUntilChanged(function (value1, value2) {
27209             return value1[0] === value2[0] && value1[1] === value2[1];
27210         }, function (configuration) {
27211             return [configuration.minWidth, configuration.maxWidth];
27212         }))).pipe(operators_1.map(function (_a) {
27213             var size = _a[0], configuration = _a[1];
27214             return _this._sequenceDOMRenderer.getContainerWidth(size, configuration);
27215         }))
27216             .subscribe(this._containerWidth$);
27217         this._playingSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
27218             return configuration.playing;
27219         }), operators_1.distinctUntilChanged())
27220             .subscribe(function (playing) {
27221             if (playing) {
27222                 _this._navigator.playService.play();
27223             }
27224             else {
27225                 _this._navigator.playService.stop();
27226             }
27227         });
27228         this._hoveredKeySubscription = this._sequenceDOMRenderer.mouseEnterDirection$.pipe(operators_1.switchMap(function (direction) {
27229             var edgeTo$ = edgeStatus$.pipe(operators_1.map(function (edgeStatus) {
27230                 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
27231                     var edge = _a[_i];
27232                     if (edge.data.direction === direction) {
27233                         return edge.to;
27234                     }
27235                 }
27236                 return null;
27237             }), operators_1.takeUntil(_this._sequenceDOMRenderer.mouseLeaveDirection$));
27238             return rxjs_1.concat(edgeTo$, rxjs_1.of(null));
27239         }), operators_1.distinctUntilChanged())
27240             .subscribe(this._hoveredKeySubject$);
27241         this._emitHoveredKeySubscription = this._hoveredKey$
27242             .subscribe(function (key) {
27243             _this.fire(SequenceComponent.hoveredkeychanged, key);
27244         });
27245     };
27246     SequenceComponent.prototype._deactivate = function () {
27247         this._emitHoveredKeySubscription.unsubscribe();
27248         this._renderSubscription.unsubscribe();
27249         this._playingSubscription.unsubscribe();
27250         this._containerWidthSubscription.unsubscribe();
27251         this._hoveredKeySubscription.unsubscribe();
27252         this._setSpeedSubscription.unsubscribe();
27253         this._setDirectionSubscription.unsubscribe();
27254         this._setSequenceGraphModeSubscription.unsubscribe();
27255         this._setSpatialGraphModeSubscription.unsubscribe();
27256         this._sequenceSubscription.unsubscribe();
27257         this._moveSubscription.unsubscribe();
27258         this._cacheSequenceNodesSubscription.unsubscribe();
27259         this._stopSubscription.unsubscribe();
27260         this._sequenceDOMRenderer.deactivate();
27261     };
27262     SequenceComponent.prototype._getDefaultConfiguration = function () {
27263         return {
27264             direction: Edge_1.EdgeDirection.Next,
27265             maxWidth: 108,
27266             minWidth: 70,
27267             playing: false,
27268             visible: true,
27269         };
27270     };
27271     /** @inheritdoc */
27272     SequenceComponent.componentName = "sequence";
27273     /**
27274      * Event fired when playing starts or stops.
27275      *
27276      * @event SequenceComponent#playingchanged
27277      * @type {boolean} Indicates whether the player is playing.
27278      */
27279     SequenceComponent.playingchanged = "playingchanged";
27280     /**
27281      * Event fired when the hovered key changes.
27282      *
27283      * @description Emits the key of the node for the direction
27284      * arrow that is being hovered. When the mouse leaves a
27285      * direction arrow null is emitted.
27286      *
27287      * @event SequenceComponent#hoveredkeychanged
27288      * @type {string} The hovered key, null if no key is hovered.
27289      */
27290     SequenceComponent.hoveredkeychanged = "hoveredkeychanged";
27291     return SequenceComponent;
27292 }(Component_1.Component));
27293 exports.SequenceComponent = SequenceComponent;
27294 Component_1.ComponentService.register(SequenceComponent);
27295 exports.default = SequenceComponent;
27296
27297 },{"../../Component":274,"../../Edge":275,"../../Graph":278,"rxjs":26,"rxjs/operators":224}],333:[function(require,module,exports){
27298 "use strict";
27299 Object.defineProperty(exports, "__esModule", { value: true });
27300 var rxjs_1 = require("rxjs");
27301 var operators_1 = require("rxjs/operators");
27302 var vd = require("virtual-dom");
27303 var Component_1 = require("../../Component");
27304 var Edge_1 = require("../../Edge");
27305 var Error_1 = require("../../Error");
27306 var SequenceDOMRenderer = /** @class */ (function () {
27307     function SequenceDOMRenderer(container) {
27308         this._container = container;
27309         this._minThresholdWidth = 320;
27310         this._maxThresholdWidth = 1480;
27311         this._minThresholdHeight = 240;
27312         this._maxThresholdHeight = 820;
27313         this._stepperDefaultWidth = 108;
27314         this._controlsDefaultWidth = 88;
27315         this._defaultHeight = 30;
27316         this._expandControls = false;
27317         this._mode = Component_1.SequenceMode.Default;
27318         this._speed = 0.5;
27319         this._changingSpeed = false;
27320         this._index = null;
27321         this._changingPosition = false;
27322         this._mouseEnterDirection$ = new rxjs_1.Subject();
27323         this._mouseLeaveDirection$ = new rxjs_1.Subject();
27324         this._notifyChanged$ = new rxjs_1.Subject();
27325         this._notifyChangingPositionChanged$ = new rxjs_1.Subject();
27326         this._notifySpeedChanged$ = new rxjs_1.Subject();
27327         this._notifyIndexChanged$ = new rxjs_1.Subject();
27328     }
27329     Object.defineProperty(SequenceDOMRenderer.prototype, "changed$", {
27330         get: function () {
27331             return this._notifyChanged$;
27332         },
27333         enumerable: true,
27334         configurable: true
27335     });
27336     Object.defineProperty(SequenceDOMRenderer.prototype, "changingPositionChanged$", {
27337         get: function () {
27338             return this._notifyChangingPositionChanged$;
27339         },
27340         enumerable: true,
27341         configurable: true
27342     });
27343     Object.defineProperty(SequenceDOMRenderer.prototype, "speed$", {
27344         get: function () {
27345             return this._notifySpeedChanged$;
27346         },
27347         enumerable: true,
27348         configurable: true
27349     });
27350     Object.defineProperty(SequenceDOMRenderer.prototype, "index$", {
27351         get: function () {
27352             return this._notifyIndexChanged$;
27353         },
27354         enumerable: true,
27355         configurable: true
27356     });
27357     Object.defineProperty(SequenceDOMRenderer.prototype, "mouseEnterDirection$", {
27358         get: function () {
27359             return this._mouseEnterDirection$;
27360         },
27361         enumerable: true,
27362         configurable: true
27363     });
27364     Object.defineProperty(SequenceDOMRenderer.prototype, "mouseLeaveDirection$", {
27365         get: function () {
27366             return this._mouseLeaveDirection$;
27367         },
27368         enumerable: true,
27369         configurable: true
27370     });
27371     SequenceDOMRenderer.prototype.activate = function () {
27372         var _this = this;
27373         if (!!this._changingSubscription) {
27374             return;
27375         }
27376         this._changingSubscription = rxjs_1.merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$.pipe(operators_1.filter(function (touchEvent) {
27377             return touchEvent.touches.length === 0;
27378         })))
27379             .subscribe(function (event) {
27380             if (_this._changingSpeed) {
27381                 _this._changingSpeed = false;
27382             }
27383             if (_this._changingPosition) {
27384                 _this._setChangingPosition(false);
27385             }
27386         });
27387     };
27388     SequenceDOMRenderer.prototype.deactivate = function () {
27389         if (!this._changingSubscription) {
27390             return;
27391         }
27392         this._changingSpeed = false;
27393         this._changingPosition = false;
27394         this._expandControls = false;
27395         this._mode = Component_1.SequenceMode.Default;
27396         this._changingSubscription.unsubscribe();
27397         this._changingSubscription = null;
27398     };
27399     SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, speed, index, max, component, navigator) {
27400         if (configuration.visible === false) {
27401             return vd.h("div.SequenceContainer", {}, []);
27402         }
27403         var stepper = this._createStepper(edgeStatus, configuration, containerWidth, component, navigator);
27404         var controls = this._createSequenceControls(containerWidth);
27405         var playback = this._createPlaybackControls(containerWidth, speed, component, configuration);
27406         var timeline = this._createTimelineControls(containerWidth, index, max);
27407         return vd.h("div.SequenceContainer", [stepper, controls, playback, timeline]);
27408     };
27409     SequenceDOMRenderer.prototype.getContainerWidth = function (size, configuration) {
27410         var minWidth = configuration.minWidth;
27411         var maxWidth = configuration.maxWidth;
27412         if (maxWidth < minWidth) {
27413             maxWidth = minWidth;
27414         }
27415         var relativeWidth = (size.width - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
27416         var relativeHeight = (size.height - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
27417         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
27418         return minWidth + coeff * (maxWidth - minWidth);
27419     };
27420     SequenceDOMRenderer.prototype._createPositionInput = function (index, max) {
27421         var _this = this;
27422         this._index = index;
27423         var onPosition = function (e) {
27424             _this._index = Number(e.target.value);
27425             _this._notifyIndexChanged$.next(_this._index);
27426         };
27427         var boundingRect = this._container.domContainer.getBoundingClientRect();
27428         var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 65;
27429         var onStart = function (e) {
27430             e.stopPropagation();
27431             _this._setChangingPosition(true);
27432         };
27433         var onMove = function (e) {
27434             if (_this._changingPosition === true) {
27435                 e.stopPropagation();
27436             }
27437         };
27438         var onKeyDown = function (e) {
27439             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
27440                 e.key === "ArrowRight" || e.key === "ArrowUp") {
27441                 e.preventDefault();
27442             }
27443         };
27444         var positionInputProperties = {
27445             max: max != null ? max : 1,
27446             min: 0,
27447             onchange: onPosition,
27448             oninput: onPosition,
27449             onkeydown: onKeyDown,
27450             onmousedown: onStart,
27451             onmousemove: onMove,
27452             ontouchmove: onMove,
27453             ontouchstart: onStart,
27454             style: {
27455                 width: width + "px",
27456             },
27457             type: "range",
27458             value: index != null ? index : 0,
27459         };
27460         var disabled = index == null || max == null || max <= 1;
27461         if (disabled) {
27462             positionInputProperties.disabled = "true";
27463         }
27464         var positionInput = vd.h("input.SequencePosition", positionInputProperties, []);
27465         var positionContainerClass = disabled ? ".SequencePositionContainerDisabled" : ".SequencePositionContainer";
27466         return vd.h("div" + positionContainerClass, [positionInput]);
27467     };
27468     SequenceDOMRenderer.prototype._createSpeedInput = function (speed) {
27469         var _this = this;
27470         this._speed = speed;
27471         var onSpeed = function (e) {
27472             _this._speed = Number(e.target.value) / 1000;
27473             _this._notifySpeedChanged$.next(_this._speed);
27474         };
27475         var boundingRect = this._container.domContainer.getBoundingClientRect();
27476         var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 160;
27477         var onStart = function (e) {
27478             _this._changingSpeed = true;
27479             e.stopPropagation();
27480         };
27481         var onMove = function (e) {
27482             if (_this._changingSpeed === true) {
27483                 e.stopPropagation();
27484             }
27485         };
27486         var onKeyDown = function (e) {
27487             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
27488                 e.key === "ArrowRight" || e.key === "ArrowUp") {
27489                 e.preventDefault();
27490             }
27491         };
27492         var speedInput = vd.h("input.SequenceSpeed", {
27493             max: 1000,
27494             min: 0,
27495             onchange: onSpeed,
27496             oninput: onSpeed,
27497             onkeydown: onKeyDown,
27498             onmousedown: onStart,
27499             onmousemove: onMove,
27500             ontouchmove: onMove,
27501             ontouchstart: onStart,
27502             style: {
27503                 width: width + "px",
27504             },
27505             type: "range",
27506             value: 1000 * speed,
27507         }, []);
27508         return vd.h("div.SequenceSpeedContainer", [speedInput]);
27509     };
27510     SequenceDOMRenderer.prototype._createPlaybackControls = function (containerWidth, speed, component, configuration) {
27511         var _this = this;
27512         if (this._mode !== Component_1.SequenceMode.Playback) {
27513             return vd.h("div.SequencePlayback", []);
27514         }
27515         var switchIcon = vd.h("div.SequenceSwitchIcon.SequenceIconVisible", []);
27516         var direction = configuration.direction === Edge_1.EdgeDirection.Next ?
27517             Edge_1.EdgeDirection.Prev : Edge_1.EdgeDirection.Next;
27518         var playing = configuration.playing;
27519         var switchButtonProperties = {
27520             onclick: function () {
27521                 if (!playing) {
27522                     component.setDirection(direction);
27523                 }
27524             },
27525         };
27526         var switchButtonClassName = configuration.playing ? ".SequenceSwitchButtonDisabled" : ".SequenceSwitchButton";
27527         var switchButton = vd.h("div" + switchButtonClassName, switchButtonProperties, [switchIcon]);
27528         var slowIcon = vd.h("div.SequenceSlowIcon.SequenceIconVisible", []);
27529         var slowContainer = vd.h("div.SequenceSlowContainer", [slowIcon]);
27530         var fastIcon = vd.h("div.SequenceFastIcon.SequenceIconVisible", []);
27531         var fastContainer = vd.h("div.SequenceFastContainer", [fastIcon]);
27532         var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
27533         var closeButtonProperties = {
27534             onclick: function () {
27535                 _this._mode = Component_1.SequenceMode.Default;
27536                 _this._notifyChanged$.next(_this);
27537             },
27538         };
27539         var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
27540         var speedInput = this._createSpeedInput(speed);
27541         var playbackChildren = [switchButton, slowContainer, speedInput, fastContainer, closeButton];
27542         var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
27543         var playbackProperties = { style: { top: top + "px" } };
27544         return vd.h("div.SequencePlayback", playbackProperties, playbackChildren);
27545     };
27546     SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
27547         var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
27548             configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
27549         var onclick = configuration.playing ?
27550             function (e) { component.stop(); } :
27551             canPlay ? function (e) { component.play(); } : null;
27552         var buttonProperties = { onclick: onclick };
27553         var iconClass = configuration.playing ?
27554             "Stop" :
27555             canPlay ? "Play" : "PlayDisabled";
27556         var iconProperties = { className: iconClass };
27557         if (configuration.direction === Edge_1.EdgeDirection.Prev) {
27558             iconProperties.style = {
27559                 transform: "rotate(180deg) translate(50%, 50%)",
27560             };
27561         }
27562         var icon = vd.h("div.SequenceComponentIcon", iconProperties, []);
27563         var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
27564         return vd.h("div." + buttonClass, buttonProperties, [icon]);
27565     };
27566     SequenceDOMRenderer.prototype._createSequenceControls = function (containerWidth) {
27567         var _this = this;
27568         var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
27569         var expanderProperties = {
27570             onclick: function () {
27571                 _this._expandControls = !_this._expandControls;
27572                 _this._mode = Component_1.SequenceMode.Default;
27573                 _this._notifyChanged$.next(_this);
27574             },
27575             style: {
27576                 "border-bottom-right-radius": borderRadius + "px",
27577                 "border-top-right-radius": borderRadius + "px",
27578             },
27579         };
27580         var expanderBar = vd.h("div.SequenceExpanderBar", []);
27581         var expander = vd.h("div.SequenceExpanderButton", expanderProperties, [expanderBar]);
27582         var fastIconClassName = this._mode === Component_1.SequenceMode.Playback ?
27583             ".SequenceFastIconGrey.SequenceIconVisible" : ".SequenceFastIcon";
27584         var fastIcon = vd.h("div" + fastIconClassName, []);
27585         var playbackProperties = {
27586             onclick: function () {
27587                 _this._mode = _this._mode === Component_1.SequenceMode.Playback ?
27588                     Component_1.SequenceMode.Default :
27589                     Component_1.SequenceMode.Playback;
27590                 _this._notifyChanged$.next(_this);
27591             },
27592         };
27593         var playback = vd.h("div.SequencePlaybackButton", playbackProperties, [fastIcon]);
27594         var timelineIconClassName = this._mode === Component_1.SequenceMode.Timeline ?
27595             ".SequenceTimelineIconGrey.SequenceIconVisible" : ".SequenceTimelineIcon";
27596         var timelineIcon = vd.h("div" + timelineIconClassName, []);
27597         var timelineProperties = {
27598             onclick: function () {
27599                 _this._mode = _this._mode === Component_1.SequenceMode.Timeline ?
27600                     Component_1.SequenceMode.Default :
27601                     Component_1.SequenceMode.Timeline;
27602                 _this._notifyChanged$.next(_this);
27603             },
27604         };
27605         var timeline = vd.h("div.SequenceTimelineButton", timelineProperties, [timelineIcon]);
27606         var properties = {
27607             style: {
27608                 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
27609                 transform: "translate(" + (containerWidth / 2 + 2) + "px, 0)",
27610                 width: (this._controlsDefaultWidth / this._stepperDefaultWidth * containerWidth) + "px",
27611             },
27612         };
27613         var className = ".SequenceControls" +
27614             (this._expandControls ? ".SequenceControlsExpanded" : "");
27615         return vd.h("div" + className, properties, [playback, timeline, expander]);
27616     };
27617     SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, containerWidth, configuration, navigator) {
27618         var _this = this;
27619         var nextProperties = {
27620             onclick: nextKey != null ?
27621                 function (e) {
27622                     navigator.moveDir$(Edge_1.EdgeDirection.Next)
27623                         .subscribe(undefined, function (error) {
27624                         if (!(error instanceof Error_1.AbortMapillaryError)) {
27625                             console.error(error);
27626                         }
27627                     });
27628                 } :
27629                 null,
27630             onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
27631             onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
27632         };
27633         var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
27634         var prevProperties = {
27635             onclick: prevKey != null ?
27636                 function (e) {
27637                     navigator.moveDir$(Edge_1.EdgeDirection.Prev)
27638                         .subscribe(undefined, function (error) {
27639                         if (!(error instanceof Error_1.AbortMapillaryError)) {
27640                             console.error(error);
27641                         }
27642                     });
27643                 } :
27644                 null,
27645             onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
27646             onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
27647             style: {
27648                 "border-bottom-left-radius": borderRadius + "px",
27649                 "border-top-left-radius": borderRadius + "px",
27650             },
27651         };
27652         var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
27653         var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
27654         var nextIcon = vd.h("div.SequenceComponentIcon", []);
27655         var prevIcon = vd.h("div.SequenceComponentIcon", []);
27656         return [
27657             vd.h("div." + prevClass, prevProperties, [prevIcon]),
27658             vd.h("div." + nextClass, nextProperties, [nextIcon]),
27659         ];
27660     };
27661     SequenceDOMRenderer.prototype._createStepper = function (edgeStatus, configuration, containerWidth, component, navigator) {
27662         var nextKey = null;
27663         var prevKey = null;
27664         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
27665             var edge = _a[_i];
27666             if (edge.data.direction === Edge_1.EdgeDirection.Next) {
27667                 nextKey = edge.to;
27668             }
27669             if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
27670                 prevKey = edge.to;
27671             }
27672         }
27673         var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
27674         var buttons = this._createSequenceArrows(nextKey, prevKey, containerWidth, configuration, navigator);
27675         buttons.splice(1, 0, playingButton);
27676         var containerProperties = {
27677             oncontextmenu: function (event) { event.preventDefault(); },
27678             style: {
27679                 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
27680                 width: containerWidth + "px",
27681             },
27682         };
27683         return vd.h("div.SequenceStepper", containerProperties, buttons);
27684     };
27685     SequenceDOMRenderer.prototype._createTimelineControls = function (containerWidth, index, max) {
27686         var _this = this;
27687         if (this._mode !== Component_1.SequenceMode.Timeline) {
27688             return vd.h("div.SequenceTimeline", []);
27689         }
27690         var positionInput = this._createPositionInput(index, max);
27691         var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
27692         var closeButtonProperties = {
27693             onclick: function () {
27694                 _this._mode = Component_1.SequenceMode.Default;
27695                 _this._notifyChanged$.next(_this);
27696             },
27697         };
27698         var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
27699         var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
27700         var playbackProperties = { style: { top: top + "px" } };
27701         return vd.h("div.SequenceTimeline", playbackProperties, [positionInput, closeButton]);
27702     };
27703     SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
27704         var className = direction === Edge_1.EdgeDirection.Next ?
27705             "SequenceStepNext" :
27706             "SequenceStepPrev";
27707         if (key == null) {
27708             className += "Disabled";
27709         }
27710         else {
27711             if (highlightKey === key) {
27712                 className += "Highlight";
27713             }
27714         }
27715         return className;
27716     };
27717     SequenceDOMRenderer.prototype._setChangingPosition = function (value) {
27718         this._changingPosition = value;
27719         this._notifyChangingPositionChanged$.next(value);
27720     };
27721     return SequenceDOMRenderer;
27722 }());
27723 exports.SequenceDOMRenderer = SequenceDOMRenderer;
27724 exports.default = SequenceDOMRenderer;
27725
27726 },{"../../Component":274,"../../Edge":275,"../../Error":276,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],334:[function(require,module,exports){
27727 "use strict";
27728 Object.defineProperty(exports, "__esModule", { value: true });
27729 var SequenceMode;
27730 (function (SequenceMode) {
27731     SequenceMode[SequenceMode["Default"] = 0] = "Default";
27732     SequenceMode[SequenceMode["Playback"] = 1] = "Playback";
27733     SequenceMode[SequenceMode["Timeline"] = 2] = "Timeline";
27734 })(SequenceMode = exports.SequenceMode || (exports.SequenceMode = {}));
27735 exports.default = SequenceMode;
27736
27737 },{}],335:[function(require,module,exports){
27738 "use strict";
27739 Object.defineProperty(exports, "__esModule", { value: true });
27740
27741 var path = require("path");
27742 var Shaders = /** @class */ (function () {
27743     function Shaders() {
27744     }
27745     Shaders.equirectangular = {
27746         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}",
27747         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}",
27748     };
27749     Shaders.equirectangularCurtain = {
27750         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float curtain;\nuniform float opacity;\nuniform float phiLength;\nuniform float phiShift;\nuniform float thetaLength;\nuniform float thetaShift;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    vec3 b = normalize(vRstq.xyz);\n    float lat = -asin(b.y);\n    float lon = atan(b.x, b.z);\n    float x = (lon - phiShift) / phiLength + 0.5;\n    float y = (lat - thetaShift) / thetaLength + 0.5;\n\n    bool inverted = curtain < 0.5;\n\n    float curtainMin = inverted ? curtain + 0.5 : curtain - 0.5;\n    float curtainMax = curtain;\n\n    bool insideCurtain = inverted ?\n        x > curtainMin || x < curtainMax :\n        x > curtainMin && x < curtainMax;\n\n    vec4 baseColor;\n    if (insideCurtain) {\n        baseColor = texture2D(projectorTex, vec2(x, y));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}",
27751         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}",
27752     };
27753     Shaders.perspective = {
27754         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 focal;\nuniform float k1;\nuniform float k2;\nuniform float scale_x;\nuniform float scale_y;\nuniform float radial_peak;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float x = vRstq.x / vRstq.z;\n    float y = vRstq.y / vRstq.z;\n    float r2 = x * x + y * y;\n\n    if (radial_peak > 0. && r2 > radial_peak * sqrt(r2)) {\n        r2 = radial_peak * radial_peak;\n    }\n\n    float d = 1.0 + k1 * r2 + k2 * r2 * r2;\n    float u = scale_x * focal * d * x + 0.5;\n    float v = - scale_y * focal * d * y + 0.5;\n\n    vec4 baseColor;\n    if (u >= 0. && u <= 1. && v >= 0. && v <= 1.) {\n        baseColor = texture2D(projectorTex, vec2(u, v));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}",
27755         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}",
27756     };
27757     Shaders.perspectiveCurtain = {
27758         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 focal;\nuniform float k1;\nuniform float k2;\nuniform float scale_x;\nuniform float scale_y;\nuniform float radial_peak;\nuniform float curtain;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float x = vRstq.x / vRstq.z;\n    float y = vRstq.y / vRstq.z;\n    float r2 = x * x + y * y;\n\n    if (radial_peak > 0. && r2 > radial_peak * sqrt(r2)) {\n        r2 = radial_peak * radial_peak;\n    }\n\n    float d = 1.0 + k1 * r2 + k2 * r2 * r2;\n    float u = scale_x * focal * d * x + 0.5;\n    float v = - scale_y * focal * d * y + 0.5;\n\n    vec4 baseColor;\n    if ((u < curtain || curtain >= 1.0) && u >= 0. && u <= 1. && v >= 0. && v <= 1.) {\n        baseColor = texture2D(projectorTex, vec2(u, v));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}\n",
27759         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}",
27760     };
27761     Shaders.perspectiveDistorted = {
27762         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float u = vRstq.x / vRstq.w;\n    float v = vRstq.y / vRstq.w;\n\n    vec4 baseColor;\n    if (u >= 0. && u <= 1. && v >= 0. && v <= 1.) {\n        baseColor = texture2D(projectorTex, vec2(u, v));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}\n",
27763         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}\n",
27764     };
27765     Shaders.perspectiveDistortedCurtain = {
27766         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float curtain;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float u = vRstq.x / vRstq.w;\n    float v = vRstq.y / vRstq.w;\n\n    vec4 baseColor;\n    if ((u < curtain || curtain >= 1.0) && u >= 0. && u <= 1. && v >= 0. && v <= 1.) {\n        baseColor = texture2D(projectorTex, vec2(u, v));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}\n",
27767         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}\n",
27768     };
27769     return Shaders;
27770 }());
27771 exports.Shaders = Shaders;
27772
27773
27774 },{"path":22}],336:[function(require,module,exports){
27775 "use strict";
27776 var __extends = (this && this.__extends) || (function () {
27777     var extendStatics = function (d, b) {
27778         extendStatics = Object.setPrototypeOf ||
27779             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27780             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27781         return extendStatics(d, b);
27782     }
27783     return function (d, b) {
27784         extendStatics(d, b);
27785         function __() { this.constructor = d; }
27786         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27787     };
27788 })();
27789 Object.defineProperty(exports, "__esModule", { value: true });
27790 var rxjs_1 = require("rxjs");
27791 var operators_1 = require("rxjs/operators");
27792 var Component_1 = require("../../Component");
27793 var Geo_1 = require("../../Geo");
27794 var State_1 = require("../../State");
27795 var Render_1 = require("../../Render");
27796 var Tiles_1 = require("../../Tiles");
27797 var Utils_1 = require("../../Utils");
27798 /**
27799  * @class SliderComponent
27800  *
27801  * @classdesc Component for comparing pairs of images. Renders
27802  * a slider for adjusting the curtain of the first image.
27803  *
27804  * Deactivate the sequence, direction and image plane
27805  * components when activating the slider component to avoid
27806  * interfering UI elements.
27807  *
27808  * To retrive and use the marker component
27809  *
27810  * @example
27811  * ```
27812  * var viewer = new Mapillary.Viewer(
27813  *     "<element-id>",
27814  *     "<client-id>",
27815  *     "<my key>");
27816  *
27817  * viewer.deactivateComponent("imagePlane");
27818  * viewer.deactivateComponent("direction");
27819  * viewer.deactivateComponent("sequence");
27820  *
27821  * viewer.activateComponent("slider");
27822  *
27823  * var sliderComponent = viewer.getComponent("marker");
27824  * ```
27825  */
27826 var SliderComponent = /** @class */ (function (_super) {
27827     __extends(SliderComponent, _super);
27828     /** @ignore */
27829     function SliderComponent(name, container, navigator, viewportCoords) {
27830         var _this = _super.call(this, name, container, navigator) || this;
27831         _this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
27832         _this._domRenderer = new Component_1.SliderDOMRenderer(container);
27833         _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
27834         _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
27835         _this._spatial = new Geo_1.Spatial();
27836         _this._glRendererOperation$ = new rxjs_1.Subject();
27837         _this._glRendererCreator$ = new rxjs_1.Subject();
27838         _this._glRendererDisposer$ = new rxjs_1.Subject();
27839         _this._glRenderer$ = _this._glRendererOperation$.pipe(operators_1.scan(function (glRenderer, operation) {
27840             return operation(glRenderer);
27841         }, null), operators_1.filter(function (glRenderer) {
27842             return glRenderer != null;
27843         }), operators_1.distinctUntilChanged(undefined, function (glRenderer) {
27844             return glRenderer.frameId;
27845         }));
27846         _this._glRendererCreator$.pipe(operators_1.map(function () {
27847             return function (glRenderer) {
27848                 if (glRenderer != null) {
27849                     throw new Error("Multiple slider states can not be created at the same time");
27850                 }
27851                 return new Component_1.SliderGLRenderer();
27852             };
27853         }))
27854             .subscribe(_this._glRendererOperation$);
27855         _this._glRendererDisposer$.pipe(operators_1.map(function () {
27856             return function (glRenderer) {
27857                 glRenderer.dispose();
27858                 return null;
27859             };
27860         }))
27861             .subscribe(_this._glRendererOperation$);
27862         return _this;
27863     }
27864     /**
27865      * Set the initial position.
27866      *
27867      * @description Configures the intial position of the slider.
27868      * The inital position value will be used when the component
27869      * is activated.
27870      *
27871      * @param {number} initialPosition - Initial slider position.
27872      */
27873     SliderComponent.prototype.setInitialPosition = function (initialPosition) {
27874         this.configure({ initialPosition: initialPosition });
27875     };
27876     /**
27877      * Set the image keys.
27878      *
27879      * @description Configures the component to show the image
27880      * planes for the supplied image keys.
27881      *
27882      * @param {ISliderKeys} keys - Slider keys object specifying
27883      * the images to be shown in the foreground and the background.
27884      */
27885     SliderComponent.prototype.setKeys = function (keys) {
27886         this.configure({ keys: keys });
27887     };
27888     /**
27889      * Set the slider mode.
27890      *
27891      * @description Configures the mode for transitions between
27892      * image pairs.
27893      *
27894      * @param {SliderMode} mode - Slider mode to be set.
27895      */
27896     SliderComponent.prototype.setSliderMode = function (mode) {
27897         this.configure({ mode: mode });
27898     };
27899     /**
27900      * Set the value controlling if the slider is visible.
27901      *
27902      * @param {boolean} sliderVisible - Value indicating if
27903      * the slider should be visible or not.
27904      */
27905     SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
27906         this.configure({ sliderVisible: sliderVisible });
27907     };
27908     SliderComponent.prototype._activate = function () {
27909         var _this = this;
27910         this._modeSubcription = this._domRenderer.mode$
27911             .subscribe(function (mode) {
27912             _this.setSliderMode(mode);
27913         });
27914         this._glRenderSubscription = this._glRenderer$.pipe(operators_1.map(function (glRenderer) {
27915             var renderHash = {
27916                 name: _this._name,
27917                 render: {
27918                     frameId: glRenderer.frameId,
27919                     needsRender: glRenderer.needsRender,
27920                     render: glRenderer.render.bind(glRenderer),
27921                     stage: Render_1.GLRenderStage.Background,
27922                 },
27923             };
27924             return renderHash;
27925         }))
27926             .subscribe(this._container.glRenderer.render$);
27927         var position$ = rxjs_1.concat(this.configuration$.pipe(operators_1.map(function (configuration) {
27928             return configuration.initialPosition != null ?
27929                 configuration.initialPosition : 1;
27930         }), operators_1.first()), this._domRenderer.position$);
27931         var mode$ = this.configuration$.pipe(operators_1.map(function (configuration) {
27932             return configuration.mode;
27933         }), operators_1.distinctUntilChanged());
27934         var motionless$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
27935             return frame.state.motionless;
27936         }), operators_1.distinctUntilChanged());
27937         var fullPano$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
27938             return frame.state.currentNode.fullPano;
27939         }), operators_1.distinctUntilChanged());
27940         var sliderVisible$ = rxjs_1.combineLatest(this._configuration$.pipe(operators_1.map(function (configuration) {
27941             return configuration.sliderVisible;
27942         })), this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
27943             return !(frame.state.currentNode == null ||
27944                 frame.state.previousNode == null ||
27945                 (frame.state.currentNode.pano && !frame.state.currentNode.fullPano) ||
27946                 (frame.state.previousNode.pano && !frame.state.previousNode.fullPano) ||
27947                 (frame.state.currentNode.fullPano && !frame.state.previousNode.fullPano));
27948         }), operators_1.distinctUntilChanged())).pipe(operators_1.map(function (_a) {
27949             var sliderVisible = _a[0], enabledState = _a[1];
27950             return sliderVisible && enabledState;
27951         }), operators_1.distinctUntilChanged());
27952         this._waitSubscription = rxjs_1.combineLatest(mode$, motionless$, fullPano$, sliderVisible$).pipe(operators_1.withLatestFrom(this._navigator.stateService.state$))
27953             .subscribe(function (_a) {
27954             var _b = _a[0], mode = _b[0], motionless = _b[1], fullPano = _b[2], sliderVisible = _b[3], state = _a[1];
27955             var interactive = sliderVisible &&
27956                 (motionless || mode === Component_1.SliderMode.Stationary || fullPano);
27957             if (interactive && state !== State_1.State.WaitingInteractively) {
27958                 _this._navigator.stateService.waitInteractively();
27959             }
27960             else if (!interactive && state !== State_1.State.Waiting) {
27961                 _this._navigator.stateService.wait();
27962             }
27963         });
27964         this._moveSubscription = rxjs_1.combineLatest(position$, mode$, motionless$, fullPano$, sliderVisible$)
27965             .subscribe(function (_a) {
27966             var position = _a[0], mode = _a[1], motionless = _a[2], fullPano = _a[3], sliderVisible = _a[4];
27967             if (motionless || mode === Component_1.SliderMode.Stationary || fullPano) {
27968                 _this._navigator.stateService.moveTo(1);
27969             }
27970             else {
27971                 _this._navigator.stateService.moveTo(position);
27972             }
27973         });
27974         this._domRenderSubscription = rxjs_1.combineLatest(position$, mode$, motionless$, fullPano$, sliderVisible$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
27975             var position = _a[0], mode = _a[1], motionless = _a[2], fullPano = _a[3], sliderVisible = _a[4], size = _a[5];
27976             return {
27977                 name: _this._name,
27978                 vnode: _this._domRenderer.render(position, mode, motionless, fullPano, sliderVisible),
27979             };
27980         }))
27981             .subscribe(this._container.domRenderer.render$);
27982         this._glRendererCreator$.next(null);
27983         this._updateCurtainSubscription = rxjs_1.combineLatest(position$, fullPano$, sliderVisible$, this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$).pipe(operators_1.map(function (_a) {
27984             var position = _a[0], fullPano = _a[1], visible = _a[2], render = _a[3], transform = _a[4];
27985             if (!fullPano) {
27986                 return visible ? position : 1;
27987             }
27988             var basicMin = _this._viewportCoords.viewportToBasic(-1.15, 0, transform, render.perspective);
27989             var basicMax = _this._viewportCoords.viewportToBasic(1.15, 0, transform, render.perspective);
27990             var shiftedMax = basicMax[0] < basicMin[0] ? basicMax[0] + 1 : basicMax[0];
27991             var basicPosition = basicMin[0] + position * (shiftedMax - basicMin[0]);
27992             return basicPosition > 1 ? basicPosition - 1 : basicPosition;
27993         }), operators_1.map(function (position) {
27994             return function (glRenderer) {
27995                 glRenderer.updateCurtain(position);
27996                 return glRenderer;
27997             };
27998         }))
27999             .subscribe(this._glRendererOperation$);
28000         this._stateSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentState$, mode$).pipe(operators_1.map(function (_a) {
28001             var frame = _a[0], mode = _a[1];
28002             return function (glRenderer) {
28003                 glRenderer.update(frame, mode);
28004                 return glRenderer;
28005             };
28006         }))
28007             .subscribe(this._glRendererOperation$);
28008         this._setKeysSubscription = this._configuration$.pipe(operators_1.filter(function (configuration) {
28009             return configuration.keys != null;
28010         }), operators_1.switchMap(function (configuration) {
28011             return rxjs_1.zip(rxjs_1.zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground)).pipe(operators_1.map(function (nodes) {
28012                 return { background: nodes[0], foreground: nodes[1] };
28013             })), _this._navigator.stateService.currentState$.pipe(operators_1.first())).pipe(operators_1.map(function (nf) {
28014                 return { nodes: nf[0], state: nf[1].state };
28015             }));
28016         }))
28017             .subscribe(function (co) {
28018             if (co.state.currentNode != null &&
28019                 co.state.previousNode != null &&
28020                 co.state.currentNode.key === co.nodes.foreground.key &&
28021                 co.state.previousNode.key === co.nodes.background.key) {
28022                 return;
28023             }
28024             if (co.state.currentNode.key === co.nodes.background.key) {
28025                 _this._navigator.stateService.setNodes([co.nodes.foreground]);
28026                 return;
28027             }
28028             if (co.state.currentNode.key === co.nodes.foreground.key &&
28029                 co.state.trajectory.length === 1) {
28030                 _this._navigator.stateService.prependNodes([co.nodes.background]);
28031                 return;
28032             }
28033             _this._navigator.stateService.setNodes([co.nodes.background]);
28034             _this._navigator.stateService.setNodes([co.nodes.foreground]);
28035         }, function (e) {
28036             console.error(e);
28037         });
28038         var previousNode$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
28039             return frame.state.previousNode;
28040         }), operators_1.filter(function (node) {
28041             return node != null;
28042         }), operators_1.distinctUntilChanged(undefined, function (node) {
28043             return node.key;
28044         }));
28045         var textureProvider$ = this._navigator.stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
28046             return frame.state.currentNode.key;
28047         }), operators_1.withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), operators_1.map(function (_a) {
28048             var frame = _a[0], renderer = _a[1], size = _a[2];
28049             var state = frame.state;
28050             var viewportSize = Math.max(size.width, size.height);
28051             var currentNode = state.currentNode;
28052             var currentTransform = state.currentTransform;
28053             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
28054             return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
28055         }), operators_1.publishReplay(1), operators_1.refCount());
28056         this._textureProviderSubscription = textureProvider$.subscribe(function () { });
28057         this._setTextureProviderSubscription = textureProvider$.pipe(operators_1.map(function (provider) {
28058             return function (renderer) {
28059                 renderer.setTextureProvider(provider.key, provider);
28060                 return renderer;
28061             };
28062         }))
28063             .subscribe(this._glRendererOperation$);
28064         this._setTileSizeSubscription = this._container.renderService.size$.pipe(operators_1.switchMap(function (size) {
28065             return rxjs_1.combineLatest(textureProvider$, rxjs_1.of(size)).pipe(operators_1.first());
28066         }))
28067             .subscribe(function (_a) {
28068             var provider = _a[0], size = _a[1];
28069             var viewportSize = Math.max(size.width, size.height);
28070             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
28071             provider.setTileSize(tileSize);
28072         });
28073         this._abortTextureProviderSubscription = textureProvider$.pipe(operators_1.pairwise())
28074             .subscribe(function (pair) {
28075             var previous = pair[0];
28076             previous.abort();
28077         });
28078         var roiTrigger$ = rxjs_1.combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(operators_1.debounceTime(250))).pipe(operators_1.map(function (_a) {
28079             var camera = _a[0], size = _a[1];
28080             return [
28081                 camera.camera.position.clone(),
28082                 camera.camera.lookat.clone(),
28083                 camera.zoom.valueOf(),
28084                 size.height.valueOf(),
28085                 size.width.valueOf()
28086             ];
28087         }), operators_1.pairwise(), operators_1.skipWhile(function (pls) {
28088             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
28089         }), operators_1.map(function (pls) {
28090             var samePosition = pls[0][0].equals(pls[1][0]);
28091             var sameLookat = pls[0][1].equals(pls[1][1]);
28092             var sameZoom = pls[0][2] === pls[1][2];
28093             var sameHeight = pls[0][3] === pls[1][3];
28094             var sameWidth = pls[0][4] === pls[1][4];
28095             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
28096         }), operators_1.distinctUntilChanged(), operators_1.filter(function (stalled) {
28097             return stalled;
28098         }), operators_1.switchMap(function (stalled) {
28099             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.first());
28100         }), operators_1.withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$));
28101         this._setRegionOfInterestSubscription = textureProvider$.pipe(operators_1.switchMap(function (provider) {
28102             return roiTrigger$.pipe(operators_1.map(function (_a) {
28103                 var camera = _a[0], size = _a[1], transform = _a[2];
28104                 return [
28105                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
28106                     provider,
28107                 ];
28108             }));
28109         }), operators_1.filter(function (args) {
28110             return !args[1].disposed;
28111         }))
28112             .subscribe(function (args) {
28113             var roi = args[0];
28114             var provider = args[1];
28115             provider.setRegionOfInterest(roi);
28116         });
28117         var hasTexture$ = textureProvider$.pipe(operators_1.switchMap(function (provider) {
28118             return provider.hasTexture$;
28119         }), operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
28120         this._hasTextureSubscription = hasTexture$.subscribe(function () { });
28121         var nodeImage$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
28122             return frame.state.nodesAhead === 0;
28123         }), operators_1.map(function (frame) {
28124             return frame.state.currentNode;
28125         }), operators_1.distinctUntilChanged(undefined, function (node) {
28126             return node.key;
28127         }), operators_1.debounceTime(1000), operators_1.withLatestFrom(hasTexture$), operators_1.filter(function (args) {
28128             return !args[1];
28129         }), operators_1.map(function (args) {
28130             return args[0];
28131         }), operators_1.filter(function (node) {
28132             return node.pano ?
28133                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
28134                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
28135         }), operators_1.switchMap(function (node) {
28136             var baseImageSize = node.pano ?
28137                 Utils_1.Settings.basePanoramaSize :
28138                 Utils_1.Settings.baseImageSize;
28139             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
28140                 return rxjs_1.empty();
28141             }
28142             var image$ = node
28143                 .cacheImage$(Utils_1.Settings.maxImageSize).pipe(operators_1.map(function (n) {
28144                 return [n.image, n];
28145             }));
28146             return image$.pipe(operators_1.takeUntil(hasTexture$.pipe(operators_1.filter(function (hasTexture) {
28147                 return hasTexture;
28148             }))), operators_1.catchError(function (error, caught) {
28149                 console.error("Failed to fetch high res image (" + node.key + ")", error);
28150                 return rxjs_1.empty();
28151             }));
28152         })).pipe(operators_1.publish(), operators_1.refCount());
28153         this._updateBackgroundSubscription = nodeImage$.pipe(operators_1.withLatestFrom(textureProvider$))
28154             .subscribe(function (args) {
28155             if (args[0][1].key !== args[1].key ||
28156                 args[1].disposed) {
28157                 return;
28158             }
28159             args[1].updateBackground(args[0][0]);
28160         });
28161         this._updateTextureImageSubscription = nodeImage$.pipe(operators_1.map(function (imn) {
28162             return function (renderer) {
28163                 renderer.updateTextureImage(imn[0], imn[1]);
28164                 return renderer;
28165             };
28166         }))
28167             .subscribe(this._glRendererOperation$);
28168         var textureProviderPrev$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
28169             return !!frame.state.previousNode;
28170         }), operators_1.distinctUntilChanged(undefined, function (frame) {
28171             return frame.state.previousNode.key;
28172         }), operators_1.withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), operators_1.map(function (_a) {
28173             var frame = _a[0], renderer = _a[1], size = _a[2];
28174             var state = frame.state;
28175             var viewportSize = Math.max(size.width, size.height);
28176             var previousNode = state.previousNode;
28177             var previousTransform = state.previousTransform;
28178             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
28179             return new Tiles_1.TextureProvider(previousNode.key, previousTransform.basicWidth, previousTransform.basicHeight, tileSize, previousNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
28180         }), operators_1.publishReplay(1), operators_1.refCount());
28181         this._textureProviderSubscriptionPrev = textureProviderPrev$.subscribe(function () { });
28182         this._setTextureProviderSubscriptionPrev = textureProviderPrev$.pipe(operators_1.map(function (provider) {
28183             return function (renderer) {
28184                 renderer.setTextureProviderPrev(provider.key, provider);
28185                 return renderer;
28186             };
28187         }))
28188             .subscribe(this._glRendererOperation$);
28189         this._setTileSizeSubscriptionPrev = this._container.renderService.size$.pipe(operators_1.switchMap(function (size) {
28190             return rxjs_1.combineLatest(textureProviderPrev$, rxjs_1.of(size)).pipe(operators_1.first());
28191         }))
28192             .subscribe(function (_a) {
28193             var provider = _a[0], size = _a[1];
28194             var viewportSize = Math.max(size.width, size.height);
28195             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
28196             provider.setTileSize(tileSize);
28197         });
28198         this._abortTextureProviderSubscriptionPrev = textureProviderPrev$.pipe(operators_1.pairwise())
28199             .subscribe(function (pair) {
28200             var previous = pair[0];
28201             previous.abort();
28202         });
28203         var roiTriggerPrev$ = rxjs_1.combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(operators_1.debounceTime(250))).pipe(operators_1.map(function (_a) {
28204             var camera = _a[0], size = _a[1];
28205             return [
28206                 camera.camera.position.clone(),
28207                 camera.camera.lookat.clone(),
28208                 camera.zoom.valueOf(),
28209                 size.height.valueOf(),
28210                 size.width.valueOf()
28211             ];
28212         }), operators_1.pairwise(), operators_1.skipWhile(function (pls) {
28213             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
28214         }), operators_1.map(function (pls) {
28215             var samePosition = pls[0][0].equals(pls[1][0]);
28216             var sameLookat = pls[0][1].equals(pls[1][1]);
28217             var sameZoom = pls[0][2] === pls[1][2];
28218             var sameHeight = pls[0][3] === pls[1][3];
28219             var sameWidth = pls[0][4] === pls[1][4];
28220             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
28221         }), operators_1.distinctUntilChanged(), operators_1.filter(function (stalled) {
28222             return stalled;
28223         }), operators_1.switchMap(function (stalled) {
28224             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.first());
28225         }), operators_1.withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$));
28226         this._setRegionOfInterestSubscriptionPrev = textureProviderPrev$.pipe(operators_1.switchMap(function (provider) {
28227             return roiTriggerPrev$.pipe(operators_1.map(function (_a) {
28228                 var camera = _a[0], size = _a[1], transform = _a[2];
28229                 return [
28230                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
28231                     provider,
28232                 ];
28233             }));
28234         }), operators_1.filter(function (args) {
28235             return !args[1].disposed;
28236         }), operators_1.withLatestFrom(this._navigator.stateService.currentState$))
28237             .subscribe(function (_a) {
28238             var _b = _a[0], roi = _b[0], provider = _b[1], frame = _a[1];
28239             var shiftedRoi = null;
28240             if (frame.state.previousNode.fullPano) {
28241                 if (frame.state.currentNode.fullPano) {
28242                     var currentViewingDirection = _this._spatial.viewingDirection(frame.state.currentNode.rotation);
28243                     var previousViewingDirection = _this._spatial.viewingDirection(frame.state.previousNode.rotation);
28244                     var directionDiff = _this._spatial.angleBetweenVector2(currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y);
28245                     var shift = directionDiff / (2 * Math.PI);
28246                     var bbox = {
28247                         maxX: _this._spatial.wrap(roi.bbox.maxX + shift, 0, 1),
28248                         maxY: roi.bbox.maxY,
28249                         minX: _this._spatial.wrap(roi.bbox.minX + shift, 0, 1),
28250                         minY: roi.bbox.minY,
28251                     };
28252                     shiftedRoi = {
28253                         bbox: bbox,
28254                         pixelHeight: roi.pixelHeight,
28255                         pixelWidth: roi.pixelWidth,
28256                     };
28257                 }
28258                 else {
28259                     var currentViewingDirection = _this._spatial.viewingDirection(frame.state.currentNode.rotation);
28260                     var previousViewingDirection = _this._spatial.viewingDirection(frame.state.previousNode.rotation);
28261                     var directionDiff = _this._spatial.angleBetweenVector2(currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y);
28262                     var shiftX = directionDiff / (2 * Math.PI);
28263                     var a1 = _this._spatial.angleToPlane(currentViewingDirection.toArray(), [0, 0, 1]);
28264                     var a2 = _this._spatial.angleToPlane(previousViewingDirection.toArray(), [0, 0, 1]);
28265                     var shiftY = (a2 - a1) / (2 * Math.PI);
28266                     var currentTransform = frame.state.currentTransform;
28267                     var size = Math.max(currentTransform.basicWidth, currentTransform.basicHeight);
28268                     var hFov = size > 0 ?
28269                         2 * Math.atan(0.5 * currentTransform.basicWidth / (size * currentTransform.focal)) :
28270                         Math.PI / 3;
28271                     var vFov = size > 0 ?
28272                         2 * Math.atan(0.5 * currentTransform.basicHeight / (size * currentTransform.focal)) :
28273                         Math.PI / 3;
28274                     var spanningWidth = hFov / (2 * Math.PI);
28275                     var spanningHeight = vFov / Math.PI;
28276                     var basicWidth = (roi.bbox.maxX - roi.bbox.minX) * spanningWidth;
28277                     var basicHeight = (roi.bbox.maxY - roi.bbox.minY) * spanningHeight;
28278                     var pixelWidth = roi.pixelWidth * spanningWidth;
28279                     var pixelHeight = roi.pixelHeight * spanningHeight;
28280                     var zoomShiftX = (roi.bbox.minX + roi.bbox.maxX) / 2 - 0.5;
28281                     var zoomShiftY = (roi.bbox.minY + roi.bbox.maxY) / 2 - 0.5;
28282                     var minX = 0.5 + shiftX + spanningWidth * zoomShiftX - basicWidth / 2;
28283                     var maxX = 0.5 + shiftX + spanningWidth * zoomShiftX + basicWidth / 2;
28284                     var minY = 0.5 + shiftY + spanningHeight * zoomShiftY - basicHeight / 2;
28285                     var maxY = 0.5 + shiftY + spanningHeight * zoomShiftY + basicHeight / 2;
28286                     var bbox = {
28287                         maxX: _this._spatial.wrap(maxX, 0, 1),
28288                         maxY: maxY,
28289                         minX: _this._spatial.wrap(minX, 0, 1),
28290                         minY: minY,
28291                     };
28292                     shiftedRoi = {
28293                         bbox: bbox,
28294                         pixelHeight: pixelHeight,
28295                         pixelWidth: pixelWidth,
28296                     };
28297                 }
28298             }
28299             else {
28300                 var currentBasicAspect = frame.state.currentTransform.basicAspect;
28301                 var previousBasicAspect = frame.state.previousTransform.basicAspect;
28302                 var _c = _this._getBasicCorners(currentBasicAspect, previousBasicAspect), _d = _c[0], cornerMinX = _d[0], cornerMinY = _d[1], _e = _c[1], cornerMaxX = _e[0], cornerMaxY = _e[1];
28303                 var basicWidth = cornerMaxX - cornerMinX;
28304                 var basicHeight = cornerMaxY - cornerMinY;
28305                 var pixelWidth = roi.pixelWidth / basicWidth;
28306                 var pixelHeight = roi.pixelHeight / basicHeight;
28307                 var minX = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.minX / basicWidth;
28308                 var maxX = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.maxX / basicWidth;
28309                 var minY = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.minY / basicHeight;
28310                 var maxY = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.maxY / basicHeight;
28311                 var bbox = {
28312                     maxX: maxX,
28313                     maxY: maxY,
28314                     minX: minX,
28315                     minY: minY,
28316                 };
28317                 _this._clipBoundingBox(bbox);
28318                 shiftedRoi = {
28319                     bbox: bbox,
28320                     pixelHeight: pixelHeight,
28321                     pixelWidth: pixelWidth,
28322                 };
28323             }
28324             provider.setRegionOfInterest(shiftedRoi);
28325         });
28326         var hasTexturePrev$ = textureProviderPrev$.pipe(operators_1.switchMap(function (provider) {
28327             return provider.hasTexture$;
28328         }), operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
28329         this._hasTextureSubscriptionPrev = hasTexturePrev$.subscribe(function () { });
28330         var nodeImagePrev$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
28331             return frame.state.nodesAhead === 0 && !!frame.state.previousNode;
28332         }), operators_1.map(function (frame) {
28333             return frame.state.previousNode;
28334         }), operators_1.distinctUntilChanged(undefined, function (node) {
28335             return node.key;
28336         }), operators_1.debounceTime(1000), operators_1.withLatestFrom(hasTexturePrev$), operators_1.filter(function (args) {
28337             return !args[1];
28338         }), operators_1.map(function (args) {
28339             return args[0];
28340         }), operators_1.filter(function (node) {
28341             return node.pano ?
28342                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
28343                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
28344         }), operators_1.switchMap(function (node) {
28345             var baseImageSize = node.pano ?
28346                 Utils_1.Settings.basePanoramaSize :
28347                 Utils_1.Settings.baseImageSize;
28348             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
28349                 return rxjs_1.empty();
28350             }
28351             var image$ = node
28352                 .cacheImage$(Utils_1.Settings.maxImageSize).pipe(operators_1.map(function (n) {
28353                 return [n.image, n];
28354             }));
28355             return image$.pipe(operators_1.takeUntil(hasTexturePrev$.pipe(operators_1.filter(function (hasTexture) {
28356                 return hasTexture;
28357             }))), operators_1.catchError(function (error, caught) {
28358                 console.error("Failed to fetch high res image (" + node.key + ")", error);
28359                 return rxjs_1.empty();
28360             }));
28361         })).pipe(operators_1.publish(), operators_1.refCount());
28362         this._updateBackgroundSubscriptionPrev = nodeImagePrev$.pipe(operators_1.withLatestFrom(textureProviderPrev$))
28363             .subscribe(function (args) {
28364             if (args[0][1].key !== args[1].key ||
28365                 args[1].disposed) {
28366                 return;
28367             }
28368             args[1].updateBackground(args[0][0]);
28369         });
28370         this._updateTextureImageSubscriptionPrev = nodeImagePrev$.pipe(operators_1.map(function (imn) {
28371             return function (renderer) {
28372                 renderer.updateTextureImage(imn[0], imn[1]);
28373                 return renderer;
28374             };
28375         }))
28376             .subscribe(this._glRendererOperation$);
28377     };
28378     SliderComponent.prototype._deactivate = function () {
28379         var _this = this;
28380         this._waitSubscription.unsubscribe();
28381         this._navigator.stateService.state$.pipe(operators_1.first())
28382             .subscribe(function (state) {
28383             if (state !== State_1.State.Traversing) {
28384                 _this._navigator.stateService.traverse();
28385             }
28386         });
28387         this._glRendererDisposer$.next(null);
28388         this._domRenderer.deactivate();
28389         this._modeSubcription.unsubscribe();
28390         this._setKeysSubscription.unsubscribe();
28391         this._stateSubscription.unsubscribe();
28392         this._glRenderSubscription.unsubscribe();
28393         this._domRenderSubscription.unsubscribe();
28394         this._moveSubscription.unsubscribe();
28395         this._updateCurtainSubscription.unsubscribe();
28396         this._textureProviderSubscription.unsubscribe();
28397         this._setTextureProviderSubscription.unsubscribe();
28398         this._setTileSizeSubscription.unsubscribe();
28399         this._abortTextureProviderSubscription.unsubscribe();
28400         this._setRegionOfInterestSubscription.unsubscribe();
28401         this._hasTextureSubscription.unsubscribe();
28402         this._updateBackgroundSubscription.unsubscribe();
28403         this._updateTextureImageSubscription.unsubscribe();
28404         this._textureProviderSubscriptionPrev.unsubscribe();
28405         this._setTextureProviderSubscriptionPrev.unsubscribe();
28406         this._setTileSizeSubscriptionPrev.unsubscribe();
28407         this._abortTextureProviderSubscriptionPrev.unsubscribe();
28408         this._setRegionOfInterestSubscriptionPrev.unsubscribe();
28409         this._hasTextureSubscriptionPrev.unsubscribe();
28410         this._updateBackgroundSubscriptionPrev.unsubscribe();
28411         this._updateTextureImageSubscriptionPrev.unsubscribe();
28412         this.configure({ keys: null });
28413     };
28414     SliderComponent.prototype._getDefaultConfiguration = function () {
28415         return {
28416             initialPosition: 1,
28417             mode: Component_1.SliderMode.Motion,
28418             sliderVisible: true,
28419         };
28420     };
28421     SliderComponent.prototype._catchCacheNode$ = function (key) {
28422         return this._navigator.graphService.cacheNode$(key).pipe(operators_1.catchError(function (error, caught) {
28423             console.error("Failed to cache slider node (" + key + ")", error);
28424             return rxjs_1.empty();
28425         }));
28426     };
28427     SliderComponent.prototype._getBasicCorners = function (currentAspect, previousAspect) {
28428         var offsetX;
28429         var offsetY;
28430         if (currentAspect > previousAspect) {
28431             offsetX = 0.5;
28432             offsetY = 0.5 * currentAspect / previousAspect;
28433         }
28434         else {
28435             offsetX = 0.5 * previousAspect / currentAspect;
28436             offsetY = 0.5;
28437         }
28438         return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]];
28439     };
28440     SliderComponent.prototype._clipBoundingBox = function (bbox) {
28441         bbox.minX = Math.max(0, Math.min(1, bbox.minX));
28442         bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
28443         bbox.minY = Math.max(0, Math.min(1, bbox.minY));
28444         bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
28445     };
28446     SliderComponent.componentName = "slider";
28447     return SliderComponent;
28448 }(Component_1.Component));
28449 exports.SliderComponent = SliderComponent;
28450 Component_1.ComponentService.register(SliderComponent);
28451 exports.default = SliderComponent;
28452
28453
28454 },{"../../Component":274,"../../Geo":277,"../../Render":280,"../../State":281,"../../Tiles":283,"../../Utils":284,"rxjs":26,"rxjs/operators":224}],337:[function(require,module,exports){
28455 "use strict";
28456 Object.defineProperty(exports, "__esModule", { value: true });
28457 var rxjs_1 = require("rxjs");
28458 var operators_1 = require("rxjs/operators");
28459 var vd = require("virtual-dom");
28460 var Component_1 = require("../../Component");
28461 var SliderDOMRenderer = /** @class */ (function () {
28462     function SliderDOMRenderer(container) {
28463         this._container = container;
28464         this._interacting = false;
28465         this._notifyModeChanged$ = new rxjs_1.Subject();
28466         this._notifyPositionChanged$ = new rxjs_1.Subject();
28467         this._stopInteractionSubscription = null;
28468     }
28469     Object.defineProperty(SliderDOMRenderer.prototype, "mode$", {
28470         get: function () {
28471             return this._notifyModeChanged$;
28472         },
28473         enumerable: true,
28474         configurable: true
28475     });
28476     Object.defineProperty(SliderDOMRenderer.prototype, "position$", {
28477         get: function () {
28478             return this._notifyPositionChanged$;
28479         },
28480         enumerable: true,
28481         configurable: true
28482     });
28483     SliderDOMRenderer.prototype.activate = function () {
28484         var _this = this;
28485         if (!!this._stopInteractionSubscription) {
28486             return;
28487         }
28488         this._stopInteractionSubscription = rxjs_1.merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$.pipe(operators_1.filter(function (touchEvent) {
28489             return touchEvent.touches.length === 0;
28490         })))
28491             .subscribe(function (event) {
28492             if (_this._interacting) {
28493                 _this._interacting = false;
28494             }
28495         });
28496     };
28497     SliderDOMRenderer.prototype.deactivate = function () {
28498         if (!this._stopInteractionSubscription) {
28499             return;
28500         }
28501         this._interacting = false;
28502         this._stopInteractionSubscription.unsubscribe();
28503         this._stopInteractionSubscription = null;
28504     };
28505     SliderDOMRenderer.prototype.render = function (position, mode, motionless, pano, visible) {
28506         var children = [];
28507         if (visible) {
28508             children.push(vd.h("div.SliderBorder", []));
28509             var modeVisible = !(motionless || pano);
28510             if (modeVisible) {
28511                 children.push(this._createModeButton(mode));
28512             }
28513             children.push(this._createPositionInput(position, modeVisible));
28514         }
28515         var boundingRect = this._container.domContainer.getBoundingClientRect();
28516         var width = Math.max(215, Math.min(400, boundingRect.width - 100));
28517         return vd.h("div.SliderContainer", { style: { width: width + "px" } }, children);
28518     };
28519     SliderDOMRenderer.prototype._createModeButton = function (mode) {
28520         var _this = this;
28521         var properties = {
28522             onclick: function () {
28523                 _this._notifyModeChanged$.next(mode === Component_1.SliderMode.Motion ?
28524                     Component_1.SliderMode.Stationary :
28525                     Component_1.SliderMode.Motion);
28526             },
28527         };
28528         var className = mode === Component_1.SliderMode.Stationary ?
28529             "SliderModeButtonPressed" :
28530             "SliderModeButton";
28531         return vd.h("div." + className, properties, [vd.h("div.SliderModeIcon", [])]);
28532     };
28533     SliderDOMRenderer.prototype._createPositionInput = function (position, modeVisible) {
28534         var _this = this;
28535         var onChange = function (e) {
28536             _this._notifyPositionChanged$.next(Number(e.target.value) / 1000);
28537         };
28538         var onStart = function (e) {
28539             _this._interacting = true;
28540             e.stopPropagation();
28541         };
28542         var onMove = function (e) {
28543             if (_this._interacting) {
28544                 e.stopPropagation();
28545             }
28546         };
28547         var onKeyDown = function (e) {
28548             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
28549                 e.key === "ArrowRight" || e.key === "ArrowUp") {
28550                 e.preventDefault();
28551             }
28552         };
28553         var boundingRect = this._container.domContainer.getBoundingClientRect();
28554         var width = Math.max(215, Math.min(400, boundingRect.width - 105)) - 68 + (modeVisible ? 0 : 36);
28555         var positionInput = vd.h("input.SliderPosition", {
28556             max: 1000,
28557             min: 0,
28558             onchange: onChange,
28559             oninput: onChange,
28560             onkeydown: onKeyDown,
28561             onmousedown: onStart,
28562             onmousemove: onMove,
28563             ontouchmove: onMove,
28564             ontouchstart: onStart,
28565             style: {
28566                 width: width + "px",
28567             },
28568             type: "range",
28569             value: 1000 * position,
28570         }, []);
28571         return vd.h("div.SliderPositionContainer", [positionInput]);
28572     };
28573     return SliderDOMRenderer;
28574 }());
28575 exports.SliderDOMRenderer = SliderDOMRenderer;
28576 exports.default = SliderDOMRenderer;
28577
28578 },{"../../Component":274,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],338:[function(require,module,exports){
28579 "use strict";
28580 Object.defineProperty(exports, "__esModule", { value: true });
28581 var Component_1 = require("../../Component");
28582 var Geo_1 = require("../../Geo");
28583 var SliderGLRenderer = /** @class */ (function () {
28584     function SliderGLRenderer() {
28585         this._factory = new Component_1.MeshFactory();
28586         this._scene = new Component_1.MeshScene();
28587         this._spatial = new Geo_1.Spatial();
28588         this._currentKey = null;
28589         this._previousKey = null;
28590         this._disabled = false;
28591         this._curtain = 1;
28592         this._frameId = 0;
28593         this._needsRender = false;
28594         this._mode = null;
28595         this._currentProviderDisposers = {};
28596         this._previousProviderDisposers = {};
28597     }
28598     Object.defineProperty(SliderGLRenderer.prototype, "disabled", {
28599         get: function () {
28600             return this._disabled;
28601         },
28602         enumerable: true,
28603         configurable: true
28604     });
28605     Object.defineProperty(SliderGLRenderer.prototype, "frameId", {
28606         get: function () {
28607             return this._frameId;
28608         },
28609         enumerable: true,
28610         configurable: true
28611     });
28612     Object.defineProperty(SliderGLRenderer.prototype, "needsRender", {
28613         get: function () {
28614             return this._needsRender;
28615         },
28616         enumerable: true,
28617         configurable: true
28618     });
28619     SliderGLRenderer.prototype.setTextureProvider = function (key, provider) {
28620         this._setTextureProvider(key, this._currentKey, provider, this._currentProviderDisposers, this._updateTexture.bind(this));
28621     };
28622     SliderGLRenderer.prototype.setTextureProviderPrev = function (key, provider) {
28623         this._setTextureProvider(key, this._previousKey, provider, this._previousProviderDisposers, this._updateTexturePrev.bind(this));
28624     };
28625     SliderGLRenderer.prototype.update = function (frame, mode) {
28626         this._updateFrameId(frame.id);
28627         this._updateImagePlanes(frame.state, mode);
28628     };
28629     SliderGLRenderer.prototype.updateCurtain = function (curtain) {
28630         if (this._curtain === curtain) {
28631             return;
28632         }
28633         this._curtain = curtain;
28634         this._updateCurtain();
28635         this._needsRender = true;
28636     };
28637     SliderGLRenderer.prototype.updateTexture = function (image, node) {
28638         var imagePlanes = node.key === this._currentKey ?
28639             this._scene.imagePlanes :
28640             node.key === this._previousKey ?
28641                 this._scene.imagePlanesOld :
28642                 [];
28643         if (imagePlanes.length === 0) {
28644             return;
28645         }
28646         this._needsRender = true;
28647         for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
28648             var plane = imagePlanes_1[_i];
28649             var material = plane.material;
28650             var texture = material.uniforms.projectorTex.value;
28651             texture.image = image;
28652             texture.needsUpdate = true;
28653         }
28654     };
28655     SliderGLRenderer.prototype.updateTextureImage = function (image, node) {
28656         if (this._currentKey !== node.key) {
28657             return;
28658         }
28659         this._needsRender = true;
28660         for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
28661             var plane = _a[_i];
28662             var material = plane.material;
28663             var texture = material.uniforms.projectorTex.value;
28664             texture.image = image;
28665             texture.needsUpdate = true;
28666         }
28667     };
28668     SliderGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
28669         if (!this.disabled) {
28670             renderer.render(this._scene.sceneOld, perspectiveCamera);
28671         }
28672         renderer.render(this._scene.scene, perspectiveCamera);
28673         this._needsRender = false;
28674     };
28675     SliderGLRenderer.prototype.dispose = function () {
28676         this._scene.clear();
28677         for (var key in this._currentProviderDisposers) {
28678             if (!this._currentProviderDisposers.hasOwnProperty(key)) {
28679                 continue;
28680             }
28681             this._currentProviderDisposers[key]();
28682         }
28683         for (var key in this._previousProviderDisposers) {
28684             if (!this._previousProviderDisposers.hasOwnProperty(key)) {
28685                 continue;
28686             }
28687             this._previousProviderDisposers[key]();
28688         }
28689         this._currentProviderDisposers = {};
28690         this._previousProviderDisposers = {};
28691     };
28692     SliderGLRenderer.prototype._getBasicCorners = function (currentAspect, previousAspect) {
28693         var offsetX;
28694         var offsetY;
28695         if (currentAspect > previousAspect) {
28696             offsetX = 0.5;
28697             offsetY = 0.5 * currentAspect / previousAspect;
28698         }
28699         else {
28700             offsetX = 0.5 * previousAspect / currentAspect;
28701             offsetY = 0.5;
28702         }
28703         return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]];
28704     };
28705     SliderGLRenderer.prototype._setDisabled = function (state) {
28706         this._disabled = state.currentNode == null ||
28707             state.previousNode == null ||
28708             (state.currentNode.pano && !state.currentNode.fullPano) ||
28709             (state.previousNode.pano && !state.previousNode.fullPano) ||
28710             (state.currentNode.fullPano && !state.previousNode.fullPano);
28711     };
28712     SliderGLRenderer.prototype._setTextureProvider = function (key, originalKey, provider, providerDisposers, updateTexture) {
28713         var _this = this;
28714         if (key !== originalKey) {
28715             return;
28716         }
28717         var createdSubscription = provider.textureCreated$
28718             .subscribe(updateTexture);
28719         var updatedSubscription = provider.textureUpdated$
28720             .subscribe(function (updated) {
28721             _this._needsRender = true;
28722         });
28723         var dispose = function () {
28724             createdSubscription.unsubscribe();
28725             updatedSubscription.unsubscribe();
28726             provider.dispose();
28727         };
28728         if (key in providerDisposers) {
28729             var disposeProvider = providerDisposers[key];
28730             disposeProvider();
28731             delete providerDisposers[key];
28732         }
28733         providerDisposers[key] = dispose;
28734     };
28735     SliderGLRenderer.prototype._updateCurtain = function () {
28736         for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
28737             var plane = _a[_i];
28738             var shaderMaterial = plane.material;
28739             if (!!shaderMaterial.uniforms.curtain) {
28740                 shaderMaterial.uniforms.curtain.value = this._curtain;
28741             }
28742         }
28743     };
28744     SliderGLRenderer.prototype._updateFrameId = function (frameId) {
28745         this._frameId = frameId;
28746     };
28747     SliderGLRenderer.prototype._updateImagePlanes = function (state, mode) {
28748         var currentChanged = state.currentNode != null && this._currentKey !== state.currentNode.key;
28749         var previousChanged = state.previousNode != null && this._previousKey !== state.previousNode.key;
28750         var modeChanged = this._mode !== mode;
28751         if (!(currentChanged || previousChanged || modeChanged)) {
28752             return;
28753         }
28754         this._setDisabled(state);
28755         this._needsRender = true;
28756         this._mode = mode;
28757         var motionless = state.motionless || mode === Component_1.SliderMode.Stationary || state.currentNode.pano;
28758         if (this.disabled || previousChanged) {
28759             if (this._previousKey in this._previousProviderDisposers) {
28760                 this._previousProviderDisposers[this._previousKey]();
28761                 delete this._previousProviderDisposers[this._previousKey];
28762             }
28763         }
28764         if (this.disabled) {
28765             this._scene.setImagePlanesOld([]);
28766         }
28767         else {
28768             if (previousChanged || modeChanged) {
28769                 var previousNode = state.previousNode;
28770                 this._previousKey = previousNode.key;
28771                 var elements = state.currentTransform.rt.elements;
28772                 var translation = [elements[12], elements[13], elements[14]];
28773                 var currentAspect = state.currentTransform.basicAspect;
28774                 var previousAspect = state.previousTransform.basicAspect;
28775                 var textureScale = currentAspect > previousAspect ?
28776                     [1, previousAspect / currentAspect] :
28777                     [currentAspect / previousAspect, 1];
28778                 var rotation = state.currentNode.rotation;
28779                 var width = state.currentNode.width;
28780                 var height = state.currentNode.height;
28781                 if (previousNode.fullPano) {
28782                     rotation = state.previousNode.rotation;
28783                     translation = this._spatial
28784                         .rotate(this._spatial
28785                         .opticalCenter(state.currentNode.rotation, translation)
28786                         .toArray(), rotation)
28787                         .multiplyScalar(-1)
28788                         .toArray();
28789                     width = state.previousNode.width;
28790                     height = state.previousNode.height;
28791                 }
28792                 var transform = new Geo_1.Transform(state.currentNode.orientation, width, height, state.currentNode.focal, state.currentNode.scale, previousNode.gpano, rotation, translation, previousNode.image, textureScale);
28793                 var mesh = undefined;
28794                 if (previousNode.fullPano) {
28795                     mesh = this._factory.createMesh(previousNode, motionless || state.currentNode.fullPano ? transform : state.previousTransform);
28796                 }
28797                 else {
28798                     if (motionless) {
28799                         var _a = this._getBasicCorners(currentAspect, previousAspect), _b = _a[0], basicX0 = _b[0], basicY0 = _b[1], _c = _a[1], basicX1 = _c[0], basicY1 = _c[1];
28800                         mesh = this._factory.createFlatMesh(state.previousNode, transform, basicX0, basicX1, basicY0, basicY1);
28801                     }
28802                     else {
28803                         mesh = this._factory.createMesh(state.previousNode, state.previousTransform);
28804                     }
28805                 }
28806                 this._scene.setImagePlanesOld([mesh]);
28807             }
28808         }
28809         if (currentChanged || modeChanged) {
28810             if (this._currentKey in this._currentProviderDisposers) {
28811                 this._currentProviderDisposers[this._currentKey]();
28812                 delete this._currentProviderDisposers[this._currentKey];
28813             }
28814             this._currentKey = state.currentNode.key;
28815             var imagePlanes = [];
28816             if (state.currentNode.fullPano) {
28817                 imagePlanes.push(this._factory.createCurtainMesh(state.currentNode, state.currentTransform));
28818             }
28819             else if (state.currentNode.pano && !state.currentNode.fullPano) {
28820                 imagePlanes.push(this._factory.createMesh(state.currentNode, state.currentTransform));
28821             }
28822             else {
28823                 if (motionless) {
28824                     imagePlanes.push(this._factory.createDistortedCurtainMesh(state.currentNode, state.currentTransform));
28825                 }
28826                 else {
28827                     imagePlanes.push(this._factory.createCurtainMesh(state.currentNode, state.currentTransform));
28828                 }
28829             }
28830             this._scene.setImagePlanes(imagePlanes);
28831             this._updateCurtain();
28832         }
28833     };
28834     SliderGLRenderer.prototype._updateTexture = function (texture) {
28835         this._needsRender = true;
28836         for (var _i = 0, _a = this._scene.imagePlanes; _i < _a.length; _i++) {
28837             var plane = _a[_i];
28838             var material = plane.material;
28839             var oldTexture = material.uniforms.projectorTex.value;
28840             material.uniforms.projectorTex.value = null;
28841             oldTexture.dispose();
28842             material.uniforms.projectorTex.value = texture;
28843         }
28844     };
28845     SliderGLRenderer.prototype._updateTexturePrev = function (texture) {
28846         this._needsRender = true;
28847         for (var _i = 0, _a = this._scene.imagePlanesOld; _i < _a.length; _i++) {
28848             var plane = _a[_i];
28849             var material = plane.material;
28850             var oldTexture = material.uniforms.projectorTex.value;
28851             material.uniforms.projectorTex.value = null;
28852             oldTexture.dispose();
28853             material.uniforms.projectorTex.value = texture;
28854         }
28855     };
28856     return SliderGLRenderer;
28857 }());
28858 exports.SliderGLRenderer = SliderGLRenderer;
28859 exports.default = SliderGLRenderer;
28860
28861
28862 },{"../../Component":274,"../../Geo":277}],339:[function(require,module,exports){
28863 "use strict";
28864 Object.defineProperty(exports, "__esModule", { value: true });
28865 var geohash = require("latlon-geohash");
28866 var rxjs_1 = require("rxjs");
28867 var operators_1 = require("rxjs/operators");
28868 var Error_1 = require("../../Error");
28869 var Utils_1 = require("../../Utils");
28870 var SpatialDataCache = /** @class */ (function () {
28871     function SpatialDataCache(graphService) {
28872         this._graphService = graphService;
28873         this._tiles = {};
28874         this._cacheRequests = {};
28875         this._reconstructions = {};
28876         this._cachingReconstructions$ = {};
28877         this._cachingTiles$ = {};
28878     }
28879     SpatialDataCache.prototype.cacheReconstructions$ = function (hash) {
28880         var _this = this;
28881         if (!this.hasTile(hash)) {
28882             throw new Error("Cannot cache reconstructions of a non-existing tile.");
28883         }
28884         if (this.hasReconstructions(hash)) {
28885             throw new Error("Cannot cache reconstructions that already exists.");
28886         }
28887         if (this.isCachingReconstructions(hash)) {
28888             return this._cachingReconstructions$[hash];
28889         }
28890         var tile = [];
28891         if (hash in this._reconstructions) {
28892             var reconstructionKeys = this.getReconstructions(hash)
28893                 .map(function (reconstruction) {
28894                 return reconstruction.data.key;
28895             });
28896             for (var _i = 0, _a = this.getTile(hash); _i < _a.length; _i++) {
28897                 var node = _a[_i];
28898                 if (reconstructionKeys.indexOf(node.key) === -1) {
28899                     tile.push(node);
28900                 }
28901             }
28902         }
28903         else {
28904             tile.push.apply(tile, this.getTile(hash));
28905             this._reconstructions[hash] = [];
28906         }
28907         this._cacheRequests[hash] = [];
28908         this._cachingReconstructions$[hash] = rxjs_1.from(tile).pipe(operators_1.mergeMap(function (nodeData) {
28909             return !_this._cacheRequests[hash] ?
28910                 rxjs_1.empty() :
28911                 rxjs_1.zip(rxjs_1.of(nodeData), _this._getAtomicReconstruction(nodeData.key, _this._cacheRequests[hash]))
28912                     .pipe(operators_1.catchError(function (error) {
28913                     if (error instanceof Error_1.AbortMapillaryError) {
28914                         return rxjs_1.empty();
28915                     }
28916                     console.error(error);
28917                     return rxjs_1.of([nodeData, null]);
28918                 }));
28919         }, 6), operators_1.map(function (_a) {
28920             var nodeData = _a[0], reconstruction = _a[1];
28921             return { data: nodeData, reconstruction: reconstruction };
28922         }), operators_1.filter(function () {
28923             return hash in _this._reconstructions;
28924         }), operators_1.tap(function (data) {
28925             _this._reconstructions[hash].push(data);
28926         }), operators_1.filter(function (data) {
28927             return !!data.reconstruction;
28928         }), operators_1.finalize(function () {
28929             if (hash in _this._cachingReconstructions$) {
28930                 delete _this._cachingReconstructions$[hash];
28931             }
28932             if (hash in _this._cacheRequests) {
28933                 delete _this._cacheRequests[hash];
28934             }
28935         }), operators_1.publish(), operators_1.refCount());
28936         return this._cachingReconstructions$[hash];
28937     };
28938     SpatialDataCache.prototype.cacheTile$ = function (hash) {
28939         var _this = this;
28940         if (hash.length !== 8) {
28941             throw new Error("Hash needs to be level 8.");
28942         }
28943         if (this.hasTile(hash)) {
28944             throw new Error("Cannot cache tile that already exists.");
28945         }
28946         if (this.hasTile(hash)) {
28947             return this._cachingTiles$[hash];
28948         }
28949         var bounds = geohash.bounds(hash);
28950         var sw = { lat: bounds.sw.lat, lon: bounds.sw.lon };
28951         var ne = { lat: bounds.ne.lat, lon: bounds.ne.lon };
28952         this._tiles[hash] = [];
28953         this._cachingTiles$[hash] = this._graphService.cacheBoundingBox$(sw, ne).pipe(operators_1.catchError(function (error) {
28954             console.error(error);
28955             delete _this._tiles[hash];
28956             return rxjs_1.empty();
28957         }), operators_1.map(function (nodes) {
28958             return nodes
28959                 .map(function (n) {
28960                 return _this._createNodeData(n);
28961             });
28962         }), operators_1.filter(function () {
28963             return hash in _this._tiles;
28964         }), operators_1.tap(function (nodeData) {
28965             var _a;
28966             (_a = _this._tiles[hash]).push.apply(_a, nodeData);
28967             delete _this._cachingTiles$[hash];
28968         }), operators_1.finalize(function () {
28969             if (hash in _this._cachingTiles$) {
28970                 delete _this._cachingTiles$[hash];
28971             }
28972         }), operators_1.publish(), operators_1.refCount());
28973         return this._cachingTiles$[hash];
28974     };
28975     SpatialDataCache.prototype.isCachingReconstructions = function (hash) {
28976         return hash in this._cachingReconstructions$;
28977     };
28978     SpatialDataCache.prototype.isCachingTile = function (hash) {
28979         return hash in this._cachingTiles$;
28980     };
28981     SpatialDataCache.prototype.hasReconstructions = function (hash) {
28982         return !(hash in this._cachingReconstructions$) &&
28983             hash in this._reconstructions &&
28984             this._reconstructions[hash].length === this._tiles[hash].length;
28985     };
28986     SpatialDataCache.prototype.hasTile = function (hash) {
28987         return !(hash in this._cachingTiles$) && hash in this._tiles;
28988     };
28989     SpatialDataCache.prototype.getReconstructions = function (hash) {
28990         return hash in this._reconstructions ?
28991             this._reconstructions[hash]
28992                 .filter(function (data) {
28993                 return !!data.reconstruction;
28994             }) :
28995             [];
28996     };
28997     SpatialDataCache.prototype.getTile = function (hash) {
28998         return hash in this._tiles ? this._tiles[hash] : [];
28999     };
29000     SpatialDataCache.prototype.uncache = function (keepHashes) {
29001         for (var _i = 0, _a = Object.keys(this._cacheRequests); _i < _a.length; _i++) {
29002             var hash = _a[_i];
29003             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
29004                 continue;
29005             }
29006             for (var _b = 0, _c = this._cacheRequests[hash]; _b < _c.length; _b++) {
29007                 var request = _c[_b];
29008                 request.abort();
29009             }
29010             delete this._cacheRequests[hash];
29011         }
29012         for (var _d = 0, _e = Object.keys(this._reconstructions); _d < _e.length; _d++) {
29013             var hash = _e[_d];
29014             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
29015                 continue;
29016             }
29017             delete this._reconstructions[hash];
29018         }
29019         for (var _f = 0, _g = Object.keys(this._tiles); _f < _g.length; _f++) {
29020             var hash = _g[_f];
29021             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
29022                 continue;
29023             }
29024             delete this._tiles[hash];
29025         }
29026     };
29027     SpatialDataCache.prototype._createNodeData = function (node) {
29028         return {
29029             alt: node.alt,
29030             focal: node.focal,
29031             gpano: node.gpano,
29032             height: node.height,
29033             k1: node.ck1,
29034             k2: node.ck2,
29035             key: node.key,
29036             lat: node.latLon.lat,
29037             lon: node.latLon.lon,
29038             mergeCC: node.mergeCC,
29039             orientation: node.orientation,
29040             originalLat: node.originalLatLon.lat,
29041             originalLon: node.originalLatLon.lon,
29042             rotation: [node.rotation[0], node.rotation[1], node.rotation[2]],
29043             scale: node.scale,
29044             width: node.width,
29045         };
29046     };
29047     SpatialDataCache.prototype._getAtomicReconstruction = function (key, requests) {
29048         return rxjs_1.Observable.create(function (subscriber) {
29049             var xmlHTTP = new XMLHttpRequest();
29050             xmlHTTP.open("GET", Utils_1.Urls.atomicReconstruction(key), true);
29051             xmlHTTP.responseType = "json";
29052             xmlHTTP.timeout = 15000;
29053             xmlHTTP.onload = function () {
29054                 if (!xmlHTTP.response) {
29055                     subscriber.error(new Error("Atomic reconstruction does not exist (" + key + ")"));
29056                 }
29057                 else {
29058                     subscriber.next(xmlHTTP.response);
29059                     subscriber.complete();
29060                 }
29061             };
29062             xmlHTTP.onerror = function () {
29063                 subscriber.error(new Error("Failed to get atomic reconstruction (" + key + ")"));
29064             };
29065             xmlHTTP.ontimeout = function () {
29066                 subscriber.error(new Error("Atomic reconstruction request timed out (" + key + ")"));
29067             };
29068             xmlHTTP.onabort = function () {
29069                 subscriber.error(new Error_1.AbortMapillaryError("Atomic reconstruction request was aborted (" + key + ")"));
29070             };
29071             requests.push(xmlHTTP);
29072             xmlHTTP.send(null);
29073         });
29074     };
29075     return SpatialDataCache;
29076 }());
29077 exports.SpatialDataCache = SpatialDataCache;
29078 exports.default = SpatialDataCache;
29079
29080 },{"../../Error":276,"../../Utils":284,"latlon-geohash":21,"rxjs":26,"rxjs/operators":224}],340:[function(require,module,exports){
29081 "use strict";
29082 var __extends = (this && this.__extends) || (function () {
29083     var extendStatics = function (d, b) {
29084         extendStatics = Object.setPrototypeOf ||
29085             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29086             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29087         return extendStatics(d, b);
29088     }
29089     return function (d, b) {
29090         extendStatics(d, b);
29091         function __() { this.constructor = d; }
29092         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29093     };
29094 })();
29095 Object.defineProperty(exports, "__esModule", { value: true });
29096 var geohash = require("latlon-geohash");
29097 var rxjs_1 = require("rxjs");
29098 var operators_1 = require("rxjs/operators");
29099 var Component_1 = require("../../Component");
29100 var Geo_1 = require("../../Geo");
29101 var Render_1 = require("../../Render");
29102 var PlayService_1 = require("../../viewer/PlayService");
29103 var State_1 = require("../../state/State");
29104 var SpatialDataComponent = /** @class */ (function (_super) {
29105     __extends(SpatialDataComponent, _super);
29106     function SpatialDataComponent(name, container, navigator) {
29107         var _this = _super.call(this, name, container, navigator) || this;
29108         _this._cache = new Component_1.SpatialDataCache(navigator.graphService);
29109         _this._scene = new Component_1.SpatialDataScene(_this._getDefaultConfiguration());
29110         _this._viewportCoords = new Geo_1.ViewportCoords();
29111         _this._geoCoords = new Geo_1.GeoCoords();
29112         return _this;
29113     }
29114     SpatialDataComponent.prototype._activate = function () {
29115         var _this = this;
29116         this._earthControlsSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
29117             return configuration.earthControls;
29118         }), operators_1.distinctUntilChanged(), operators_1.withLatestFrom(this._navigator.stateService.state$))
29119             .subscribe(function (_a) {
29120             var earth = _a[0], state = _a[1];
29121             if (earth && state !== State_1.default.Earth) {
29122                 _this._navigator.stateService.earth();
29123             }
29124             else if (!earth && state === State_1.default.Earth) {
29125                 _this._navigator.stateService.traverse();
29126             }
29127         });
29128         var direction$ = this._container.renderService.bearing$.pipe(operators_1.map(function (bearing) {
29129             var direction = "";
29130             if (bearing > 292.5 || bearing <= 67.5) {
29131                 direction += "n";
29132             }
29133             if (bearing > 112.5 && bearing <= 247.5) {
29134                 direction += "s";
29135             }
29136             if (bearing > 22.5 && bearing <= 157.5) {
29137                 direction += "e";
29138             }
29139             if (bearing > 202.5 && bearing <= 337.5) {
29140                 direction += "w";
29141             }
29142             return direction;
29143         }), operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
29144         var hash$ = this._navigator.stateService.reference$.pipe(operators_1.tap(function () {
29145             _this._scene.uncache();
29146         }), operators_1.switchMap(function () {
29147             return _this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) {
29148                 return geohash.encode(node.latLon.lat, node.latLon.lon, 8);
29149             }), operators_1.distinctUntilChanged());
29150         }), operators_1.publishReplay(1), operators_1.refCount());
29151         var sequencePlay$ = rxjs_1.combineLatest(this._navigator.playService.playing$, this._navigator.playService.speed$).pipe(operators_1.map(function (_a) {
29152             var playing = _a[0], speed = _a[1];
29153             return playing && speed > PlayService_1.default.sequenceSpeed;
29154         }), operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
29155         this._addSubscription = rxjs_1.combineLatest(this._navigator.stateService.state$.pipe(operators_1.map(function (state) {
29156             return state === State_1.default.Earth;
29157         }), operators_1.distinctUntilChanged()), hash$, sequencePlay$, direction$).pipe(operators_1.distinctUntilChanged(function (_a, _b) {
29158             var e1 = _a[0], h1 = _a[1], s1 = _a[2], d1 = _a[3];
29159             var e2 = _b[0], h2 = _b[1], s2 = _b[2], d2 = _b[3];
29160             if (e1 !== e2) {
29161                 return false;
29162             }
29163             if (e1) {
29164                 return h1 === h2 && s1 === s2;
29165             }
29166             return h1 === h2 && s1 === s2 && d1 === d2;
29167         }), operators_1.concatMap(function (_a) {
29168             var earth = _a[0], hash = _a[1], sequencePlay = _a[2], direction = _a[3];
29169             if (earth) {
29170                 return sequencePlay ?
29171                     rxjs_1.of([hash]) :
29172                     rxjs_1.of(_this._adjacentComponent(hash, 4));
29173             }
29174             return sequencePlay ?
29175                 rxjs_1.of([hash, geohash.neighbours(hash)[direction]]) :
29176                 rxjs_1.of(_this._computeTiles(hash, direction));
29177         }), operators_1.switchMap(function (hashes) {
29178             return rxjs_1.from(hashes).pipe(operators_1.mergeMap(function (h) {
29179                 var tile$;
29180                 if (_this._cache.hasTile(h)) {
29181                     tile$ = rxjs_1.of(_this._cache.getTile(h));
29182                 }
29183                 else if (_this._cache.isCachingTile(h)) {
29184                     tile$ = _this._cache.cacheTile$(h).pipe(operators_1.last(null, {}), operators_1.switchMap(function () {
29185                         return rxjs_1.of(_this._cache.getTile(h));
29186                     }));
29187                 }
29188                 else {
29189                     tile$ = _this._cache.cacheTile$(h);
29190                 }
29191                 return rxjs_1.combineLatest(rxjs_1.of(h), tile$);
29192             }, 1), operators_1.map(function (_a) {
29193                 var hash = _a[0];
29194                 return hash;
29195             }));
29196         }), operators_1.concatMap(function (hash) {
29197             var reconstructions$;
29198             if (_this._cache.hasReconstructions(hash)) {
29199                 reconstructions$ = rxjs_1.from(_this._cache.getReconstructions(hash));
29200             }
29201             else if (_this._cache.isCachingReconstructions(hash)) {
29202                 reconstructions$ = _this._cache.cacheReconstructions$(hash).pipe(operators_1.last(null, {}), operators_1.switchMap(function () {
29203                     return rxjs_1.from(_this._cache.getReconstructions(hash));
29204                 }));
29205             }
29206             else if (_this._cache.hasTile(hash)) {
29207                 reconstructions$ = _this._cache.cacheReconstructions$(hash);
29208             }
29209             else {
29210                 reconstructions$ = rxjs_1.empty();
29211             }
29212             return rxjs_1.combineLatest(rxjs_1.of(hash), reconstructions$);
29213         }), operators_1.withLatestFrom(this._navigator.stateService.reference$), operators_1.tap(function (_a) {
29214             var hash = _a[0][0], reference = _a[1];
29215             if (_this._scene.hasTile(hash)) {
29216                 return;
29217             }
29218             _this._scene.addTile(_this._computeTileBBox(hash, reference), hash);
29219         }), operators_1.filter(function (_a) {
29220             var _b = _a[0], hash = _b[0], data = _b[1];
29221             return !_this._scene.hasReconstruction(data.reconstruction.main_shot, hash);
29222         }), operators_1.map(function (_a) {
29223             var _b = _a[0], hash = _b[0], data = _b[1], reference = _a[1];
29224             return [
29225                 data,
29226                 _this._createTransform(data.data, reference),
29227                 _this._computeOriginalPosition(data.data, reference),
29228                 hash
29229             ];
29230         }))
29231             .subscribe(function (_a) {
29232             var data = _a[0], transform = _a[1], position = _a[2], hash = _a[3];
29233             _this._scene.addReconstruction(data.reconstruction, transform, position, !!data.data.mergeCC ? data.data.mergeCC.toString() : "", hash);
29234         });
29235         this._cameraVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
29236             return configuration.camerasVisible;
29237         }), operators_1.distinctUntilChanged())
29238             .subscribe(function (visible) {
29239             _this._scene.setCameraVisibility(visible);
29240         });
29241         this._pointVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
29242             return configuration.pointsVisible;
29243         }), operators_1.distinctUntilChanged())
29244             .subscribe(function (visible) {
29245             _this._scene.setPointVisibility(visible);
29246         });
29247         this._positionVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
29248             return configuration.positionsVisible;
29249         }), operators_1.distinctUntilChanged())
29250             .subscribe(function (visible) {
29251             _this._scene.setPositionVisibility(visible);
29252         });
29253         this._tileVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
29254             return configuration.tilesVisible;
29255         }), operators_1.distinctUntilChanged())
29256             .subscribe(function (visible) {
29257             _this._scene.setTileVisibility(visible);
29258         });
29259         this._visualizeConnectedComponentSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
29260             return configuration.connectedComponents;
29261         }), operators_1.distinctUntilChanged())
29262             .subscribe(function (visualize) {
29263             _this._scene.setConnectedComponentVisualization(visualize);
29264         });
29265         this._uncacheSubscription = hash$
29266             .subscribe(function (hash) {
29267             var keepHashes = _this._adjacentComponent(hash, 4);
29268             _this._scene.uncache(keepHashes);
29269             _this._cache.uncache(keepHashes);
29270         });
29271         this._moveSubscription = this._navigator.playService.playing$.pipe(operators_1.switchMap(function (playing) {
29272             return playing ?
29273                 rxjs_1.empty() :
29274                 _this._container.mouseService.dblClick$;
29275         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$), operators_1.switchMap(function (_a) {
29276             var event = _a[0], render = _a[1];
29277             var element = _this._container.element;
29278             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
29279             var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
29280             var key = _this._scene.intersectObjects(viewport, render.perspective);
29281             return !!key ?
29282                 _this._navigator.moveToKey$(key).pipe(operators_1.catchError(function () {
29283                     return rxjs_1.empty();
29284                 })) :
29285                 rxjs_1.empty();
29286         }))
29287             .subscribe();
29288         this._renderSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
29289             var scene = _this._scene;
29290             return {
29291                 name: _this._name,
29292                 render: {
29293                     frameId: frame.id,
29294                     needsRender: scene.needsRender,
29295                     render: scene.render.bind(scene),
29296                     stage: Render_1.GLRenderStage.Foreground,
29297                 },
29298             };
29299         }))
29300             .subscribe(this._container.glRenderer.render$);
29301     };
29302     SpatialDataComponent.prototype._deactivate = function () {
29303         var _this = this;
29304         this._cache.uncache();
29305         this._scene.uncache();
29306         this._addSubscription.unsubscribe();
29307         this._cameraVisibilitySubscription.unsubscribe();
29308         this._earthControlsSubscription.unsubscribe();
29309         this._moveSubscription.unsubscribe();
29310         this._pointVisibilitySubscription.unsubscribe();
29311         this._positionVisibilitySubscription.unsubscribe();
29312         this._renderSubscription.unsubscribe();
29313         this._tileVisibilitySubscription.unsubscribe();
29314         this._uncacheSubscription.unsubscribe();
29315         this._visualizeConnectedComponentSubscription.unsubscribe();
29316         this._navigator.stateService.state$.pipe(operators_1.first())
29317             .subscribe(function (state) {
29318             if (state === State_1.default.Earth) {
29319                 _this._navigator.stateService.traverse();
29320             }
29321         });
29322     };
29323     SpatialDataComponent.prototype._getDefaultConfiguration = function () {
29324         return { camerasVisible: false, pointsVisible: true, positionsVisible: false, tilesVisible: false };
29325     };
29326     SpatialDataComponent.prototype._adjacentComponent = function (hash, depth) {
29327         var hashSet = new Set();
29328         hashSet.add(hash);
29329         this._adjacentComponentRecursive(hashSet, [hash], 0, depth);
29330         return this._setToArray(hashSet);
29331     };
29332     SpatialDataComponent.prototype._adjacentComponentRecursive = function (hashSet, currentHashes, currentDepth, maxDepth) {
29333         if (currentDepth === maxDepth) {
29334             return;
29335         }
29336         var neighbours = [];
29337         for (var _i = 0, currentHashes_1 = currentHashes; _i < currentHashes_1.length; _i++) {
29338             var hash = currentHashes_1[_i];
29339             var hashNeighbours = geohash.neighbours(hash);
29340             for (var direction in hashNeighbours) {
29341                 if (!hashNeighbours.hasOwnProperty(direction)) {
29342                     continue;
29343                 }
29344                 neighbours.push(hashNeighbours[direction]);
29345             }
29346         }
29347         var newHashes = [];
29348         for (var _a = 0, neighbours_1 = neighbours; _a < neighbours_1.length; _a++) {
29349             var neighbour = neighbours_1[_a];
29350             if (!hashSet.has(neighbour)) {
29351                 hashSet.add(neighbour);
29352                 newHashes.push(neighbour);
29353             }
29354         }
29355         this._adjacentComponentRecursive(hashSet, newHashes, currentDepth + 1, maxDepth);
29356     };
29357     SpatialDataComponent.prototype._computeOriginalPosition = function (data, reference) {
29358         return this._geoCoords.geodeticToEnu(data.originalLat, data.originalLon, data.alt, reference.lat, reference.lon, reference.alt);
29359     };
29360     SpatialDataComponent.prototype._computeTileBBox = function (hash, reference) {
29361         var bounds = geohash.bounds(hash);
29362         var sw = this._geoCoords.geodeticToEnu(bounds.sw.lat, bounds.sw.lon, 0, reference.lat, reference.lon, reference.alt);
29363         var ne = this._geoCoords.geodeticToEnu(bounds.ne.lat, bounds.ne.lon, 0, reference.lat, reference.lon, reference.alt);
29364         return [sw, ne];
29365     };
29366     SpatialDataComponent.prototype._createTransform = function (data, reference) {
29367         var translation = Geo_1.Geo.computeTranslation({ alt: data.alt, lat: data.lat, lon: data.lon }, data.rotation, reference);
29368         var transform = new Geo_1.Transform(data.orientation, data.width, data.height, data.focal, data.scale, data.gpano, data.rotation, translation, undefined, undefined, data.k1, data.k2);
29369         return transform;
29370     };
29371     SpatialDataComponent.prototype._computeTiles = function (hash, direction) {
29372         var hashSet = new Set();
29373         var directions = ["n", "ne", "e", "se", "s", "sw", "w", "nw"];
29374         this._computeTilesRecursive(hashSet, hash, direction, directions, 0, 2);
29375         return this._setToArray(hashSet);
29376     };
29377     SpatialDataComponent.prototype._computeTilesRecursive = function (hashSet, currentHash, direction, directions, currentDepth, maxDepth) {
29378         hashSet.add(currentHash);
29379         if (currentDepth === maxDepth) {
29380             return;
29381         }
29382         var neighbours = geohash.neighbours(currentHash);
29383         var directionIndex = directions.indexOf(direction);
29384         var length = directions.length;
29385         var directionNeighbours = [
29386             neighbours[directions[this._modulo((directionIndex - 1), length)]],
29387             neighbours[direction],
29388             neighbours[directions[this._modulo((directionIndex + 1), length)]],
29389         ];
29390         for (var _i = 0, directionNeighbours_1 = directionNeighbours; _i < directionNeighbours_1.length; _i++) {
29391             var directionNeighbour = directionNeighbours_1[_i];
29392             this._computeTilesRecursive(hashSet, directionNeighbour, direction, directions, currentDepth + 1, maxDepth);
29393         }
29394     };
29395     SpatialDataComponent.prototype._modulo = function (a, n) {
29396         return ((a % n) + n) % n;
29397     };
29398     SpatialDataComponent.prototype._setToArray = function (s) {
29399         var a = [];
29400         s.forEach(function (value) {
29401             a.push(value);
29402         });
29403         return a;
29404     };
29405     SpatialDataComponent.componentName = "spatialData";
29406     return SpatialDataComponent;
29407 }(Component_1.Component));
29408 exports.SpatialDataComponent = SpatialDataComponent;
29409 Component_1.ComponentService.register(SpatialDataComponent);
29410 exports.default = SpatialDataComponent;
29411
29412 },{"../../Component":274,"../../Geo":277,"../../Render":280,"../../state/State":411,"../../viewer/PlayService":440,"latlon-geohash":21,"rxjs":26,"rxjs/operators":224}],341:[function(require,module,exports){
29413 "use strict";
29414 Object.defineProperty(exports, "__esModule", { value: true });
29415 var THREE = require("three");
29416 var SpatialDataScene = /** @class */ (function () {
29417     function SpatialDataScene(configuration, scene, raycaster) {
29418         this._scene = !!scene ? scene : new THREE.Scene();
29419         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster(undefined, undefined, 0.8);
29420         this._connectedComponentColors = {};
29421         this._needsRender = false;
29422         this._interactiveObjects = [];
29423         this._reconstructions = {};
29424         this._tiles = {};
29425         this._camerasVisible = configuration.camerasVisible;
29426         this._pointsVisible = configuration.pointsVisible;
29427         this._positionsVisible = configuration.positionsVisible;
29428         this._tilesVisible = configuration.tilesVisible;
29429         this._visualizeConnectedComponents = configuration.connectedComponents;
29430     }
29431     Object.defineProperty(SpatialDataScene.prototype, "needsRender", {
29432         get: function () {
29433             return this._needsRender;
29434         },
29435         enumerable: true,
29436         configurable: true
29437     });
29438     SpatialDataScene.prototype.addReconstruction = function (reconstruction, transform, originalPosition, connectedComponent, hash) {
29439         if (!(hash in this._reconstructions)) {
29440             this._reconstructions[hash] = {
29441                 cameraKeys: {},
29442                 cameras: new THREE.Object3D(),
29443                 connectedComponents: {},
29444                 keys: [],
29445                 points: new THREE.Object3D(),
29446                 positions: new THREE.Object3D(),
29447             };
29448             this._reconstructions[hash].cameras.visible = this._camerasVisible;
29449             this._reconstructions[hash].points.visible = this._pointsVisible;
29450             this._reconstructions[hash].positions.visible = this._positionsVisible;
29451             this._scene.add(this._reconstructions[hash].cameras, this._reconstructions[hash].points, this._reconstructions[hash].positions);
29452         }
29453         if (!(connectedComponent in this._reconstructions[hash].connectedComponents)) {
29454             this._reconstructions[hash].connectedComponents[connectedComponent] = [];
29455         }
29456         if (transform.hasValidScale) {
29457             this._reconstructions[hash].points.add(this._createPoints(reconstruction, transform));
29458         }
29459         var camera = this._createCamera(transform);
29460         this._reconstructions[hash].cameras.add(camera);
29461         for (var _i = 0, _a = camera.children; _i < _a.length; _i++) {
29462             var child = _a[_i];
29463             this._reconstructions[hash].cameraKeys[child.uuid] = reconstruction.main_shot;
29464             this._interactiveObjects.push(child);
29465         }
29466         this._reconstructions[hash].connectedComponents[connectedComponent].push(camera);
29467         var color = this._getColor(connectedComponent, this._visualizeConnectedComponents);
29468         this._setCameraColor(color, camera);
29469         this._reconstructions[hash].positions.add(this._createPosition(transform, originalPosition));
29470         this._reconstructions[hash].keys.push(reconstruction.main_shot);
29471         this._needsRender = true;
29472     };
29473     SpatialDataScene.prototype.addTile = function (tileBBox, hash) {
29474         if (this.hasTile(hash)) {
29475             return;
29476         }
29477         var sw = tileBBox[0];
29478         var ne = tileBBox[1];
29479         var geometry = new THREE.Geometry();
29480         geometry.vertices.push(new THREE.Vector3().fromArray(sw), new THREE.Vector3(sw[0], ne[1], (sw[2] + ne[2]) / 2), new THREE.Vector3().fromArray(ne), new THREE.Vector3(ne[0], sw[1], (sw[2] + ne[2]) / 2), new THREE.Vector3().fromArray(sw));
29481         var tile = new THREE.Line(geometry, new THREE.LineBasicMaterial());
29482         this._tiles[hash] = new THREE.Object3D();
29483         this._tiles[hash].visible = this._tilesVisible;
29484         this._tiles[hash].add(tile);
29485         this._scene.add(this._tiles[hash]);
29486         this._needsRender = true;
29487     };
29488     SpatialDataScene.prototype.uncache = function (keepHashes) {
29489         for (var _i = 0, _a = Object.keys(this._reconstructions); _i < _a.length; _i++) {
29490             var hash = _a[_i];
29491             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
29492                 continue;
29493             }
29494             this._disposeReconstruction(hash);
29495         }
29496         for (var _b = 0, _c = Object.keys(this._tiles); _b < _c.length; _b++) {
29497             var hash = _c[_b];
29498             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
29499                 continue;
29500             }
29501             this._disposeTile(hash);
29502         }
29503         this._needsRender = true;
29504     };
29505     SpatialDataScene.prototype.hasReconstruction = function (key, hash) {
29506         return hash in this._reconstructions && this._reconstructions[hash].keys.indexOf(key) !== -1;
29507     };
29508     SpatialDataScene.prototype.hasTile = function (hash) {
29509         return hash in this._tiles;
29510     };
29511     SpatialDataScene.prototype.intersectObjects = function (_a, camera) {
29512         var viewportX = _a[0], viewportY = _a[1];
29513         if (!this._camerasVisible) {
29514             return null;
29515         }
29516         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
29517         var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
29518         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
29519             var intersect = intersects_1[_i];
29520             for (var hash in this._reconstructions) {
29521                 if (!this._reconstructions.hasOwnProperty(hash)) {
29522                     continue;
29523                 }
29524                 if (intersect.object.uuid in this._reconstructions[hash].cameraKeys) {
29525                     return this._reconstructions[hash].cameraKeys[intersect.object.uuid];
29526                 }
29527             }
29528         }
29529         return null;
29530     };
29531     SpatialDataScene.prototype.setCameraVisibility = function (visible) {
29532         if (visible === this._camerasVisible) {
29533             return;
29534         }
29535         for (var hash in this._reconstructions) {
29536             if (!this._reconstructions.hasOwnProperty(hash)) {
29537                 continue;
29538             }
29539             this._reconstructions[hash].cameras.visible = visible;
29540         }
29541         this._camerasVisible = visible;
29542         this._needsRender = true;
29543     };
29544     SpatialDataScene.prototype.setPointVisibility = function (visible) {
29545         if (visible === this._pointsVisible) {
29546             return;
29547         }
29548         for (var hash in this._reconstructions) {
29549             if (!this._reconstructions.hasOwnProperty(hash)) {
29550                 continue;
29551             }
29552             this._reconstructions[hash].points.visible = visible;
29553         }
29554         this._pointsVisible = visible;
29555         this._needsRender = true;
29556     };
29557     SpatialDataScene.prototype.setPositionVisibility = function (visible) {
29558         if (visible === this._positionsVisible) {
29559             return;
29560         }
29561         for (var hash in this._reconstructions) {
29562             if (!this._reconstructions.hasOwnProperty(hash)) {
29563                 continue;
29564             }
29565             this._reconstructions[hash].positions.visible = visible;
29566         }
29567         this._positionsVisible = visible;
29568         this._needsRender = true;
29569     };
29570     SpatialDataScene.prototype.setTileVisibility = function (visible) {
29571         if (visible === this._tilesVisible) {
29572             return;
29573         }
29574         for (var hash in this._tiles) {
29575             if (!this._tiles.hasOwnProperty(hash)) {
29576                 continue;
29577             }
29578             this._tiles[hash].visible = visible;
29579         }
29580         this._tilesVisible = visible;
29581         this._needsRender = true;
29582     };
29583     SpatialDataScene.prototype.setConnectedComponentVisualization = function (visualize) {
29584         if (visualize === this._visualizeConnectedComponents) {
29585             return;
29586         }
29587         for (var hash in this._reconstructions) {
29588             if (!this._reconstructions.hasOwnProperty(hash)) {
29589                 continue;
29590             }
29591             var connectedComponents = this._reconstructions[hash].connectedComponents;
29592             for (var connectedComponent in connectedComponents) {
29593                 if (!connectedComponents.hasOwnProperty(connectedComponent)) {
29594                     continue;
29595                 }
29596                 var color = this._getColor(connectedComponent, visualize);
29597                 for (var _i = 0, _a = connectedComponents[connectedComponent]; _i < _a.length; _i++) {
29598                     var camera = _a[_i];
29599                     this._setCameraColor(color, camera);
29600                 }
29601             }
29602         }
29603         this._visualizeConnectedComponents = visualize;
29604         this._needsRender = true;
29605     };
29606     SpatialDataScene.prototype.render = function (perspectiveCamera, renderer) {
29607         renderer.render(this._scene, perspectiveCamera);
29608         this._needsRender = false;
29609     };
29610     SpatialDataScene.prototype._arrayToFloatArray = function (a, columns) {
29611         var n = a.length;
29612         var f = new Float32Array(n * columns);
29613         for (var i = 0; i < n; i++) {
29614             var item = a[i];
29615             var index = 3 * i;
29616             f[index + 0] = item[0];
29617             f[index + 1] = item[1];
29618             f[index + 2] = item[2];
29619         }
29620         return f;
29621     };
29622     SpatialDataScene.prototype._createAxis = function (transform) {
29623         var north = transform.unprojectBasic([0.5, 0], 0.22);
29624         var south = transform.unprojectBasic([0.5, 1], 0.16);
29625         var axis = new THREE.BufferGeometry();
29626         axis.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray([north, south], 3), 3));
29627         return new THREE.Line(axis, new THREE.LineBasicMaterial());
29628     };
29629     SpatialDataScene.prototype._createCamera = function (transform) {
29630         return !!transform.gpano ?
29631             this._createPanoCamera(transform) :
29632             this._createPrespectiveCamera(transform);
29633     };
29634     SpatialDataScene.prototype._createDiagonals = function (transform, depth) {
29635         var origin = transform.unprojectBasic([0, 0], 0, true);
29636         var topLeft = transform.unprojectBasic([0, 0], depth, true);
29637         var topRight = transform.unprojectBasic([1, 0], depth, true);
29638         var bottomRight = transform.unprojectBasic([1, 1], depth, true);
29639         var bottomLeft = transform.unprojectBasic([0, 1], depth, true);
29640         var vertices = [
29641             origin, topLeft,
29642             origin, topRight,
29643             origin, bottomRight,
29644             origin, bottomLeft,
29645         ];
29646         var diagonals = new THREE.BufferGeometry();
29647         diagonals.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray(vertices, 3), 3));
29648         return new THREE.LineSegments(diagonals, new THREE.LineBasicMaterial());
29649     };
29650     SpatialDataScene.prototype._createFrame = function (transform, depth) {
29651         var vertices2d = [];
29652         vertices2d.push.apply(vertices2d, this._subsample([0, 1], [0, 0], 20));
29653         vertices2d.push.apply(vertices2d, this._subsample([0, 0], [1, 0], 20));
29654         vertices2d.push.apply(vertices2d, this._subsample([1, 0], [1, 1], 20));
29655         var vertices3d = vertices2d
29656             .map(function (basic) {
29657             return transform.unprojectBasic(basic, depth, true);
29658         });
29659         var frame = new THREE.BufferGeometry();
29660         frame.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray(vertices3d, 3), 3));
29661         return new THREE.Line(frame, new THREE.LineBasicMaterial());
29662     };
29663     SpatialDataScene.prototype._createLatitude = function (basicY, numVertices, transform) {
29664         var positions = new Float32Array((numVertices + 1) * 3);
29665         for (var i = 0; i <= numVertices; i++) {
29666             var position = transform.unprojectBasic([i / numVertices, basicY], 0.16);
29667             var index = 3 * i;
29668             positions[index + 0] = position[0];
29669             positions[index + 1] = position[1];
29670             positions[index + 2] = position[2];
29671         }
29672         var latitude = new THREE.BufferGeometry();
29673         latitude.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29674         return new THREE.Line(latitude, new THREE.LineBasicMaterial());
29675     };
29676     SpatialDataScene.prototype._createLongitude = function (basicX, numVertices, transform) {
29677         var positions = new Float32Array((numVertices + 1) * 3);
29678         for (var i = 0; i <= numVertices; i++) {
29679             var position = transform.unprojectBasic([basicX, i / numVertices], 0.16);
29680             var index = 3 * i;
29681             positions[index + 0] = position[0];
29682             positions[index + 1] = position[1];
29683             positions[index + 2] = position[2];
29684         }
29685         var latitude = new THREE.BufferGeometry();
29686         latitude.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29687         return new THREE.Line(latitude, new THREE.LineBasicMaterial());
29688     };
29689     SpatialDataScene.prototype._createPanoCamera = function (transform) {
29690         var camera = new THREE.Object3D();
29691         camera.children.push(this._createAxis(transform));
29692         camera.children.push(this._createLatitude(0.5, 10, transform));
29693         camera.children.push(this._createLongitude(0, 6, transform));
29694         camera.children.push(this._createLongitude(0.25, 6, transform));
29695         camera.children.push(this._createLongitude(0.5, 6, transform));
29696         camera.children.push(this._createLongitude(0.75, 6, transform));
29697         return camera;
29698     };
29699     SpatialDataScene.prototype._createPoints = function (reconstruction, transform) {
29700         var srtInverse = new THREE.Matrix4().getInverse(transform.srt);
29701         var points = Object
29702             .keys(reconstruction.points)
29703             .map(function (key) {
29704             return reconstruction.points[key];
29705         });
29706         var numPoints = points.length;
29707         var positions = new Float32Array(numPoints * 3);
29708         var colors = new Float32Array(numPoints * 3);
29709         for (var i = 0; i < numPoints; i++) {
29710             var index = 3 * i;
29711             var coords = points[i].coordinates;
29712             var point = new THREE.Vector3(coords[0], coords[1], coords[2])
29713                 .applyMatrix4(srtInverse);
29714             positions[index + 0] = point.x;
29715             positions[index + 1] = point.y;
29716             positions[index + 2] = point.z;
29717             var color = points[i].color;
29718             colors[index + 0] = color[0] / 255.0;
29719             colors[index + 1] = color[1] / 255.0;
29720             colors[index + 2] = color[2] / 255.0;
29721         }
29722         var geometry = new THREE.BufferGeometry();
29723         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29724         geometry.addAttribute("color", new THREE.BufferAttribute(colors, 3));
29725         var material = new THREE.PointsMaterial({
29726             size: 0.1,
29727             vertexColors: THREE.VertexColors,
29728         });
29729         return new THREE.Points(geometry, material);
29730     };
29731     SpatialDataScene.prototype._createPosition = function (transform, originalPosition) {
29732         var computedPosition = transform.unprojectBasic([0, 0], 0);
29733         var vertices = [originalPosition, computedPosition];
29734         var geometry = new THREE.BufferGeometry();
29735         geometry.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray(vertices, 3), 3));
29736         return new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: new THREE.Color(1, 0, 0) }));
29737     };
29738     SpatialDataScene.prototype._createPrespectiveCamera = function (transform) {
29739         var depth = 0.2;
29740         var camera = new THREE.Object3D();
29741         camera.children.push(this._createDiagonals(transform, depth));
29742         camera.children.push(this._createFrame(transform, depth));
29743         return camera;
29744     };
29745     SpatialDataScene.prototype._disposeCameras = function (hash) {
29746         var tileCameras = this._reconstructions[hash].cameras;
29747         for (var _i = 0, _a = tileCameras.children.slice(); _i < _a.length; _i++) {
29748             var camera = _a[_i];
29749             for (var _b = 0, _c = camera.children; _b < _c.length; _b++) {
29750                 var child = _c[_b];
29751                 child.geometry.dispose();
29752                 child.material.dispose();
29753                 var index = this._interactiveObjects.indexOf(child);
29754                 if (index !== -1) {
29755                     this._interactiveObjects.splice(index, 1);
29756                 }
29757                 else {
29758                     console.warn("Object does not exist (" + child.id + ") for " + hash);
29759                 }
29760             }
29761             tileCameras.remove(camera);
29762         }
29763         this._scene.remove(tileCameras);
29764     };
29765     SpatialDataScene.prototype._disposePoints = function (hash) {
29766         var tilePoints = this._reconstructions[hash].points;
29767         for (var _i = 0, _a = tilePoints.children.slice(); _i < _a.length; _i++) {
29768             var points = _a[_i];
29769             points.geometry.dispose();
29770             points.material.dispose();
29771             tilePoints.remove(points);
29772         }
29773         this._scene.remove(tilePoints);
29774     };
29775     SpatialDataScene.prototype._disposePositions = function (hash) {
29776         var tilePositions = this._reconstructions[hash].positions;
29777         for (var _i = 0, _a = tilePositions.children.slice(); _i < _a.length; _i++) {
29778             var position = _a[_i];
29779             position.geometry.dispose();
29780             position.material.dispose();
29781             tilePositions.remove(position);
29782         }
29783         this._scene.remove(tilePositions);
29784     };
29785     SpatialDataScene.prototype._disposeReconstruction = function (hash) {
29786         this._disposeCameras(hash);
29787         this._disposePoints(hash);
29788         this._disposePositions(hash);
29789         delete this._reconstructions[hash];
29790     };
29791     SpatialDataScene.prototype._disposeTile = function (hash) {
29792         var tile = this._tiles[hash];
29793         for (var _i = 0, _a = tile.children.slice(); _i < _a.length; _i++) {
29794             var line = _a[_i];
29795             line.geometry.dispose();
29796             line.material.dispose();
29797             tile.remove(line);
29798         }
29799         this._scene.remove(tile);
29800         delete this._tiles[hash];
29801     };
29802     SpatialDataScene.prototype._getColor = function (connectedComponent, visualizeConnectedComponents) {
29803         return visualizeConnectedComponents ?
29804             this._getConnectedComponentColor(connectedComponent) :
29805             "#FFFFFF";
29806     };
29807     SpatialDataScene.prototype._getConnectedComponentColor = function (connectedComponent) {
29808         if (!(connectedComponent in this._connectedComponentColors)) {
29809             this._connectedComponentColors[connectedComponent] = this._randomColor();
29810         }
29811         return this._connectedComponentColors[connectedComponent];
29812     };
29813     SpatialDataScene.prototype._interpolate = function (a, b, alpha) {
29814         return a + alpha * (b - a);
29815     };
29816     SpatialDataScene.prototype._randomColor = function () {
29817         return "hsl(" + Math.floor(360 * Math.random()) + ", 100%, 65%)";
29818     };
29819     SpatialDataScene.prototype._setCameraColor = function (color, camera) {
29820         for (var _i = 0, _a = camera.children; _i < _a.length; _i++) {
29821             var child = _a[_i];
29822             child.material.color = new THREE.Color(color);
29823         }
29824     };
29825     SpatialDataScene.prototype._subsample = function (p1, p2, subsamples) {
29826         if (subsamples < 1) {
29827             return [p1, p2];
29828         }
29829         var samples = [];
29830         for (var i = 0; i <= subsamples + 1; i++) {
29831             var p = [];
29832             for (var j = 0; j < 3; j++) {
29833                 p.push(this._interpolate(p1[j], p2[j], i / (subsamples + 1)));
29834             }
29835             samples.push(p);
29836         }
29837         return samples;
29838     };
29839     return SpatialDataScene;
29840 }());
29841 exports.SpatialDataScene = SpatialDataScene;
29842 exports.default = SpatialDataScene;
29843
29844 },{"three":225}],342:[function(require,module,exports){
29845 "use strict";
29846 Object.defineProperty(exports, "__esModule", { value: true });
29847 var GeometryTagError_1 = require("./error/GeometryTagError");
29848 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
29849 var PointGeometry_1 = require("./geometry/PointGeometry");
29850 exports.PointGeometry = PointGeometry_1.PointGeometry;
29851 var RectGeometry_1 = require("./geometry/RectGeometry");
29852 exports.RectGeometry = RectGeometry_1.RectGeometry;
29853 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
29854 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
29855 var OutlineTag_1 = require("./tag/OutlineTag");
29856 exports.OutlineTag = OutlineTag_1.OutlineTag;
29857 var SpotTag_1 = require("./tag/SpotTag");
29858 exports.SpotTag = SpotTag_1.SpotTag;
29859 var TagDomain_1 = require("./tag/TagDomain");
29860 exports.TagDomain = TagDomain_1.TagDomain;
29861 var TagComponent_1 = require("./TagComponent");
29862 exports.TagComponent = TagComponent_1.TagComponent;
29863 var TagMode_1 = require("./TagMode");
29864 exports.TagMode = TagMode_1.TagMode;
29865
29866 },{"./TagComponent":343,"./TagMode":346,"./error/GeometryTagError":350,"./geometry/PointGeometry":352,"./geometry/PolygonGeometry":353,"./geometry/RectGeometry":354,"./tag/OutlineTag":366,"./tag/SpotTag":369,"./tag/TagDomain":371}],343:[function(require,module,exports){
29867 "use strict";
29868 var __extends = (this && this.__extends) || (function () {
29869     var extendStatics = function (d, b) {
29870         extendStatics = Object.setPrototypeOf ||
29871             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29872             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29873         return extendStatics(d, b);
29874     }
29875     return function (d, b) {
29876         extendStatics(d, b);
29877         function __() { this.constructor = d; }
29878         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29879     };
29880 })();
29881 Object.defineProperty(exports, "__esModule", { value: true });
29882 var rxjs_1 = require("rxjs");
29883 var operators_1 = require("rxjs/operators");
29884 var when = require("when");
29885 var Component_1 = require("../../Component");
29886 var Geo_1 = require("../../Geo");
29887 var Render_1 = require("../../Render");
29888 /**
29889  * @class TagComponent
29890  *
29891  * @classdesc Component for showing and editing tags with different
29892  * geometries composed from 2D basic image coordinates (see the
29893  * {@link Viewer} class documentation for more information about coordinate
29894  * systems).
29895  *
29896  * The `add` method is used for adding new tags or replacing
29897  * tags already in the set. Tags are removed by id.
29898  *
29899  * If a tag already in the set has the same
29900  * id as one of the tags added, the old tag will be removed and
29901  * the added tag will take its place.
29902  *
29903  * The tag component mode can be set to either be non interactive or
29904  * to be in creating mode of a certain geometry type.
29905  *
29906  * The tag properties can be updated at any time and the change will
29907  * be visibile immediately.
29908  *
29909  * Tags are only relevant to a single image because they are based on
29910  * 2D basic image coordinates. Tags related to a certain image should
29911  * be removed when the viewer is moved to another node.
29912  *
29913  * To retrive and use the tag component
29914  *
29915  * @example
29916  * ```
29917  * var viewer = new Mapillary.Viewer(
29918  *     "<element-id>",
29919  *     "<client-id>",
29920  *     "<my key>",
29921  *     { component: { tag: true } });
29922  *
29923  * var tagComponent = viewer.getComponent("tag");
29924  * ```
29925  */
29926 var TagComponent = /** @class */ (function (_super) {
29927     __extends(TagComponent, _super);
29928     /** @ignore */
29929     function TagComponent(name, container, navigator) {
29930         var _this = _super.call(this, name, container, navigator) || this;
29931         _this._tagDomRenderer = new Component_1.TagDOMRenderer();
29932         _this._tagScene = new Component_1.TagScene();
29933         _this._tagSet = new Component_1.TagSet();
29934         _this._tagCreator = new Component_1.TagCreator(_this, navigator);
29935         _this._viewportCoords = new Geo_1.ViewportCoords();
29936         _this._createHandlers = {
29937             "CreatePoint": new Component_1.CreatePointHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
29938             "CreatePolygon": new Component_1.CreatePolygonHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
29939             "CreateRect": new Component_1.CreateRectHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
29940             "CreateRectDrag": new Component_1.CreateRectDragHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
29941             "Default": undefined,
29942         };
29943         _this._editVertexHandler = new Component_1.EditVertexHandler(_this, container, navigator, _this._viewportCoords, _this._tagSet);
29944         _this._renderTags$ = _this._tagSet.changed$.pipe(operators_1.map(function (tagSet) {
29945             var tags = tagSet.getAll();
29946             // ensure that tags are always rendered in the same order
29947             // to avoid hover tracking problems on first resize.
29948             tags.sort(function (t1, t2) {
29949                 var id1 = t1.tag.id;
29950                 var id2 = t2.tag.id;
29951                 if (id1 < id2) {
29952                     return -1;
29953                 }
29954                 if (id1 > id2) {
29955                     return 1;
29956                 }
29957                 return 0;
29958             });
29959             return tags;
29960         }), operators_1.share());
29961         _this._tagChanged$ = _this._renderTags$.pipe(operators_1.switchMap(function (tags) {
29962             return rxjs_1.from(tags).pipe(operators_1.mergeMap(function (tag) {
29963                 return rxjs_1.merge(tag.tag.changed$, tag.tag.geometryChanged$);
29964             }));
29965         }), operators_1.share());
29966         _this._renderTagGLChanged$ = _this._renderTags$.pipe(operators_1.switchMap(function (tags) {
29967             return rxjs_1.from(tags).pipe(operators_1.mergeMap(function (tag) {
29968                 return tag.glObjectsChanged$;
29969             }));
29970         }), operators_1.share());
29971         _this._createGeometryChanged$ = _this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
29972             return tag != null ?
29973                 tag.geometryChanged$ :
29974                 rxjs_1.empty();
29975         }), operators_1.share());
29976         _this._createGLObjectsChanged$ = _this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
29977             return tag != null ?
29978                 tag.glObjectsChanged$ :
29979                 rxjs_1.empty();
29980         }), operators_1.share());
29981         _this._creatingConfiguration$ = _this._configuration$.pipe(operators_1.distinctUntilChanged(function (c1, c2) {
29982             return c1.mode === c2.mode;
29983         }, function (configuration) {
29984             return {
29985                 createColor: configuration.createColor,
29986                 mode: configuration.mode,
29987             };
29988         }), operators_1.publishReplay(1), operators_1.refCount());
29989         _this._creatingConfiguration$
29990             .subscribe(function (configuration) {
29991             _this.fire(TagComponent.modechanged, configuration.mode);
29992         });
29993         return _this;
29994     }
29995     /**
29996      * Add tags to the tag set or replace tags in the tag set.
29997      *
29998      * @description If a tag already in the set has the same
29999      * id as one of the tags added, the old tag will be removed
30000      * the added tag will take its place.
30001      *
30002      * @param {Array<Tag>} tags - Tags to add.
30003      *
30004      * @example ```tagComponent.add([tag1, tag2]);```
30005      */
30006     TagComponent.prototype.add = function (tags) {
30007         var _this = this;
30008         if (this._activated) {
30009             this._navigator.stateService.currentTransform$.pipe(operators_1.first())
30010                 .subscribe(function (transform) {
30011                 _this._tagSet.add(tags, transform);
30012                 var renderTags = tags
30013                     .map(function (tag) {
30014                     return _this._tagSet.get(tag.id);
30015                 });
30016                 _this._tagScene.add(renderTags);
30017             });
30018         }
30019         else {
30020             this._tagSet.addDeactivated(tags);
30021         }
30022     };
30023     /**
30024      * Change the current tag mode.
30025      *
30026      * @description Change the tag mode to one of the create modes for creating new geometries.
30027      *
30028      * @param {TagMode} mode - New tag mode.
30029      *
30030      * @fires TagComponent#modechanged
30031      *
30032      * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);```
30033      */
30034     TagComponent.prototype.changeMode = function (mode) {
30035         this.configure({ mode: mode });
30036     };
30037     /**
30038      * Returns the tag in the tag set with the specified id, or
30039      * undefined if the id matches no tag.
30040      *
30041      * @param {string} tagId - Id of the tag.
30042      *
30043      * @example ```var tag = tagComponent.get("tagId");```
30044      */
30045     TagComponent.prototype.get = function (tagId) {
30046         if (this._activated) {
30047             var renderTag = this._tagSet.get(tagId);
30048             return renderTag !== undefined ? renderTag.tag : undefined;
30049         }
30050         else {
30051             return this._tagSet.getDeactivated(tagId);
30052         }
30053     };
30054     /**
30055      * Returns an array of all tags.
30056      *
30057      * @example ```var tags = tagComponent.getAll();```
30058      */
30059     TagComponent.prototype.getAll = function () {
30060         if (this.activated) {
30061             return this._tagSet
30062                 .getAll()
30063                 .map(function (renderTag) {
30064                 return renderTag.tag;
30065             });
30066         }
30067         else {
30068             return this._tagSet.getAllDeactivated();
30069         }
30070     };
30071     /**
30072      * Returns an array of tag ids for tags that contain the specified point.
30073      *
30074      * @description The pixel point must lie inside the polygon or rectangle
30075      * of an added tag for the tag id to be returned. Tag ids for
30076      * tags that do not have a fill will also be returned if the point is inside
30077      * the geometry of the tag. Tags with point geometries can not be retrieved.
30078      *
30079      * No tag ids will be returned for panoramas.
30080      *
30081      * Notice that the pixelPoint argument requires x, y coordinates from pixel space.
30082      *
30083      * With this function, you can use the coordinates provided by mouse
30084      * events to get information out of the tag component.
30085      *
30086      * If no tag at exist the pixel point, an empty array will be returned.
30087      *
30088      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
30089      * @returns {Array<string>} Ids of the tags that contain the specified pixel point.
30090      *
30091      * @example
30092      * ```
30093      * tagComponent.getTagIdsAt([100, 100])
30094      *     .then((tagIds) => { console.log(tagIds); });
30095      * ```
30096      */
30097     TagComponent.prototype.getTagIdsAt = function (pixelPoint) {
30098         var _this = this;
30099         return when.promise(function (resolve, reject) {
30100             _this._container.renderService.renderCamera$.pipe(operators_1.first(), operators_1.map(function (render) {
30101                 var viewport = _this._viewportCoords
30102                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
30103                 var ids = _this._tagScene.intersectObjects(viewport, render.perspective);
30104                 return ids;
30105             }))
30106                 .subscribe(function (ids) {
30107                 resolve(ids);
30108             }, function (error) {
30109                 reject(error);
30110             });
30111         });
30112     };
30113     /**
30114      * Check if a tag exist in the tag set.
30115      *
30116      * @param {string} tagId - Id of the tag.
30117      *
30118      * @example ```var tagExists = tagComponent.has("tagId");```
30119      */
30120     TagComponent.prototype.has = function (tagId) {
30121         return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
30122     };
30123     /**
30124      * Remove tags with the specified ids from the tag set.
30125      *
30126      * @param {Array<string>} tagIds - Ids for tags to remove.
30127      *
30128      * @example ```tagComponent.remove(["id-1", "id-2"]);```
30129      */
30130     TagComponent.prototype.remove = function (tagIds) {
30131         if (this._activated) {
30132             this._tagSet.remove(tagIds);
30133             this._tagScene.remove(tagIds);
30134         }
30135         else {
30136             this._tagSet.removeDeactivated(tagIds);
30137         }
30138     };
30139     /**
30140      * Remove all tags from the tag set.
30141      *
30142      * @example ```tagComponent.removeAll();```
30143      */
30144     TagComponent.prototype.removeAll = function () {
30145         if (this._activated) {
30146             this._tagSet.removeAll();
30147             this._tagScene.removeAll();
30148         }
30149         else {
30150             this._tagSet.removeAllDeactivated();
30151         }
30152     };
30153     TagComponent.prototype._activate = function () {
30154         var _this = this;
30155         this._editVertexHandler.enable();
30156         var handlerGeometryCreated$ = rxjs_1.from(Object.keys(this._createHandlers)).pipe(operators_1.map(function (key) {
30157             return _this._createHandlers[key];
30158         }), operators_1.filter(function (handler) {
30159             return !!handler;
30160         }), operators_1.mergeMap(function (handler) {
30161             return handler.geometryCreated$;
30162         }), operators_1.share());
30163         this._fireGeometryCreatedSubscription = handlerGeometryCreated$
30164             .subscribe(function (geometry) {
30165             _this.fire(TagComponent.geometrycreated, geometry);
30166         });
30167         this._fireCreateGeometryEventSubscription = this._tagCreator.tag$.pipe(operators_1.skipWhile(function (tag) {
30168             return tag == null;
30169         }), operators_1.distinctUntilChanged())
30170             .subscribe(function (tag) {
30171             var eventType = tag != null ?
30172                 TagComponent.creategeometrystart :
30173                 TagComponent.creategeometryend;
30174             _this.fire(eventType, _this);
30175         });
30176         this._handlerStopCreateSubscription = handlerGeometryCreated$
30177             .subscribe(function () {
30178             _this.changeMode(Component_1.TagMode.Default);
30179         });
30180         this._handlerEnablerSubscription = this._creatingConfiguration$
30181             .subscribe(function (configuration) {
30182             _this._disableCreateHandlers();
30183             var mode = Component_1.TagMode[configuration.mode];
30184             var handler = _this._createHandlers[mode];
30185             if (!!handler) {
30186                 handler.enable();
30187             }
30188         });
30189         this._fireTagsChangedSubscription = this._renderTags$
30190             .subscribe(function (tags) {
30191             _this.fire(TagComponent.tagschanged, _this);
30192         });
30193         this._stopCreateSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
30194             return tag != null ?
30195                 tag.aborted$.pipe(operators_1.map(function (t) { return null; })) :
30196                 rxjs_1.empty();
30197         }))
30198             .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); });
30199         this._setGLCreateTagSubscription = this._tagCreator.tag$
30200             .subscribe(function (tag) {
30201             if (_this._tagScene.hasCreateTag()) {
30202                 _this._tagScene.removeCreateTag();
30203             }
30204             if (tag != null) {
30205                 _this._tagScene.addCreateTag(tag);
30206             }
30207         });
30208         this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$
30209             .subscribe(function (tag) {
30210             _this._tagScene.updateCreateTagObjects(tag);
30211         });
30212         this._updateGLObjectsSubscription = this._renderTagGLChanged$
30213             .subscribe(function (tag) {
30214             _this._tagScene.updateObjects(tag);
30215         });
30216         this._updateTagSceneSubscription = this._tagChanged$
30217             .subscribe(function (tag) {
30218             _this._tagScene.update();
30219         });
30220         this._domSubscription = rxjs_1.combineLatest(this._renderTags$.pipe(operators_1.startWith([]), operators_1.tap(function (tags) {
30221             _this._container.domRenderer.render$.next({
30222                 name: _this._name,
30223                 vnode: _this._tagDomRenderer.clear(),
30224             });
30225         })), this._container.renderService.renderCamera$, this._container.spriteService.spriteAtlas$, this._container.renderService.size$, this._tagChanged$.pipe(operators_1.startWith(null)), rxjs_1.merge(this._tagCreator.tag$, this._createGeometryChanged$).pipe(operators_1.startWith(null))).pipe(operators_1.map(function (_a) {
30226             var renderTags = _a[0], rc = _a[1], atlas = _a[2], size = _a[3], tag = _a[4], ct = _a[5];
30227             return {
30228                 name: _this._name,
30229                 vnode: _this._tagDomRenderer.render(renderTags, ct, atlas, rc.perspective, size),
30230             };
30231         }))
30232             .subscribe(this._container.domRenderer.render$);
30233         this._glSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
30234             var tagScene = _this._tagScene;
30235             return {
30236                 name: _this._name,
30237                 render: {
30238                     frameId: frame.id,
30239                     needsRender: tagScene.needsRender,
30240                     render: tagScene.render.bind(tagScene),
30241                     stage: Render_1.GLRenderStage.Foreground,
30242                 },
30243             };
30244         }))
30245             .subscribe(this._container.glRenderer.render$);
30246         this._navigator.stateService.currentTransform$.pipe(operators_1.first())
30247             .subscribe(function (transform) {
30248             _this._tagSet.activate(transform);
30249             _this._tagScene.add(_this._tagSet.getAll());
30250         });
30251     };
30252     TagComponent.prototype._deactivate = function () {
30253         this._editVertexHandler.disable();
30254         this._disableCreateHandlers();
30255         this._tagScene.clear();
30256         this._tagSet.deactivate();
30257         this._tagCreator.delete$.next(null);
30258         this._updateGLObjectsSubscription.unsubscribe();
30259         this._updateTagSceneSubscription.unsubscribe();
30260         this._stopCreateSubscription.unsubscribe();
30261         this._setGLCreateTagSubscription.unsubscribe();
30262         this._createGLObjectsChangedSubscription.unsubscribe();
30263         this._domSubscription.unsubscribe();
30264         this._glSubscription.unsubscribe();
30265         this._fireCreateGeometryEventSubscription.unsubscribe();
30266         this._fireGeometryCreatedSubscription.unsubscribe();
30267         this._fireTagsChangedSubscription.unsubscribe();
30268         this._handlerStopCreateSubscription.unsubscribe();
30269         this._handlerEnablerSubscription.unsubscribe();
30270         this._container.element.classList.remove("component-tag-create");
30271     };
30272     TagComponent.prototype._getDefaultConfiguration = function () {
30273         return {
30274             createColor: 0xFFFFFF,
30275             mode: Component_1.TagMode.Default,
30276         };
30277     };
30278     TagComponent.prototype._disableCreateHandlers = function () {
30279         var createHandlers = this._createHandlers;
30280         for (var key in createHandlers) {
30281             if (!createHandlers.hasOwnProperty(key)) {
30282                 continue;
30283             }
30284             var handler = createHandlers[key];
30285             if (!!handler) {
30286                 handler.disable();
30287             }
30288         }
30289     };
30290     /** @inheritdoc */
30291     TagComponent.componentName = "tag";
30292     /**
30293      * Event fired when an interaction to create a geometry ends.
30294      *
30295      * @description A create interaction can by a geometry being created
30296      * or by the creation being aborted.
30297      *
30298      * @event TagComponent#creategeometryend
30299      * @type {TagComponent} Tag component.
30300      * @example
30301      * ```
30302      * tagComponent.on("creategeometryend", function(component) {
30303      *     console.log(component);
30304      * });
30305      * ```
30306      */
30307     TagComponent.creategeometryend = "creategeometryend";
30308     /**
30309      * Event fired when an interaction to create a geometry starts.
30310      *
30311      * @description A create interaction starts when the first vertex
30312      * is created in the geometry.
30313      *
30314      * @event TagComponent#creategeometrystart
30315      * @type {TagComponent} Tag component.
30316      * @example
30317      * ```
30318      * tagComponent.on("creategeometrystart", function(component) {
30319      *     console.log(component);
30320      * });
30321      * ```
30322      */
30323     TagComponent.creategeometrystart = "creategeometrystart";
30324     /**
30325      * Event fired when the create mode is changed.
30326      *
30327      * @event TagComponent#modechanged
30328      * @type {TagMode} Tag mode
30329      * @example
30330      * ```
30331      * tagComponent.on("modechanged", function(mode) {
30332      *     console.log(mode);
30333      * });
30334      * ```
30335      */
30336     TagComponent.modechanged = "modechanged";
30337     /**
30338      * Event fired when a geometry has been created.
30339      *
30340      * @event TagComponent#geometrycreated
30341      * @type {Geometry} Created geometry.
30342      * @example
30343      * ```
30344      * tagComponent.on("geometrycreated", function(geometry) {
30345      *     console.log(geometry);
30346      * });
30347      * ```
30348      */
30349     TagComponent.geometrycreated = "geometrycreated";
30350     /**
30351      * Event fired when the tags collection has changed.
30352      *
30353      * @event TagComponent#tagschanged
30354      * @type {TagComponent} Tag component.
30355      * @example
30356      * ```
30357      * tagComponent.on("tagschanged", function(component) {
30358      *     console.log(component.getAll());
30359      * });
30360      * ```
30361      */
30362     TagComponent.tagschanged = "tagschanged";
30363     return TagComponent;
30364 }(Component_1.Component));
30365 exports.TagComponent = TagComponent;
30366 Component_1.ComponentService.register(TagComponent);
30367 exports.default = TagComponent;
30368
30369 },{"../../Component":274,"../../Geo":277,"../../Render":280,"rxjs":26,"rxjs/operators":224,"when":271}],344:[function(require,module,exports){
30370 "use strict";
30371 Object.defineProperty(exports, "__esModule", { value: true });
30372 var operators_1 = require("rxjs/operators");
30373 var rxjs_1 = require("rxjs");
30374 var Component_1 = require("../../Component");
30375 var TagCreator = /** @class */ (function () {
30376     function TagCreator(component, navigator) {
30377         this._component = component;
30378         this._navigator = navigator;
30379         this._tagOperation$ = new rxjs_1.Subject();
30380         this._createPolygon$ = new rxjs_1.Subject();
30381         this._createRect$ = new rxjs_1.Subject();
30382         this._delete$ = new rxjs_1.Subject();
30383         this._tag$ = this._tagOperation$.pipe(operators_1.scan(function (tag, operation) {
30384             return operation(tag);
30385         }, null), operators_1.share());
30386         this._createRect$.pipe(operators_1.withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
30387             var coord = _a[0], conf = _a[1], transform = _a[2];
30388             return function (tag) {
30389                 var geometry = new Component_1.RectGeometry([
30390                     coord[0],
30391                     coord[1],
30392                     coord[0],
30393                     coord[1],
30394                 ]);
30395                 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
30396             };
30397         }))
30398             .subscribe(this._tagOperation$);
30399         this._createPolygon$.pipe(operators_1.withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
30400             var coord = _a[0], conf = _a[1], transform = _a[2];
30401             return function (tag) {
30402                 var geometry = new Component_1.PolygonGeometry([
30403                     [coord[0], coord[1]],
30404                     [coord[0], coord[1]],
30405                     [coord[0], coord[1]],
30406                 ]);
30407                 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
30408             };
30409         }))
30410             .subscribe(this._tagOperation$);
30411         this._delete$.pipe(operators_1.map(function () {
30412             return function (tag) {
30413                 return null;
30414             };
30415         }))
30416             .subscribe(this._tagOperation$);
30417     }
30418     Object.defineProperty(TagCreator.prototype, "createRect$", {
30419         get: function () {
30420             return this._createRect$;
30421         },
30422         enumerable: true,
30423         configurable: true
30424     });
30425     Object.defineProperty(TagCreator.prototype, "createPolygon$", {
30426         get: function () {
30427             return this._createPolygon$;
30428         },
30429         enumerable: true,
30430         configurable: true
30431     });
30432     Object.defineProperty(TagCreator.prototype, "delete$", {
30433         get: function () {
30434             return this._delete$;
30435         },
30436         enumerable: true,
30437         configurable: true
30438     });
30439     Object.defineProperty(TagCreator.prototype, "tag$", {
30440         get: function () {
30441             return this._tag$;
30442         },
30443         enumerable: true,
30444         configurable: true
30445     });
30446     return TagCreator;
30447 }());
30448 exports.TagCreator = TagCreator;
30449 exports.default = TagCreator;
30450
30451 },{"../../Component":274,"rxjs":26,"rxjs/operators":224}],345:[function(require,module,exports){
30452 "use strict";
30453 Object.defineProperty(exports, "__esModule", { value: true });
30454 var vd = require("virtual-dom");
30455 var TagDOMRenderer = /** @class */ (function () {
30456     function TagDOMRenderer() {
30457     }
30458     TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, size) {
30459         var vNodes = [];
30460         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
30461             var tag = tags_1[_i];
30462             vNodes = vNodes.concat(tag.getDOMObjects(atlas, camera, size));
30463         }
30464         if (createTag != null) {
30465             vNodes = vNodes.concat(createTag.getDOMObjects(camera, size));
30466         }
30467         return vd.h("div.TagContainer", {}, vNodes);
30468     };
30469     TagDOMRenderer.prototype.clear = function () {
30470         return vd.h("div", {}, []);
30471     };
30472     return TagDOMRenderer;
30473 }());
30474 exports.TagDOMRenderer = TagDOMRenderer;
30475
30476 },{"virtual-dom":230}],346:[function(require,module,exports){
30477 "use strict";
30478 Object.defineProperty(exports, "__esModule", { value: true });
30479 /**
30480  * Enumeration for tag modes
30481  * @enum {number}
30482  * @readonly
30483  * @description Modes for the interaction in the tag component.
30484  */
30485 var TagMode;
30486 (function (TagMode) {
30487     /**
30488      * Disables creating tags.
30489      */
30490     TagMode[TagMode["Default"] = 0] = "Default";
30491     /**
30492      * Create a point geometry through a click.
30493      */
30494     TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint";
30495     /**
30496      * Create a polygon geometry through clicks.
30497      */
30498     TagMode[TagMode["CreatePolygon"] = 2] = "CreatePolygon";
30499     /**
30500      * Create a rect geometry through clicks.
30501      */
30502     TagMode[TagMode["CreateRect"] = 3] = "CreateRect";
30503     /**
30504      * Create a rect geometry through drag.
30505      *
30506      * @description Claims the mouse which results in mouse handlers like
30507      * drag pan and scroll zoom becoming inactive.
30508      */
30509     TagMode[TagMode["CreateRectDrag"] = 4] = "CreateRectDrag";
30510 })(TagMode = exports.TagMode || (exports.TagMode = {}));
30511 exports.default = TagMode;
30512
30513 },{}],347:[function(require,module,exports){
30514 "use strict";
30515 Object.defineProperty(exports, "__esModule", { value: true });
30516 var TagOperation;
30517 (function (TagOperation) {
30518     TagOperation[TagOperation["None"] = 0] = "None";
30519     TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
30520     TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
30521 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
30522 exports.default = TagOperation;
30523
30524 },{}],348:[function(require,module,exports){
30525 "use strict";
30526 Object.defineProperty(exports, "__esModule", { value: true });
30527 var THREE = require("three");
30528 var TagScene = /** @class */ (function () {
30529     function TagScene(scene, raycaster) {
30530         this._createTag = null;
30531         this._needsRender = false;
30532         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
30533         this._scene = !!scene ? scene : new THREE.Scene();
30534         this._objectTags = {};
30535         this._retrievableObjects = [];
30536         this._tags = {};
30537     }
30538     Object.defineProperty(TagScene.prototype, "needsRender", {
30539         get: function () {
30540             return this._needsRender;
30541         },
30542         enumerable: true,
30543         configurable: true
30544     });
30545     TagScene.prototype.add = function (tags) {
30546         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
30547             var tag = tags_1[_i];
30548             if (tag.tag.id in this._tags) {
30549                 this._remove(tag.tag.id);
30550             }
30551             this._add(tag);
30552         }
30553         this._needsRender = true;
30554     };
30555     TagScene.prototype.addCreateTag = function (tag) {
30556         for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) {
30557             var object = _a[_i];
30558             this._scene.add(object);
30559         }
30560         this._createTag = { tag: tag, objects: tag.glObjects };
30561         this._needsRender = true;
30562     };
30563     TagScene.prototype.clear = function () {
30564         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
30565             var id = _a[_i];
30566             this._remove(id);
30567         }
30568         this._needsRender = false;
30569     };
30570     TagScene.prototype.get = function (id) {
30571         return this.has(id) ? this._tags[id].tag : undefined;
30572     };
30573     TagScene.prototype.has = function (id) {
30574         return id in this._tags;
30575     };
30576     TagScene.prototype.hasCreateTag = function () {
30577         return this._createTag != null;
30578     };
30579     TagScene.prototype.intersectObjects = function (_a, camera) {
30580         var viewportX = _a[0], viewportY = _a[1];
30581         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
30582         var intersects = this._raycaster.intersectObjects(this._retrievableObjects);
30583         var intersectedIds = [];
30584         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
30585             var intersect = intersects_1[_i];
30586             if (intersect.object.uuid in this._objectTags) {
30587                 intersectedIds.push(this._objectTags[intersect.object.uuid]);
30588             }
30589         }
30590         return intersectedIds;
30591     };
30592     TagScene.prototype.remove = function (ids) {
30593         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
30594             var id = ids_1[_i];
30595             this._remove(id);
30596         }
30597         this._needsRender = true;
30598     };
30599     TagScene.prototype.removeAll = function () {
30600         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
30601             var id = _a[_i];
30602             this._remove(id);
30603         }
30604         this._needsRender = true;
30605     };
30606     TagScene.prototype.removeCreateTag = function () {
30607         if (this._createTag == null) {
30608             return;
30609         }
30610         for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
30611             var object = _a[_i];
30612             this._scene.remove(object);
30613         }
30614         this._createTag.tag.dispose();
30615         this._createTag = null;
30616         this._needsRender = true;
30617     };
30618     TagScene.prototype.render = function (perspectiveCamera, renderer) {
30619         renderer.render(this._scene, perspectiveCamera);
30620         this._needsRender = false;
30621     };
30622     TagScene.prototype.update = function () {
30623         this._needsRender = true;
30624     };
30625     TagScene.prototype.updateCreateTagObjects = function (tag) {
30626         if (this._createTag.tag !== tag) {
30627             throw new Error("Create tags do not have the same reference.");
30628         }
30629         for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
30630             var object = _a[_i];
30631             this._scene.remove(object);
30632         }
30633         for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) {
30634             var object = _c[_b];
30635             this._scene.add(object);
30636         }
30637         this._createTag.objects = tag.glObjects;
30638         this._needsRender = true;
30639     };
30640     TagScene.prototype.updateObjects = function (tag) {
30641         var id = tag.tag.id;
30642         if (this._tags[id].tag !== tag) {
30643             throw new Error("Tags do not have the same reference.");
30644         }
30645         var tagObjects = this._tags[id];
30646         this._removeObjects(tagObjects);
30647         delete this._tags[id];
30648         this._add(tag);
30649         this._needsRender = true;
30650     };
30651     TagScene.prototype._add = function (tag) {
30652         var id = tag.tag.id;
30653         var tagObjects = { tag: tag, objects: [], retrievableObjects: [] };
30654         this._tags[id] = tagObjects;
30655         for (var _i = 0, _a = tag.getGLObjects(); _i < _a.length; _i++) {
30656             var object = _a[_i];
30657             tagObjects.objects.push(object);
30658             this._scene.add(object);
30659         }
30660         for (var _b = 0, _c = tag.getRetrievableObjects(); _b < _c.length; _b++) {
30661             var retrievableObject = _c[_b];
30662             tagObjects.retrievableObjects.push(retrievableObject);
30663             this._retrievableObjects.push(retrievableObject);
30664             this._objectTags[retrievableObject.uuid] = tag.tag.id;
30665         }
30666     };
30667     TagScene.prototype._remove = function (id) {
30668         var tagObjects = this._tags[id];
30669         this._removeObjects(tagObjects);
30670         tagObjects.tag.dispose();
30671         delete this._tags[id];
30672     };
30673     TagScene.prototype._removeObjects = function (tagObjects) {
30674         for (var _i = 0, _a = tagObjects.objects; _i < _a.length; _i++) {
30675             var object = _a[_i];
30676             this._scene.remove(object);
30677         }
30678         for (var _b = 0, _c = tagObjects.retrievableObjects; _b < _c.length; _b++) {
30679             var retrievableObject = _c[_b];
30680             var index = this._retrievableObjects.indexOf(retrievableObject);
30681             if (index !== -1) {
30682                 this._retrievableObjects.splice(index, 1);
30683             }
30684         }
30685     };
30686     return TagScene;
30687 }());
30688 exports.TagScene = TagScene;
30689 exports.default = TagScene;
30690
30691 },{"three":225}],349:[function(require,module,exports){
30692 "use strict";
30693 Object.defineProperty(exports, "__esModule", { value: true });
30694 var rxjs_1 = require("rxjs");
30695 var Component_1 = require("../../Component");
30696 var TagSet = /** @class */ (function () {
30697     function TagSet() {
30698         this._active = false;
30699         this._hash = {};
30700         this._hashDeactivated = {};
30701         this._notifyChanged$ = new rxjs_1.Subject();
30702     }
30703     Object.defineProperty(TagSet.prototype, "active", {
30704         get: function () {
30705             return this._active;
30706         },
30707         enumerable: true,
30708         configurable: true
30709     });
30710     Object.defineProperty(TagSet.prototype, "changed$", {
30711         get: function () {
30712             return this._notifyChanged$;
30713         },
30714         enumerable: true,
30715         configurable: true
30716     });
30717     TagSet.prototype.activate = function (transform) {
30718         if (this._active) {
30719             return;
30720         }
30721         for (var id in this._hashDeactivated) {
30722             if (!this._hashDeactivated.hasOwnProperty(id)) {
30723                 continue;
30724             }
30725             var tag = this._hashDeactivated[id];
30726             this._add(tag, transform);
30727         }
30728         this._hashDeactivated = {};
30729         this._active = true;
30730         this._notifyChanged$.next(this);
30731     };
30732     TagSet.prototype.deactivate = function () {
30733         if (!this._active) {
30734             return;
30735         }
30736         for (var id in this._hash) {
30737             if (!this._hash.hasOwnProperty(id)) {
30738                 continue;
30739             }
30740             this._hashDeactivated[id] = this._hash[id].tag;
30741         }
30742         this._hash = {};
30743         this._active = false;
30744     };
30745     TagSet.prototype.add = function (tags, transform) {
30746         this._assertActivationState(true);
30747         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
30748             var tag = tags_1[_i];
30749             this._add(tag, transform);
30750         }
30751         this._notifyChanged$.next(this);
30752     };
30753     TagSet.prototype.addDeactivated = function (tags) {
30754         this._assertActivationState(false);
30755         for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
30756             var tag = tags_2[_i];
30757             if (!(tag instanceof Component_1.OutlineTag || tag instanceof Component_1.SpotTag)) {
30758                 throw new Error("Tag type not supported");
30759             }
30760             this._hashDeactivated[tag.id] = tag;
30761         }
30762     };
30763     TagSet.prototype.get = function (id) {
30764         return this.has(id) ? this._hash[id] : undefined;
30765     };
30766     TagSet.prototype.getAll = function () {
30767         var hash = this._hash;
30768         return Object.keys(hash)
30769             .map(function (id) {
30770             return hash[id];
30771         });
30772     };
30773     TagSet.prototype.getAllDeactivated = function () {
30774         var hashDeactivated = this._hashDeactivated;
30775         return Object.keys(hashDeactivated)
30776             .map(function (id) {
30777             return hashDeactivated[id];
30778         });
30779     };
30780     TagSet.prototype.getDeactivated = function (id) {
30781         return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined;
30782     };
30783     TagSet.prototype.has = function (id) {
30784         return id in this._hash;
30785     };
30786     TagSet.prototype.hasDeactivated = function (id) {
30787         return id in this._hashDeactivated;
30788     };
30789     TagSet.prototype.remove = function (ids) {
30790         this._assertActivationState(true);
30791         var hash = this._hash;
30792         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
30793             var id = ids_1[_i];
30794             if (!(id in hash)) {
30795                 continue;
30796             }
30797             delete hash[id];
30798         }
30799         this._notifyChanged$.next(this);
30800     };
30801     TagSet.prototype.removeAll = function () {
30802         this._assertActivationState(true);
30803         this._hash = {};
30804         this._notifyChanged$.next(this);
30805     };
30806     TagSet.prototype.removeAllDeactivated = function () {
30807         this._assertActivationState(false);
30808         this._hashDeactivated = {};
30809     };
30810     TagSet.prototype.removeDeactivated = function (ids) {
30811         this._assertActivationState(false);
30812         var hashDeactivated = this._hashDeactivated;
30813         for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) {
30814             var id = ids_2[_i];
30815             if (!(id in hashDeactivated)) {
30816                 continue;
30817             }
30818             delete hashDeactivated[id];
30819         }
30820     };
30821     TagSet.prototype._add = function (tag, transform) {
30822         if (tag instanceof Component_1.OutlineTag) {
30823             this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform);
30824         }
30825         else if (tag instanceof Component_1.SpotTag) {
30826             this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform);
30827         }
30828         else {
30829             throw new Error("Tag type not supported");
30830         }
30831     };
30832     TagSet.prototype._assertActivationState = function (should) {
30833         if (should !== this._active) {
30834             throw new Error("Tag set not in correct state for operation.");
30835         }
30836     };
30837     return TagSet;
30838 }());
30839 exports.TagSet = TagSet;
30840 exports.default = TagSet;
30841
30842 },{"../../Component":274,"rxjs":26}],350:[function(require,module,exports){
30843 "use strict";
30844 var __extends = (this && this.__extends) || (function () {
30845     var extendStatics = function (d, b) {
30846         extendStatics = Object.setPrototypeOf ||
30847             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30848             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30849         return extendStatics(d, b);
30850     }
30851     return function (d, b) {
30852         extendStatics(d, b);
30853         function __() { this.constructor = d; }
30854         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30855     };
30856 })();
30857 Object.defineProperty(exports, "__esModule", { value: true });
30858 var Error_1 = require("../../../Error");
30859 var GeometryTagError = /** @class */ (function (_super) {
30860     __extends(GeometryTagError, _super);
30861     function GeometryTagError(message) {
30862         var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
30863         _this.name = "GeometryTagError";
30864         return _this;
30865     }
30866     return GeometryTagError;
30867 }(Error_1.MapillaryError));
30868 exports.GeometryTagError = GeometryTagError;
30869 exports.default = Error_1.MapillaryError;
30870
30871 },{"../../../Error":276}],351:[function(require,module,exports){
30872 "use strict";
30873 Object.defineProperty(exports, "__esModule", { value: true });
30874 var rxjs_1 = require("rxjs");
30875 /**
30876  * @class Geometry
30877  * @abstract
30878  * @classdesc Represents a geometry.
30879  */
30880 var Geometry = /** @class */ (function () {
30881     /**
30882      * Create a geometry.
30883      *
30884      * @constructor
30885      * @ignore
30886      */
30887     function Geometry() {
30888         this._notifyChanged$ = new rxjs_1.Subject();
30889     }
30890     Object.defineProperty(Geometry.prototype, "changed$", {
30891         /**
30892          * Get changed observable.
30893          *
30894          * @description Emits the geometry itself every time the geometry
30895          * has changed.
30896          *
30897          * @returns {Observable<Geometry>} Observable emitting the geometry instance.
30898          * @ignore
30899          */
30900         get: function () {
30901             return this._notifyChanged$;
30902         },
30903         enumerable: true,
30904         configurable: true
30905     });
30906     return Geometry;
30907 }());
30908 exports.Geometry = Geometry;
30909 exports.default = Geometry;
30910
30911 },{"rxjs":26}],352:[function(require,module,exports){
30912 "use strict";
30913 var __extends = (this && this.__extends) || (function () {
30914     var extendStatics = function (d, b) {
30915         extendStatics = Object.setPrototypeOf ||
30916             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30917             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30918         return extendStatics(d, b);
30919     }
30920     return function (d, b) {
30921         extendStatics(d, b);
30922         function __() { this.constructor = d; }
30923         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30924     };
30925 })();
30926 Object.defineProperty(exports, "__esModule", { value: true });
30927 var Component_1 = require("../../../Component");
30928 /**
30929  * @class PointGeometry
30930  *
30931  * @classdesc Represents a point geometry in the 2D basic image coordinate system.
30932  *
30933  * @example
30934  * ```
30935  * var basicPoint = [0.5, 0.7];
30936  * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint);
30937  * ```
30938  */
30939 var PointGeometry = /** @class */ (function (_super) {
30940     __extends(PointGeometry, _super);
30941     /**
30942      * Create a point geometry.
30943      *
30944      * @constructor
30945      * @param {Array<number>} point - An array representing the basic coordinates of
30946      * the point.
30947      *
30948      * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
30949      */
30950     function PointGeometry(point) {
30951         var _this = _super.call(this) || this;
30952         var x = point[0];
30953         var y = point[1];
30954         if (x < 0 || x > 1 || y < 0 || y > 1) {
30955             throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
30956         }
30957         _this._point = point.slice();
30958         return _this;
30959     }
30960     Object.defineProperty(PointGeometry.prototype, "point", {
30961         /**
30962          * Get point property.
30963          * @returns {Array<number>} Array representing the basic coordinates of the point.
30964          */
30965         get: function () {
30966             return this._point;
30967         },
30968         enumerable: true,
30969         configurable: true
30970     });
30971     /**
30972      * Get the 2D basic coordinates for the centroid of the point, i.e. the 2D
30973      * basic coordinates of the point itself.
30974      *
30975      * @returns {Array<number>} 2D basic coordinates representing the centroid.
30976      * @ignore
30977      */
30978     PointGeometry.prototype.getCentroid2d = function () {
30979         return this._point.slice();
30980     };
30981     /**
30982      * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
30983      * world coordinates of the point itself.
30984      *
30985      * @param {Transform} transform - The transform of the node related to the point.
30986      * @returns {Array<number>} 3D world coordinates representing the centroid.
30987      * @ignore
30988      */
30989     PointGeometry.prototype.getCentroid3d = function (transform) {
30990         return transform.unprojectBasic(this._point, 200);
30991     };
30992     /**
30993      * Set the centroid of the point, i.e. the point coordinates.
30994      *
30995      * @param {Array<number>} value - The new value of the centroid.
30996      * @param {Transform} transform - The transform of the node related to the point.
30997      * @ignore
30998      */
30999     PointGeometry.prototype.setCentroid2d = function (value, transform) {
31000         var changed = [
31001             Math.max(0, Math.min(1, value[0])),
31002             Math.max(0, Math.min(1, value[1])),
31003         ];
31004         this._point[0] = changed[0];
31005         this._point[1] = changed[1];
31006         this._notifyChanged$.next(this);
31007     };
31008     return PointGeometry;
31009 }(Component_1.Geometry));
31010 exports.PointGeometry = PointGeometry;
31011
31012 },{"../../../Component":274}],353:[function(require,module,exports){
31013 "use strict";
31014 var __extends = (this && this.__extends) || (function () {
31015     var extendStatics = function (d, b) {
31016         extendStatics = Object.setPrototypeOf ||
31017             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31018             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31019         return extendStatics(d, b);
31020     }
31021     return function (d, b) {
31022         extendStatics(d, b);
31023         function __() { this.constructor = d; }
31024         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31025     };
31026 })();
31027 Object.defineProperty(exports, "__esModule", { value: true });
31028 var Component_1 = require("../../../Component");
31029 /**
31030  * @class PolygonGeometry
31031  *
31032  * @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
31033  * All polygons and holes provided to the constructor needs to be closed.
31034  *
31035  * @example
31036  * ```
31037  * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
31038  * var polygonGeometry = new Mapillary.TagComponent.PolygonGeometry(basicPolygon);
31039  * ```
31040  */
31041 var PolygonGeometry = /** @class */ (function (_super) {
31042     __extends(PolygonGeometry, _super);
31043     /**
31044      * Create a polygon geometry.
31045      *
31046      * @constructor
31047      * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
31048      * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
31049      * Each array of holes vertices must be closed.
31050      *
31051      * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
31052      */
31053     function PolygonGeometry(polygon, holes) {
31054         var _this = _super.call(this) || this;
31055         _this._subsampleThreshold = 0.01;
31056         var polygonLength = polygon.length;
31057         if (polygonLength < 3) {
31058             throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
31059         }
31060         if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
31061             polygon[0][1] !== polygon[polygonLength - 1][1]) {
31062             throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
31063         }
31064         _this._polygon = [];
31065         for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
31066             var vertex = polygon_1[_i];
31067             if (vertex[0] < 0 || vertex[0] > 1 ||
31068                 vertex[1] < 0 || vertex[1] > 1) {
31069                 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
31070             }
31071             _this._polygon.push(vertex.slice());
31072         }
31073         _this._holes = [];
31074         if (holes == null) {
31075             return _this;
31076         }
31077         for (var i = 0; i < holes.length; i++) {
31078             var hole = holes[i];
31079             var holeLength = hole.length;
31080             if (holeLength < 3) {
31081                 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
31082             }
31083             if (hole[0][0] !== hole[holeLength - 1][0] ||
31084                 hole[0][1] !== hole[holeLength - 1][1]) {
31085                 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
31086             }
31087             _this._holes.push([]);
31088             for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
31089                 var vertex = hole_1[_a];
31090                 if (vertex[0] < 0 || vertex[0] > 1 ||
31091                     vertex[1] < 0 || vertex[1] > 1) {
31092                     throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
31093                 }
31094                 _this._holes[i].push(vertex.slice());
31095             }
31096         }
31097         return _this;
31098     }
31099     Object.defineProperty(PolygonGeometry.prototype, "polygon", {
31100         /**
31101          * Get polygon property.
31102          * @returns {Array<Array<number>>} Closed 2d polygon.
31103          */
31104         get: function () {
31105             return this._polygon;
31106         },
31107         enumerable: true,
31108         configurable: true
31109     });
31110     Object.defineProperty(PolygonGeometry.prototype, "holes", {
31111         /**
31112          * Get holes property.
31113          * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
31114          */
31115         get: function () {
31116             return this._holes;
31117         },
31118         enumerable: true,
31119         configurable: true
31120     });
31121     /**
31122      * Add a vertex to the polygon by appending it after the last vertex.
31123      *
31124      * @param {Array<number>} vertex - Vertex to add.
31125      * @ignore
31126      */
31127     PolygonGeometry.prototype.addVertex2d = function (vertex) {
31128         var clamped = [
31129             Math.max(0, Math.min(1, vertex[0])),
31130             Math.max(0, Math.min(1, vertex[1])),
31131         ];
31132         this._polygon.splice(this._polygon.length - 1, 0, clamped);
31133         this._notifyChanged$.next(this);
31134     };
31135     /**
31136      * Get the coordinates of a vertex from the polygon representation of the geometry.
31137      *
31138      * @description The first vertex represents the bottom-left corner with the rest of
31139      * the vertices following in clockwise order.
31140      *
31141      * @param {number} index - Vertex index.
31142      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
31143      * @ignore
31144      */
31145     PolygonGeometry.prototype.getVertex2d = function (index) {
31146         return this._polygon[index].slice();
31147     };
31148     /**
31149      * Remove a vertex from the polygon.
31150      *
31151      * @param {number} index - The index of the vertex to remove.
31152      * @ignore
31153      */
31154     PolygonGeometry.prototype.removeVertex2d = function (index) {
31155         if (index < 0 ||
31156             index >= this._polygon.length ||
31157             this._polygon.length < 4) {
31158             throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
31159         }
31160         if (index > 0 && index < this._polygon.length - 1) {
31161             this._polygon.splice(index, 1);
31162         }
31163         else {
31164             this._polygon.splice(0, 1);
31165             this._polygon.pop();
31166             var closing = this._polygon[0].slice();
31167             this._polygon.push(closing);
31168         }
31169         this._notifyChanged$.next(this);
31170     };
31171     /** @ignore */
31172     PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
31173         var changed = [
31174             Math.max(0, Math.min(1, value[0])),
31175             Math.max(0, Math.min(1, value[1])),
31176         ];
31177         if (index === 0 || index === this._polygon.length - 1) {
31178             this._polygon[0] = changed.slice();
31179             this._polygon[this._polygon.length - 1] = changed.slice();
31180         }
31181         else {
31182             this._polygon[index] = changed.slice();
31183         }
31184         this._notifyChanged$.next(this);
31185     };
31186     /** @ignore */
31187     PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
31188         var xs = this._polygon.map(function (point) { return point[0]; });
31189         var ys = this._polygon.map(function (point) { return point[1]; });
31190         var minX = Math.min.apply(Math, xs);
31191         var maxX = Math.max.apply(Math, xs);
31192         var minY = Math.min.apply(Math, ys);
31193         var maxY = Math.max.apply(Math, ys);
31194         var centroid = this.getCentroid2d();
31195         var minTranslationX = -minX;
31196         var maxTranslationX = 1 - maxX;
31197         var minTranslationY = -minY;
31198         var maxTranslationY = 1 - maxY;
31199         var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
31200         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
31201         for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
31202             var point = _a[_i];
31203             point[0] += translationX;
31204             point[1] += translationY;
31205         }
31206         this._notifyChanged$.next(this);
31207     };
31208     /** @ignore */
31209     PolygonGeometry.prototype.getPoints3d = function (transform) {
31210         return this._getPoints3d(this._subsample(this._polygon, this._subsampleThreshold), transform);
31211     };
31212     /** @ignore */
31213     PolygonGeometry.prototype.getVertex3d = function (index, transform) {
31214         return transform.unprojectBasic(this._polygon[index], 200);
31215     };
31216     /** @ignore */
31217     PolygonGeometry.prototype.getVertices2d = function () {
31218         return this._polygon.slice();
31219     };
31220     /** @ignore */
31221     PolygonGeometry.prototype.getVertices3d = function (transform) {
31222         return this._getPoints3d(this._polygon, transform);
31223     };
31224     /**
31225      * Get a polygon representation of the 3D coordinates for the vertices of each hole
31226      * of the geometry. Line segments between vertices will possibly be subsampled
31227      * resulting in a larger number of points than the total number of vertices.
31228      *
31229      * @param {Transform} transform - The transform of the node related to the geometry.
31230      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
31231      * representing the vertices of each hole of the geometry.
31232      * @ignore
31233      */
31234     PolygonGeometry.prototype.getHolePoints3d = function (transform) {
31235         var _this = this;
31236         return this._holes
31237             .map(function (hole2d) {
31238             return _this._getPoints3d(_this._subsample(hole2d, _this._subsampleThreshold), transform);
31239         });
31240     };
31241     /**
31242      * Get a polygon representation of the 3D coordinates for the vertices of each hole
31243      * of the geometry.
31244      *
31245      * @param {Transform} transform - The transform of the node related to the geometry.
31246      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
31247      * representing the vertices of each hole of the geometry.
31248      * @ignore
31249      */
31250     PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
31251         var _this = this;
31252         return this._holes
31253             .map(function (hole2d) {
31254             return _this._getPoints3d(hole2d, transform);
31255         });
31256     };
31257     /** @ignore */
31258     PolygonGeometry.prototype.getCentroid2d = function () {
31259         var polygon = this._polygon;
31260         var area = 0;
31261         var centroidX = 0;
31262         var centroidY = 0;
31263         for (var i = 0; i < polygon.length - 1; i++) {
31264             var xi = polygon[i][0];
31265             var yi = polygon[i][1];
31266             var xi1 = polygon[i + 1][0];
31267             var yi1 = polygon[i + 1][1];
31268             var a = xi * yi1 - xi1 * yi;
31269             area += a;
31270             centroidX += (xi + xi1) * a;
31271             centroidY += (yi + yi1) * a;
31272         }
31273         area /= 2;
31274         centroidX /= 6 * area;
31275         centroidY /= 6 * area;
31276         return [centroidX, centroidY];
31277     };
31278     /** @ignore */
31279     PolygonGeometry.prototype.getCentroid3d = function (transform) {
31280         var centroid2d = this.getCentroid2d();
31281         return transform.unprojectBasic(centroid2d, 200);
31282     };
31283     /** @ignore */
31284     PolygonGeometry.prototype.get3dDomainTriangles3d = function (transform) {
31285         var _this = this;
31286         return this._triangulate(this._project(this._polygon, transform), this.getVertices3d(transform), this._holes
31287             .map(function (hole2d) {
31288             return _this._project(hole2d, transform);
31289         }), this.getHoleVertices3d(transform));
31290     };
31291     /** @ignore */
31292     PolygonGeometry.prototype.getTriangles3d = function (transform) {
31293         var _this = this;
31294         var threshold = this._subsampleThreshold;
31295         var points2d = this._project(this._subsample(this._polygon, threshold), transform);
31296         var points3d = this.getPoints3d(transform);
31297         var holes2d = this._holes
31298             .map(function (hole) {
31299             return _this._project(_this._subsample(hole, threshold), transform);
31300         });
31301         var holes3d = this.getHolePoints3d(transform);
31302         return this._triangulate(points2d, points3d, holes2d, holes3d);
31303     };
31304     /** @ignore */
31305     PolygonGeometry.prototype.getPoleOfInaccessibility2d = function () {
31306         return this._getPoleOfInaccessibility2d(this._polygon.slice());
31307     };
31308     /** @ignore */
31309     PolygonGeometry.prototype.getPoleOfInaccessibility3d = function (transform) {
31310         var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice());
31311         return transform.unprojectBasic(pole2d, 200);
31312     };
31313     PolygonGeometry.prototype._getPoints3d = function (points2d, transform) {
31314         return points2d
31315             .map(function (point) {
31316             return transform.unprojectBasic(point, 200);
31317         });
31318     };
31319     PolygonGeometry.prototype._subsample = function (points2d, threshold) {
31320         var subsampled = [];
31321         var length = points2d.length;
31322         for (var index = 0; index < length; index++) {
31323             var p1 = points2d[index];
31324             var p2 = points2d[(index + 1) % length];
31325             subsampled.push(p1);
31326             var dist = Math.sqrt(Math.pow((p2[0] - p1[0]), 2) + Math.pow((p2[1] - p1[1]), 2));
31327             var subsamples = Math.floor(dist / threshold);
31328             var coeff = 1 / (subsamples + 1);
31329             for (var i = 1; i <= subsamples; i++) {
31330                 var alpha = i * coeff;
31331                 var subsample = [
31332                     (1 - alpha) * p1[0] + alpha * p2[0],
31333                     (1 - alpha) * p1[1] + alpha * p2[1],
31334                 ];
31335                 subsampled.push(subsample);
31336             }
31337         }
31338         return subsampled;
31339     };
31340     return PolygonGeometry;
31341 }(Component_1.VertexGeometry));
31342 exports.PolygonGeometry = PolygonGeometry;
31343 exports.default = PolygonGeometry;
31344
31345 },{"../../../Component":274}],354:[function(require,module,exports){
31346 "use strict";
31347 var __extends = (this && this.__extends) || (function () {
31348     var extendStatics = function (d, b) {
31349         extendStatics = Object.setPrototypeOf ||
31350             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31351             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31352         return extendStatics(d, b);
31353     }
31354     return function (d, b) {
31355         extendStatics(d, b);
31356         function __() { this.constructor = d; }
31357         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31358     };
31359 })();
31360 Object.defineProperty(exports, "__esModule", { value: true });
31361 var Component_1 = require("../../../Component");
31362 /**
31363  * @class RectGeometry
31364  *
31365  * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system.
31366  *
31367  * @example
31368  * ```
31369  * var basicRect = [0.5, 0.3, 0.7, 0.4];
31370  * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect);
31371  * ```
31372  */
31373 var RectGeometry = /** @class */ (function (_super) {
31374     __extends(RectGeometry, _super);
31375     /**
31376      * Create a rectangle geometry.
31377      *
31378      * @constructor
31379      * @param {Array<number>} rect - An array representing the top-left and bottom-right
31380      * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
31381      *
31382      * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
31383      */
31384     function RectGeometry(rect) {
31385         var _this = _super.call(this) || this;
31386         if (rect[1] > rect[3]) {
31387             throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
31388         }
31389         for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
31390             var coord = rect_1[_i];
31391             if (coord < 0 || coord > 1) {
31392                 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
31393             }
31394         }
31395         _this._anchorIndex = undefined;
31396         _this._rect = rect.slice(0, 4);
31397         _this._inverted = _this._rect[0] > _this._rect[2];
31398         return _this;
31399     }
31400     Object.defineProperty(RectGeometry.prototype, "anchorIndex", {
31401         /**
31402          * Get anchor index property.
31403          *
31404          * @returns {number} Index representing the current anchor property if
31405          * achoring indexing has been initialized. If anchor indexing has not been
31406          * initialized or has been terminated undefined will be returned.
31407          * @ignore
31408          */
31409         get: function () {
31410             return this._anchorIndex;
31411         },
31412         enumerable: true,
31413         configurable: true
31414     });
31415     Object.defineProperty(RectGeometry.prototype, "inverted", {
31416         /**
31417          * Get inverted property.
31418          *
31419          * @returns {boolean} Boolean determining whether the rect geometry is
31420          * inverted. For panoramas the rect geometrye may be inverted.
31421          * @ignore
31422          */
31423         get: function () {
31424             return this._inverted;
31425         },
31426         enumerable: true,
31427         configurable: true
31428     });
31429     Object.defineProperty(RectGeometry.prototype, "rect", {
31430         /**
31431          * Get rect property.
31432          *
31433          * @returns {Array<number>} Array representing the top-left and bottom-right
31434          * corners of the rectangle in basic coordinates.
31435          */
31436         get: function () {
31437             return this._rect;
31438         },
31439         enumerable: true,
31440         configurable: true
31441     });
31442     /**
31443      * Initialize anchor indexing to enable setting opposite vertex.
31444      *
31445      * @param {number} [index] - The index of the vertex to use as anchor.
31446      *
31447      * @throws {Error} If anchor indexing has already been initialized.
31448      * @throws {Error} If index is not valid (0 to 3).
31449      * @ignore
31450      */
31451     RectGeometry.prototype.initializeAnchorIndexing = function (index) {
31452         if (this._anchorIndex !== undefined) {
31453             throw new Error("Anchor indexing is already initialized.");
31454         }
31455         if (index < 0 || index > 3) {
31456             throw new Error("Invalid anchor index: " + index + ".");
31457         }
31458         this._anchorIndex = index === undefined ? 0 : index;
31459     };
31460     /**
31461      * Terminate anchor indexing to disable setting pposite vertex.
31462      * @ignore
31463      */
31464     RectGeometry.prototype.terminateAnchorIndexing = function () {
31465         this._anchorIndex = undefined;
31466     };
31467     /**
31468      * Set the value of the vertex opposite to the anchor in the polygon
31469      * representation of the rectangle.
31470      *
31471      * @description Setting the opposite vertex may change the anchor index.
31472      *
31473      * @param {Array<number>} opposite - The new value of the vertex opposite to the anchor.
31474      * @param {Transform} transform - The transform of the node related to the rectangle.
31475      *
31476      * @throws {Error} When anchor indexing has not been initialized.
31477      * @ignore
31478      */
31479     RectGeometry.prototype.setOppositeVertex2d = function (opposite, transform) {
31480         if (this._anchorIndex === undefined) {
31481             throw new Error("Anchor indexing needs to be initialized.");
31482         }
31483         var changed = [
31484             Math.max(0, Math.min(1, opposite[0])),
31485             Math.max(0, Math.min(1, opposite[1])),
31486         ];
31487         var original = this._rect.slice();
31488         var anchor = this._anchorIndex === 0 ? [original[0], original[3]] :
31489             this._anchorIndex === 1 ? [original[0], original[1]] :
31490                 this._anchorIndex === 2 ? [original[2], original[1]] :
31491                     [original[2], original[3]];
31492         if (transform.fullPano) {
31493             var deltaX = this._anchorIndex < 2 ?
31494                 changed[0] - original[2] :
31495                 changed[0] - original[0];
31496             if (!this._inverted && this._anchorIndex < 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
31497                 // right side passes boundary rightward
31498                 this._inverted = true;
31499                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31500             }
31501             else if (!this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
31502                 // left side passes right side and boundary rightward
31503                 this._inverted = true;
31504                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31505             }
31506             else if (this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[0] > 0.75 && deltaX < -0.5) {
31507                 this._inverted = false;
31508                 if (anchor[0] > changed[0]) {
31509                     // left side passes boundary rightward
31510                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31511                 }
31512                 else {
31513                     // left side passes right side and boundary rightward
31514                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31515                 }
31516             }
31517             else if (!this._inverted && this._anchorIndex >= 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
31518                 // left side passes boundary leftward
31519                 this._inverted = true;
31520                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31521             }
31522             else if (!this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
31523                 // right side passes left side and boundary leftward
31524                 this._inverted = true;
31525                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31526             }
31527             else if (this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[2] < 0.25 && deltaX > 0.5) {
31528                 this._inverted = false;
31529                 if (anchor[0] > changed[0]) {
31530                     // right side passes boundary leftward
31531                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31532                 }
31533                 else {
31534                     // right side passes left side and boundary leftward
31535                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31536                 }
31537             }
31538             else if (this._inverted && this._anchorIndex < 2 && changed[0] > original[0]) {
31539                 // inverted and right side passes left side completing a loop
31540                 this._inverted = false;
31541                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31542             }
31543             else if (this._inverted && this._anchorIndex >= 2 && changed[0] < original[2]) {
31544                 // inverted and left side passes right side completing a loop
31545                 this._inverted = false;
31546                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31547             }
31548             else if (this._inverted) {
31549                 // if still inverted only top and bottom can switch
31550                 if (this._anchorIndex < 2) {
31551                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
31552                 }
31553                 else {
31554                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
31555                 }
31556             }
31557             else {
31558                 // if still not inverted treat as non full pano
31559                 if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
31560                     this._anchorIndex = 0;
31561                 }
31562                 else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
31563                     this._anchorIndex = 1;
31564                 }
31565                 else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
31566                     this._anchorIndex = 2;
31567                 }
31568                 else {
31569                     this._anchorIndex = 3;
31570                 }
31571             }
31572             var rect = [];
31573             if (this._anchorIndex === 0) {
31574                 rect[0] = anchor[0];
31575                 rect[1] = changed[1];
31576                 rect[2] = changed[0];
31577                 rect[3] = anchor[1];
31578             }
31579             else if (this._anchorIndex === 1) {
31580                 rect[0] = anchor[0];
31581                 rect[1] = anchor[1];
31582                 rect[2] = changed[0];
31583                 rect[3] = changed[1];
31584             }
31585             else if (this._anchorIndex === 2) {
31586                 rect[0] = changed[0];
31587                 rect[1] = anchor[1];
31588                 rect[2] = anchor[0];
31589                 rect[3] = changed[1];
31590             }
31591             else {
31592                 rect[0] = changed[0];
31593                 rect[1] = changed[1];
31594                 rect[2] = anchor[0];
31595                 rect[3] = anchor[1];
31596             }
31597             if (!this._inverted && rect[0] > rect[2] ||
31598                 this._inverted && rect[0] < rect[2]) {
31599                 rect[0] = original[0];
31600                 rect[2] = original[2];
31601             }
31602             if (rect[1] > rect[3]) {
31603                 rect[1] = original[1];
31604                 rect[3] = original[3];
31605             }
31606             this._rect[0] = rect[0];
31607             this._rect[1] = rect[1];
31608             this._rect[2] = rect[2];
31609             this._rect[3] = rect[3];
31610         }
31611         else {
31612             if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
31613                 this._anchorIndex = 0;
31614             }
31615             else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
31616                 this._anchorIndex = 1;
31617             }
31618             else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
31619                 this._anchorIndex = 2;
31620             }
31621             else {
31622                 this._anchorIndex = 3;
31623             }
31624             var rect = [];
31625             if (this._anchorIndex === 0) {
31626                 rect[0] = anchor[0];
31627                 rect[1] = changed[1];
31628                 rect[2] = changed[0];
31629                 rect[3] = anchor[1];
31630             }
31631             else if (this._anchorIndex === 1) {
31632                 rect[0] = anchor[0];
31633                 rect[1] = anchor[1];
31634                 rect[2] = changed[0];
31635                 rect[3] = changed[1];
31636             }
31637             else if (this._anchorIndex === 2) {
31638                 rect[0] = changed[0];
31639                 rect[1] = anchor[1];
31640                 rect[2] = anchor[0];
31641                 rect[3] = changed[1];
31642             }
31643             else {
31644                 rect[0] = changed[0];
31645                 rect[1] = changed[1];
31646                 rect[2] = anchor[0];
31647                 rect[3] = anchor[1];
31648             }
31649             if (rect[0] > rect[2]) {
31650                 rect[0] = original[0];
31651                 rect[2] = original[2];
31652             }
31653             if (rect[1] > rect[3]) {
31654                 rect[1] = original[1];
31655                 rect[3] = original[3];
31656             }
31657             this._rect[0] = rect[0];
31658             this._rect[1] = rect[1];
31659             this._rect[2] = rect[2];
31660             this._rect[3] = rect[3];
31661         }
31662         this._notifyChanged$.next(this);
31663     };
31664     /**
31665      * Set the value of a vertex in the polygon representation of the rectangle.
31666      *
31667      * @description The polygon is defined to have the first vertex at the
31668      * bottom-left corner with the rest of the vertices following in clockwise order.
31669      *
31670      * @param {number} index - The index of the vertex to be set.
31671      * @param {Array<number>} value - The new value of the vertex.
31672      * @param {Transform} transform - The transform of the node related to the rectangle.
31673      * @ignore
31674      */
31675     RectGeometry.prototype.setVertex2d = function (index, value, transform) {
31676         var original = this._rect.slice();
31677         var changed = [
31678             Math.max(0, Math.min(1, value[0])),
31679             Math.max(0, Math.min(1, value[1])),
31680         ];
31681         var rect = [];
31682         if (index === 0) {
31683             rect[0] = changed[0];
31684             rect[1] = original[1];
31685             rect[2] = original[2];
31686             rect[3] = changed[1];
31687         }
31688         else if (index === 1) {
31689             rect[0] = changed[0];
31690             rect[1] = changed[1];
31691             rect[2] = original[2];
31692             rect[3] = original[3];
31693         }
31694         else if (index === 2) {
31695             rect[0] = original[0];
31696             rect[1] = changed[1];
31697             rect[2] = changed[0];
31698             rect[3] = original[3];
31699         }
31700         else if (index === 3) {
31701             rect[0] = original[0];
31702             rect[1] = original[1];
31703             rect[2] = changed[0];
31704             rect[3] = changed[1];
31705         }
31706         if (transform.fullPano) {
31707             var passingBoundaryLeftward = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
31708                 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
31709             var passingBoundaryRightward = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
31710                 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
31711             if (passingBoundaryLeftward || passingBoundaryRightward) {
31712                 this._inverted = !this._inverted;
31713             }
31714             else {
31715                 if (rect[0] - original[0] < -0.25) {
31716                     rect[0] = original[0];
31717                 }
31718                 if (rect[2] - original[2] > 0.25) {
31719                     rect[2] = original[2];
31720                 }
31721             }
31722             if (!this._inverted && rect[0] > rect[2] ||
31723                 this._inverted && rect[0] < rect[2]) {
31724                 rect[0] = original[0];
31725                 rect[2] = original[2];
31726             }
31727         }
31728         else {
31729             if (rect[0] > rect[2]) {
31730                 rect[0] = original[0];
31731                 rect[2] = original[2];
31732             }
31733         }
31734         if (rect[1] > rect[3]) {
31735             rect[1] = original[1];
31736             rect[3] = original[3];
31737         }
31738         this._rect[0] = rect[0];
31739         this._rect[1] = rect[1];
31740         this._rect[2] = rect[2];
31741         this._rect[3] = rect[3];
31742         this._notifyChanged$.next(this);
31743     };
31744     /** @ignore */
31745     RectGeometry.prototype.setCentroid2d = function (value, transform) {
31746         var original = this._rect.slice();
31747         var x0 = original[0];
31748         var x1 = this._inverted ? original[2] + 1 : original[2];
31749         var y0 = original[1];
31750         var y1 = original[3];
31751         var centerX = x0 + (x1 - x0) / 2;
31752         var centerY = y0 + (y1 - y0) / 2;
31753         var translationX = 0;
31754         if (transform.gpano != null &&
31755             transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
31756             translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
31757         }
31758         else {
31759             var minTranslationX = -x0;
31760             var maxTranslationX = 1 - x1;
31761             translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
31762         }
31763         var minTranslationY = -y0;
31764         var maxTranslationY = 1 - y1;
31765         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
31766         this._rect[0] = original[0] + translationX;
31767         this._rect[1] = original[1] + translationY;
31768         this._rect[2] = original[2] + translationX;
31769         this._rect[3] = original[3] + translationY;
31770         if (this._rect[0] < 0) {
31771             this._rect[0] += 1;
31772             this._inverted = !this._inverted;
31773         }
31774         else if (this._rect[0] > 1) {
31775             this._rect[0] -= 1;
31776             this._inverted = !this._inverted;
31777         }
31778         if (this._rect[2] < 0) {
31779             this._rect[2] += 1;
31780             this._inverted = !this._inverted;
31781         }
31782         else if (this._rect[2] > 1) {
31783             this._rect[2] -= 1;
31784             this._inverted = !this._inverted;
31785         }
31786         this._notifyChanged$.next(this);
31787     };
31788     /**
31789      * Get the 3D coordinates for the vertices of the rectangle with
31790      * interpolated points along the lines.
31791      *
31792      * @param {Transform} transform - The transform of the node related to
31793      * the rectangle.
31794      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
31795      * representing the rectangle.
31796      * @ignore
31797      */
31798     RectGeometry.prototype.getPoints3d = function (transform) {
31799         return this._getPoints2d()
31800             .map(function (point) {
31801             return transform.unprojectBasic(point, 200);
31802         });
31803     };
31804     /**
31805      * Get the coordinates of a vertex from the polygon representation of the geometry.
31806      *
31807      * @description The first vertex represents the bottom-left corner with the rest of
31808      * the vertices following in clockwise order. The method shifts the right side
31809      * coordinates of the rectangle by one unit to ensure that the vertices are ordered
31810      * clockwise.
31811      *
31812      * @param {number} index - Vertex index.
31813      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
31814      * @ignore
31815      */
31816     RectGeometry.prototype.getVertex2d = function (index) {
31817         return this._rectToVertices2d(this._rect)[index];
31818     };
31819     /**
31820      * Get the coordinates of a vertex from the polygon representation of the geometry.
31821      *
31822      * @description The first vertex represents the bottom-left corner with the rest of
31823      * the vertices following in clockwise order. The coordinates will not be shifted
31824      * so they may not appear in clockwise order when layed out on the plane.
31825      *
31826      * @param {number} index - Vertex index.
31827      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
31828      * @ignore
31829      */
31830     RectGeometry.prototype.getNonAdjustedVertex2d = function (index) {
31831         return this._rectToNonAdjustedVertices2d(this._rect)[index];
31832     };
31833     /**
31834      * Get a vertex from the polygon representation of the 3D coordinates for the
31835      * vertices of the geometry.
31836      *
31837      * @description The first vertex represents the bottom-left corner with the rest of
31838      * the vertices following in clockwise order.
31839      *
31840      * @param {number} index - Vertex index.
31841      * @param {Transform} transform - The transform of the node related to the geometry.
31842      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
31843      * the vertices of the geometry.
31844      * @ignore
31845      */
31846     RectGeometry.prototype.getVertex3d = function (index, transform) {
31847         return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
31848     };
31849     /**
31850      * Get a polygon representation of the 2D basic coordinates for the vertices of the rectangle.
31851      *
31852      * @description The first vertex represents the bottom-left corner with the rest of
31853      * the vertices following in clockwise order.
31854      *
31855      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates representing
31856      * the rectangle vertices.
31857      * @ignore
31858      */
31859     RectGeometry.prototype.getVertices2d = function () {
31860         return this._rectToVertices2d(this._rect);
31861     };
31862     /**
31863      * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
31864      *
31865      * @description The first vertex represents the bottom-left corner with the rest of
31866      * the vertices following in clockwise order.
31867      *
31868      * @param {Transform} transform - The transform of the node related to the rectangle.
31869      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
31870      * the rectangle vertices.
31871      * @ignore
31872      */
31873     RectGeometry.prototype.getVertices3d = function (transform) {
31874         return this._rectToVertices2d(this._rect)
31875             .map(function (vertex) {
31876             return transform.unprojectBasic(vertex, 200);
31877         });
31878     };
31879     /** @ignore */
31880     RectGeometry.prototype.getCentroid2d = function () {
31881         var rect = this._rect;
31882         var x0 = rect[0];
31883         var x1 = this._inverted ? rect[2] + 1 : rect[2];
31884         var y0 = rect[1];
31885         var y1 = rect[3];
31886         var centroidX = (x0 + x1) / 2;
31887         var centroidY = (y0 + y1) / 2;
31888         return [centroidX, centroidY];
31889     };
31890     /** @ignore */
31891     RectGeometry.prototype.getCentroid3d = function (transform) {
31892         var centroid2d = this.getCentroid2d();
31893         return transform.unprojectBasic(centroid2d, 200);
31894     };
31895     /**
31896      * @ignore
31897      */
31898     RectGeometry.prototype.getPoleOfInaccessibility2d = function () {
31899         return this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
31900     };
31901     /** @ignore */
31902     RectGeometry.prototype.getPoleOfInaccessibility3d = function (transform) {
31903         var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
31904         return transform.unprojectBasic(pole2d, 200);
31905     };
31906     /** @ignore */
31907     RectGeometry.prototype.getTriangles3d = function (transform) {
31908         return this._triangulate(this._project(this._getPoints2d(), transform), this.getPoints3d(transform));
31909     };
31910     /**
31911      * Check if a particular bottom-right value is valid according to the current
31912      * rectangle coordinates.
31913      *
31914      * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
31915      * @returns {boolean} Value indicating whether the provided bottom-right coordinates
31916      * are valid.
31917      * @ignore
31918      */
31919     RectGeometry.prototype.validate = function (bottomRight) {
31920         var rect = this._rect;
31921         if (!this._inverted && bottomRight[0] < rect[0] ||
31922             bottomRight[0] - rect[2] > 0.25 ||
31923             bottomRight[1] < rect[1]) {
31924             return false;
31925         }
31926         return true;
31927     };
31928     /**
31929      * Get the 2D coordinates for the vertices of the rectangle with
31930      * interpolated points along the lines.
31931      *
31932      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
31933      * representing the rectangle.
31934      */
31935     RectGeometry.prototype._getPoints2d = function () {
31936         var vertices2d = this._rectToVertices2d(this._rect);
31937         var sides = vertices2d.length - 1;
31938         var sections = 10;
31939         var points2d = [];
31940         for (var i = 0; i < sides; ++i) {
31941             var startX = vertices2d[i][0];
31942             var startY = vertices2d[i][1];
31943             var endX = vertices2d[i + 1][0];
31944             var endY = vertices2d[i + 1][1];
31945             var intervalX = (endX - startX) / (sections - 1);
31946             var intervalY = (endY - startY) / (sections - 1);
31947             for (var j = 0; j < sections; ++j) {
31948                 var point = [
31949                     startX + j * intervalX,
31950                     startY + j * intervalY,
31951                 ];
31952                 points2d.push(point);
31953             }
31954         }
31955         return points2d;
31956     };
31957     /**
31958      * Convert the top-left, bottom-right representation of a rectangle to a polygon
31959      * representation of the vertices starting at the bottom-left corner going
31960      * clockwise.
31961      *
31962      * @description The method shifts the right side coordinates of the rectangle
31963      * by one unit to ensure that the vertices are ordered clockwise.
31964      *
31965      * @param {Array<number>} rect - Top-left, bottom-right representation of a
31966      * rectangle.
31967      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
31968      * rectangle.
31969      */
31970     RectGeometry.prototype._rectToVertices2d = function (rect) {
31971         return [
31972             [rect[0], rect[3]],
31973             [rect[0], rect[1]],
31974             [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
31975             [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
31976             [rect[0], rect[3]],
31977         ];
31978     };
31979     /**
31980      * Convert the top-left, bottom-right representation of a rectangle to a polygon
31981      * representation of the vertices starting at the bottom-left corner going
31982      * clockwise.
31983      *
31984      * @description The first vertex represents the bottom-left corner with the rest of
31985      * the vertices following in clockwise order. The coordinates will not be shifted
31986      * to ensure that the vertices are ordered clockwise when layed out on the plane.
31987      *
31988      * @param {Array<number>} rect - Top-left, bottom-right representation of a
31989      * rectangle.
31990      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
31991      * rectangle.
31992      */
31993     RectGeometry.prototype._rectToNonAdjustedVertices2d = function (rect) {
31994         return [
31995             [rect[0], rect[3]],
31996             [rect[0], rect[1]],
31997             [rect[2], rect[1]],
31998             [rect[2], rect[3]],
31999             [rect[0], rect[3]],
32000         ];
32001     };
32002     return RectGeometry;
32003 }(Component_1.VertexGeometry));
32004 exports.RectGeometry = RectGeometry;
32005 exports.default = RectGeometry;
32006
32007 },{"../../../Component":274}],355:[function(require,module,exports){
32008 "use strict";
32009 var __extends = (this && this.__extends) || (function () {
32010     var extendStatics = function (d, b) {
32011         extendStatics = Object.setPrototypeOf ||
32012             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32013             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32014         return extendStatics(d, b);
32015     }
32016     return function (d, b) {
32017         extendStatics(d, b);
32018         function __() { this.constructor = d; }
32019         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32020     };
32021 })();
32022 Object.defineProperty(exports, "__esModule", { value: true });
32023 var earcut_1 = require("earcut");
32024 var polylabel = require("@mapbox/polylabel");
32025 var THREE = require("three");
32026 var Component_1 = require("../../../Component");
32027 /**
32028  * @class VertexGeometry
32029  * @abstract
32030  * @classdesc Represents a vertex geometry.
32031  */
32032 var VertexGeometry = /** @class */ (function (_super) {
32033     __extends(VertexGeometry, _super);
32034     /**
32035      * Create a vertex geometry.
32036      *
32037      * @constructor
32038      * @ignore
32039      */
32040     function VertexGeometry() {
32041         return _super.call(this) || this;
32042     }
32043     /**
32044      * Finds the polygon pole of inaccessibility, the most distant internal
32045      * point from the polygon outline.
32046      *
32047      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
32048      * @returns {Array<number>} Point of inaccessibility.
32049      * @ignore
32050      */
32051     VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) {
32052         var pole2d = polylabel([points2d], 3e-2);
32053         return pole2d;
32054     };
32055     /**
32056      * Triangulates a 2d polygon and returns the triangle
32057      * representation as a flattened array of 3d points.
32058      *
32059      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
32060      * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
32061      * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
32062      * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
32063      * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
32064      * @ignore
32065      */
32066     VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
32067         var data = [points2d.slice(0, -1)];
32068         for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
32069             var hole2d = _a[_i];
32070             data.push(hole2d.slice(0, -1));
32071         }
32072         var points = points3d.slice(0, -1);
32073         for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
32074             var hole3d = _c[_b];
32075             points = points.concat(hole3d.slice(0, -1));
32076         }
32077         var flattened = earcut_1.default.flatten(data);
32078         var indices = earcut_1.default(flattened.vertices, flattened.holes, flattened.dimensions);
32079         var triangles = [];
32080         for (var i = 0; i < indices.length; ++i) {
32081             var point = points[indices[i]];
32082             triangles.push(point[0]);
32083             triangles.push(point[1]);
32084             triangles.push(point[2]);
32085         }
32086         return triangles;
32087     };
32088     VertexGeometry.prototype._project = function (points2d, transform) {
32089         var camera = new THREE.Camera();
32090         camera.up.copy(transform.upVector());
32091         camera.position.copy(new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0)));
32092         camera.lookAt(new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10)));
32093         camera.updateMatrix();
32094         camera.updateMatrixWorld(true);
32095         var projected = points2d
32096             .map(function (point2d) {
32097             var pointWorld = transform.unprojectBasic(point2d, 10000);
32098             var pointCamera = new THREE.Vector3(pointWorld[0], pointWorld[1], pointWorld[2])
32099                 .applyMatrix4(camera.matrixWorldInverse);
32100             return [pointCamera.x / pointCamera.z, pointCamera.y / pointCamera.z];
32101         });
32102         return projected;
32103     };
32104     return VertexGeometry;
32105 }(Component_1.Geometry));
32106 exports.VertexGeometry = VertexGeometry;
32107 exports.default = VertexGeometry;
32108
32109 },{"../../../Component":274,"@mapbox/polylabel":1,"earcut":8,"three":225}],356:[function(require,module,exports){
32110 "use strict";
32111 var __extends = (this && this.__extends) || (function () {
32112     var extendStatics = function (d, b) {
32113         extendStatics = Object.setPrototypeOf ||
32114             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32115             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32116         return extendStatics(d, b);
32117     }
32118     return function (d, b) {
32119         extendStatics(d, b);
32120         function __() { this.constructor = d; }
32121         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32122     };
32123 })();
32124 Object.defineProperty(exports, "__esModule", { value: true });
32125 var operators_1 = require("rxjs/operators");
32126 var rxjs_1 = require("rxjs");
32127 var Component_1 = require("../../../Component");
32128 var CreateHandlerBase = /** @class */ (function (_super) {
32129     __extends(CreateHandlerBase, _super);
32130     function CreateHandlerBase(component, container, navigator, viewportCoords, tagCreator) {
32131         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
32132         _this._tagCreator = tagCreator;
32133         _this._geometryCreated$ = new rxjs_1.Subject();
32134         return _this;
32135     }
32136     Object.defineProperty(CreateHandlerBase.prototype, "geometryCreated$", {
32137         get: function () {
32138             return this._geometryCreated$;
32139         },
32140         enumerable: true,
32141         configurable: true
32142     });
32143     CreateHandlerBase.prototype._enable = function () {
32144         this._enableCreate();
32145         this._container.element.classList.add("component-tag-create");
32146     };
32147     CreateHandlerBase.prototype._disable = function () {
32148         this._container.element.classList.remove("component-tag-create");
32149         this._disableCreate();
32150     };
32151     CreateHandlerBase.prototype._validateBasic = function (basic) {
32152         var x = basic[0];
32153         var y = basic[1];
32154         return 0 <= x && x <= 1 && 0 <= y && y <= 1;
32155     };
32156     CreateHandlerBase.prototype._mouseEventToBasic$ = function (mouseEvent$) {
32157         var _this = this;
32158         return mouseEvent$.pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
32159             var event = _a[0], camera = _a[1], transform = _a[2];
32160             return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
32161         }));
32162     };
32163     return CreateHandlerBase;
32164 }(Component_1.TagHandlerBase));
32165 exports.CreateHandlerBase = CreateHandlerBase;
32166 exports.default = CreateHandlerBase;
32167
32168 },{"../../../Component":274,"rxjs":26,"rxjs/operators":224}],357:[function(require,module,exports){
32169 "use strict";
32170 var __extends = (this && this.__extends) || (function () {
32171     var extendStatics = function (d, b) {
32172         extendStatics = Object.setPrototypeOf ||
32173             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32174             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32175         return extendStatics(d, b);
32176     }
32177     return function (d, b) {
32178         extendStatics(d, b);
32179         function __() { this.constructor = d; }
32180         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32181     };
32182 })();
32183 Object.defineProperty(exports, "__esModule", { value: true });
32184 var operators_1 = require("rxjs/operators");
32185 var Component_1 = require("../../../Component");
32186 var CreatePointHandler = /** @class */ (function (_super) {
32187     __extends(CreatePointHandler, _super);
32188     function CreatePointHandler() {
32189         return _super !== null && _super.apply(this, arguments) || this;
32190     }
32191     CreatePointHandler.prototype._enableCreate = function () {
32192         this._container.mouseService.deferPixels(this._name, 4);
32193         this._geometryCreatedSubscription = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).pipe(operators_1.filter(this._validateBasic), operators_1.map(function (basic) {
32194             return new Component_1.PointGeometry(basic);
32195         }))
32196             .subscribe(this._geometryCreated$);
32197     };
32198     CreatePointHandler.prototype._disableCreate = function () {
32199         this._container.mouseService.undeferPixels(this._name);
32200         this._geometryCreatedSubscription.unsubscribe();
32201     };
32202     CreatePointHandler.prototype._getNameExtension = function () {
32203         return "create-point";
32204     };
32205     return CreatePointHandler;
32206 }(Component_1.CreateHandlerBase));
32207 exports.CreatePointHandler = CreatePointHandler;
32208 exports.default = CreatePointHandler;
32209
32210 },{"../../../Component":274,"rxjs/operators":224}],358:[function(require,module,exports){
32211 "use strict";
32212 var __extends = (this && this.__extends) || (function () {
32213     var extendStatics = function (d, b) {
32214         extendStatics = Object.setPrototypeOf ||
32215             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32216             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32217         return extendStatics(d, b);
32218     }
32219     return function (d, b) {
32220         extendStatics(d, b);
32221         function __() { this.constructor = d; }
32222         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32223     };
32224 })();
32225 Object.defineProperty(exports, "__esModule", { value: true });
32226 var Component_1 = require("../../../Component");
32227 var CreatePolygonHandler = /** @class */ (function (_super) {
32228     __extends(CreatePolygonHandler, _super);
32229     function CreatePolygonHandler() {
32230         return _super !== null && _super.apply(this, arguments) || this;
32231     }
32232     CreatePolygonHandler.prototype._addPoint = function (tag, basicPoint) {
32233         tag.addPoint(basicPoint);
32234     };
32235     Object.defineProperty(CreatePolygonHandler.prototype, "_create$", {
32236         get: function () {
32237             return this._tagCreator.createPolygon$;
32238         },
32239         enumerable: true,
32240         configurable: true
32241     });
32242     CreatePolygonHandler.prototype._getNameExtension = function () {
32243         return "create-polygon";
32244     };
32245     CreatePolygonHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
32246         tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basicPoint, transform);
32247     };
32248     return CreatePolygonHandler;
32249 }(Component_1.CreateVertexHandler));
32250 exports.CreatePolygonHandler = CreatePolygonHandler;
32251 exports.default = CreatePolygonHandler;
32252
32253 },{"../../../Component":274}],359:[function(require,module,exports){
32254 "use strict";
32255 var __extends = (this && this.__extends) || (function () {
32256     var extendStatics = function (d, b) {
32257         extendStatics = Object.setPrototypeOf ||
32258             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32259             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32260         return extendStatics(d, b);
32261     }
32262     return function (d, b) {
32263         extendStatics(d, b);
32264         function __() { this.constructor = d; }
32265         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32266     };
32267 })();
32268 Object.defineProperty(exports, "__esModule", { value: true });
32269 var rxjs_1 = require("rxjs");
32270 var operators_1 = require("rxjs/operators");
32271 var Component_1 = require("../../../Component");
32272 var CreateRectDragHandler = /** @class */ (function (_super) {
32273     __extends(CreateRectDragHandler, _super);
32274     function CreateRectDragHandler() {
32275         return _super !== null && _super.apply(this, arguments) || this;
32276     }
32277     CreateRectDragHandler.prototype._enableCreate = function () {
32278         var _this = this;
32279         this._container.mouseService.claimMouse(this._name, 2);
32280         this._deleteSubscription = this._navigator.stateService.currentTransform$.pipe(operators_1.map(function (transform) { return null; }), operators_1.skip(1))
32281             .subscribe(this._tagCreator.delete$);
32282         this._createSubscription = this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDragStart$)).pipe(operators_1.filter(this._validateBasic))
32283             .subscribe(this._tagCreator.createRect$);
32284         this._initializeAnchorIndexingSubscription = this._tagCreator.tag$.pipe(operators_1.filter(function (tag) {
32285             return !!tag;
32286         }))
32287             .subscribe(function (tag) {
32288             tag.geometry.initializeAnchorIndexing();
32289         });
32290         var basicMouse$ = rxjs_1.combineLatest(rxjs_1.merge(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseMove$), this._container.mouseService.filtered$(this._name, this._container.mouseService.domMouseMove$)), this._container.renderService.renderCamera$).pipe(operators_1.withLatestFrom(this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
32291             var _b = _a[0], event = _b[0], camera = _b[1], transform = _a[1];
32292             return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
32293         }));
32294         this._setVertexSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
32295             return !!tag ?
32296                 rxjs_1.combineLatest(rxjs_1.of(tag), basicMouse$, _this._navigator.stateService.currentTransform$) :
32297                 rxjs_1.empty();
32298         }))
32299             .subscribe(function (_a) {
32300             var tag = _a[0], basicPoint = _a[1], transform = _a[2];
32301             tag.geometry.setOppositeVertex2d(basicPoint, transform);
32302         });
32303         var basicMouseDragEnd$ = this._container.mouseService.mouseDragEnd$.pipe(operators_1.withLatestFrom(this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDrag$)).pipe(operators_1.filter(this._validateBasic)), function (event, basicPoint) {
32304             return basicPoint;
32305         }), operators_1.share());
32306         this._addPointSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
32307             return !!tag ?
32308                 rxjs_1.combineLatest(rxjs_1.of(tag), basicMouseDragEnd$) :
32309                 rxjs_1.empty();
32310         }))
32311             .subscribe(function (_a) {
32312             var tag = _a[0], basicPoint = _a[1];
32313             var rectGeometry = tag.geometry;
32314             if (!rectGeometry.validate(basicPoint)) {
32315                 basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
32316             }
32317             tag.addPoint(basicPoint);
32318         });
32319         this._geometryCreatedSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
32320             return !!tag ?
32321                 tag.created$.pipe(operators_1.map(function (t) {
32322                     return t.geometry;
32323                 })) :
32324                 rxjs_1.empty();
32325         }))
32326             .subscribe(this._geometryCreated$);
32327     };
32328     CreateRectDragHandler.prototype._disableCreate = function () {
32329         this._container.mouseService.unclaimMouse(this._name);
32330         this._tagCreator.delete$.next(null);
32331         this._addPointSubscription.unsubscribe();
32332         this._createSubscription.unsubscribe();
32333         this._deleteSubscription.unsubscribe();
32334         this._geometryCreatedSubscription.unsubscribe();
32335         this._initializeAnchorIndexingSubscription.unsubscribe();
32336         this._setVertexSubscription.unsubscribe();
32337     };
32338     CreateRectDragHandler.prototype._getNameExtension = function () {
32339         return "create-rect-drag";
32340     };
32341     return CreateRectDragHandler;
32342 }(Component_1.CreateHandlerBase));
32343 exports.CreateRectDragHandler = CreateRectDragHandler;
32344 exports.default = CreateRectDragHandler;
32345
32346 },{"../../../Component":274,"rxjs":26,"rxjs/operators":224}],360:[function(require,module,exports){
32347 "use strict";
32348 var __extends = (this && this.__extends) || (function () {
32349     var extendStatics = function (d, b) {
32350         extendStatics = Object.setPrototypeOf ||
32351             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32352             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32353         return extendStatics(d, b);
32354     }
32355     return function (d, b) {
32356         extendStatics(d, b);
32357         function __() { this.constructor = d; }
32358         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32359     };
32360 })();
32361 Object.defineProperty(exports, "__esModule", { value: true });
32362 var operators_1 = require("rxjs/operators");
32363 var Component_1 = require("../../../Component");
32364 var CreateRectHandler = /** @class */ (function (_super) {
32365     __extends(CreateRectHandler, _super);
32366     function CreateRectHandler() {
32367         return _super !== null && _super.apply(this, arguments) || this;
32368     }
32369     Object.defineProperty(CreateRectHandler.prototype, "_create$", {
32370         get: function () {
32371             return this._tagCreator.createRect$;
32372         },
32373         enumerable: true,
32374         configurable: true
32375     });
32376     CreateRectHandler.prototype._addPoint = function (tag, basicPoint) {
32377         var rectGeometry = tag.geometry;
32378         if (!rectGeometry.validate(basicPoint)) {
32379             basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
32380         }
32381         tag.addPoint(basicPoint);
32382     };
32383     CreateRectHandler.prototype._enable = function () {
32384         _super.prototype._enable.call(this);
32385         this._initializeAnchorIndexingSubscription = this._tagCreator.tag$.pipe(operators_1.filter(function (tag) {
32386             return !!tag;
32387         }))
32388             .subscribe(function (tag) {
32389             tag.geometry.initializeAnchorIndexing();
32390         });
32391     };
32392     CreateRectHandler.prototype._disable = function () {
32393         _super.prototype._disable.call(this);
32394         this._initializeAnchorIndexingSubscription.unsubscribe();
32395     };
32396     CreateRectHandler.prototype._getNameExtension = function () {
32397         return "create-rect";
32398     };
32399     CreateRectHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
32400         tag.geometry.setOppositeVertex2d(basicPoint, transform);
32401     };
32402     return CreateRectHandler;
32403 }(Component_1.CreateVertexHandler));
32404 exports.CreateRectHandler = CreateRectHandler;
32405 exports.default = CreateRectHandler;
32406
32407 },{"../../../Component":274,"rxjs/operators":224}],361:[function(require,module,exports){
32408 "use strict";
32409 var __extends = (this && this.__extends) || (function () {
32410     var extendStatics = function (d, b) {
32411         extendStatics = Object.setPrototypeOf ||
32412             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32413             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32414         return extendStatics(d, b);
32415     }
32416     return function (d, b) {
32417         extendStatics(d, b);
32418         function __() { this.constructor = d; }
32419         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32420     };
32421 })();
32422 Object.defineProperty(exports, "__esModule", { value: true });
32423 var rxjs_1 = require("rxjs");
32424 var operators_1 = require("rxjs/operators");
32425 var Component_1 = require("../../../Component");
32426 var CreateVertexHandler = /** @class */ (function (_super) {
32427     __extends(CreateVertexHandler, _super);
32428     function CreateVertexHandler() {
32429         return _super !== null && _super.apply(this, arguments) || this;
32430     }
32431     CreateVertexHandler.prototype._enableCreate = function () {
32432         var _this = this;
32433         this._container.mouseService.deferPixels(this._name, 4);
32434         var transformChanged$ = this._navigator.stateService.currentTransform$.pipe(operators_1.map(function (transform) { }), operators_1.publishReplay(1), operators_1.refCount());
32435         this._deleteSubscription = transformChanged$.pipe(operators_1.skip(1))
32436             .subscribe(this._tagCreator.delete$);
32437         var basicClick$ = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).pipe(operators_1.share());
32438         this._createSubscription = transformChanged$.pipe(operators_1.switchMap(function () {
32439             return basicClick$.pipe(operators_1.filter(_this._validateBasic), operators_1.take(1));
32440         }))
32441             .subscribe(this._create$);
32442         this._setVertexSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
32443             return !!tag ?
32444                 rxjs_1.combineLatest(rxjs_1.of(tag), rxjs_1.merge(_this._container.mouseService.mouseMove$, _this._container.mouseService.domMouseMove$), _this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$) :
32445                 rxjs_1.empty();
32446         }))
32447             .subscribe(function (_a) {
32448             var tag = _a[0], event = _a[1], camera = _a[2], transform = _a[3];
32449             var basicPoint = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
32450             _this._setVertex2d(tag, basicPoint, transform);
32451         });
32452         this._addPointSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
32453             return !!tag ?
32454                 rxjs_1.combineLatest(rxjs_1.of(tag), basicClick$) :
32455                 rxjs_1.empty();
32456         }))
32457             .subscribe(function (_a) {
32458             var tag = _a[0], basicPoint = _a[1];
32459             _this._addPoint(tag, basicPoint);
32460         });
32461         this._geometryCreateSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
32462             return !!tag ?
32463                 tag.created$.pipe(operators_1.map(function (t) {
32464                     return t.geometry;
32465                 })) :
32466                 rxjs_1.empty();
32467         }))
32468             .subscribe(this._geometryCreated$);
32469     };
32470     CreateVertexHandler.prototype._disableCreate = function () {
32471         this._container.mouseService.undeferPixels(this._name);
32472         this._tagCreator.delete$.next(null);
32473         this._addPointSubscription.unsubscribe();
32474         this._createSubscription.unsubscribe();
32475         this._deleteSubscription.unsubscribe();
32476         this._geometryCreateSubscription.unsubscribe();
32477         this._setVertexSubscription.unsubscribe();
32478     };
32479     return CreateVertexHandler;
32480 }(Component_1.CreateHandlerBase));
32481 exports.CreateVertexHandler = CreateVertexHandler;
32482 exports.default = CreateVertexHandler;
32483
32484 },{"../../../Component":274,"rxjs":26,"rxjs/operators":224}],362:[function(require,module,exports){
32485 "use strict";
32486 var __extends = (this && this.__extends) || (function () {
32487     var extendStatics = function (d, b) {
32488         extendStatics = Object.setPrototypeOf ||
32489             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32490             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32491         return extendStatics(d, b);
32492     }
32493     return function (d, b) {
32494         extendStatics(d, b);
32495         function __() { this.constructor = d; }
32496         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32497     };
32498 })();
32499 Object.defineProperty(exports, "__esModule", { value: true });
32500 var rxjs_1 = require("rxjs");
32501 var operators_1 = require("rxjs/operators");
32502 var Component_1 = require("../../../Component");
32503 var EditVertexHandler = /** @class */ (function (_super) {
32504     __extends(EditVertexHandler, _super);
32505     function EditVertexHandler(component, container, navigator, viewportCoords, tagSet) {
32506         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
32507         _this._tagSet = tagSet;
32508         return _this;
32509     }
32510     EditVertexHandler.prototype._enable = function () {
32511         var _this = this;
32512         var interaction$ = this._tagSet.changed$.pipe(operators_1.map(function (tagSet) {
32513             return tagSet.getAll();
32514         }), operators_1.switchMap(function (tags) {
32515             return rxjs_1.from(tags).pipe(operators_1.mergeMap(function (tag) {
32516                 return tag.interact$;
32517             }));
32518         }), operators_1.switchMap(function (interaction) {
32519             return rxjs_1.concat(rxjs_1.of(interaction), _this._container.mouseService.documentMouseUp$.pipe(operators_1.map(function () {
32520                 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
32521             }), operators_1.first()));
32522         }), operators_1.share());
32523         var mouseMove$ = rxjs_1.merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$).pipe(operators_1.share());
32524         this._claimMouseSubscription = interaction$.pipe(operators_1.switchMap(function (interaction) {
32525             return !!interaction.tag ? _this._container.mouseService.domMouseDragStart$ : rxjs_1.empty();
32526         }))
32527             .subscribe(function () {
32528             _this._container.mouseService.claimMouse(_this._name, 3);
32529         });
32530         this._cursorSubscription = interaction$.pipe(operators_1.map(function (interaction) {
32531             return interaction.cursor;
32532         }), operators_1.distinctUntilChanged())
32533             .subscribe(function (cursor) {
32534             var interactionCursors = ["crosshair", "move", "nesw-resize", "nwse-resize"];
32535             for (var _i = 0, interactionCursors_1 = interactionCursors; _i < interactionCursors_1.length; _i++) {
32536                 var interactionCursor = interactionCursors_1[_i];
32537                 _this._container.element.classList.remove("component-tag-edit-" + interactionCursor);
32538             }
32539             if (!!cursor) {
32540                 _this._container.element.classList.add("component-tag-edit-" + cursor);
32541             }
32542         });
32543         this._unclaimMouseSubscription = this._container.mouseService
32544             .filtered$(this._name, this._container.mouseService.domMouseDragEnd$)
32545             .subscribe(function (e) {
32546             _this._container.mouseService.unclaimMouse(_this._name);
32547         });
32548         this._preventDefaultSubscription = interaction$.pipe(operators_1.switchMap(function (interaction) {
32549             return !!interaction.tag ?
32550                 _this._container.mouseService.documentMouseMove$ :
32551                 rxjs_1.empty();
32552         }))
32553             .subscribe(function (event) {
32554             event.preventDefault(); // prevent selection of content outside the viewer
32555         });
32556         this._updateGeometrySubscription = interaction$.pipe(operators_1.switchMap(function (interaction) {
32557             if (interaction.operation === Component_1.TagOperation.None || !interaction.tag) {
32558                 return rxjs_1.empty();
32559             }
32560             var mouseDrag$ = _this._container.mouseService
32561                 .filtered$(_this._name, _this._container.mouseService.domMouseDrag$).pipe(operators_1.filter(function (event) {
32562                 return _this._viewportCoords.insideElement(event, _this._container.element);
32563             }));
32564             return rxjs_1.combineLatest(mouseDrag$, _this._container.renderService.renderCamera$).pipe(operators_1.withLatestFrom(rxjs_1.of(interaction), _this._navigator.stateService.currentTransform$, function (_a, i, transform) {
32565                 var event = _a[0], render = _a[1];
32566                 return [event, render, i, transform];
32567             }));
32568         }))
32569             .subscribe(function (_a) {
32570             var mouseEvent = _a[0], renderCamera = _a[1], interaction = _a[2], transform = _a[3];
32571             var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, interaction.offsetX, interaction.offsetY);
32572             var geometry = interaction.tag.geometry;
32573             if (interaction.operation === Component_1.TagOperation.Centroid) {
32574                 geometry.setCentroid2d(basic, transform);
32575             }
32576             else if (interaction.operation === Component_1.TagOperation.Vertex) {
32577                 geometry.setVertex2d(interaction.vertexIndex, basic, transform);
32578             }
32579         });
32580     };
32581     EditVertexHandler.prototype._disable = function () {
32582         this._claimMouseSubscription.unsubscribe();
32583         this._cursorSubscription.unsubscribe();
32584         this._preventDefaultSubscription.unsubscribe();
32585         this._unclaimMouseSubscription.unsubscribe();
32586         this._updateGeometrySubscription.unsubscribe();
32587     };
32588     EditVertexHandler.prototype._getNameExtension = function () {
32589         return "edit-vertex";
32590     };
32591     return EditVertexHandler;
32592 }(Component_1.TagHandlerBase));
32593 exports.EditVertexHandler = EditVertexHandler;
32594 exports.default = EditVertexHandler;
32595
32596
32597 },{"../../../Component":274,"rxjs":26,"rxjs/operators":224}],363:[function(require,module,exports){
32598 "use strict";
32599 var __extends = (this && this.__extends) || (function () {
32600     var extendStatics = function (d, b) {
32601         extendStatics = Object.setPrototypeOf ||
32602             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32603             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32604         return extendStatics(d, b);
32605     }
32606     return function (d, b) {
32607         extendStatics(d, b);
32608         function __() { this.constructor = d; }
32609         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32610     };
32611 })();
32612 Object.defineProperty(exports, "__esModule", { value: true });
32613 var Component_1 = require("../../../Component");
32614 var TagHandlerBase = /** @class */ (function (_super) {
32615     __extends(TagHandlerBase, _super);
32616     function TagHandlerBase(component, container, navigator, viewportCoords) {
32617         var _this = _super.call(this, component, container, navigator) || this;
32618         _this._name = _this._component.name + "-" + _this._getNameExtension();
32619         _this._viewportCoords = viewportCoords;
32620         return _this;
32621     }
32622     TagHandlerBase.prototype._getConfiguration = function (enable) {
32623         return {};
32624     };
32625     TagHandlerBase.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
32626         offsetX = offsetX != null ? offsetX : 0;
32627         offsetY = offsetY != null ? offsetY : 0;
32628         var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
32629         var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
32630         return basic;
32631     };
32632     return TagHandlerBase;
32633 }(Component_1.HandlerBase));
32634 exports.TagHandlerBase = TagHandlerBase;
32635 exports.default = TagHandlerBase;
32636
32637
32638 },{"../../../Component":274}],364:[function(require,module,exports){
32639 "use strict";
32640 Object.defineProperty(exports, "__esModule", { value: true });
32641 var operators_1 = require("rxjs/operators");
32642 var THREE = require("three");
32643 var vd = require("virtual-dom");
32644 var rxjs_1 = require("rxjs");
32645 var Component_1 = require("../../../Component");
32646 var Geo_1 = require("../../../Geo");
32647 var OutlineCreateTag = /** @class */ (function () {
32648     function OutlineCreateTag(geometry, options, transform, viewportCoords) {
32649         var _this = this;
32650         this._geometry = geometry;
32651         this._options = { color: options.color == null ? 0xFFFFFF : options.color };
32652         this._transform = transform;
32653         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
32654         this._outline = this._createOutine();
32655         this._glObjects = [this._outline];
32656         this._aborted$ = new rxjs_1.Subject();
32657         this._created$ = new rxjs_1.Subject();
32658         this._glObjectsChanged$ = new rxjs_1.Subject();
32659         this._geometryChangedSubscription = this._geometry.changed$
32660             .subscribe(function (vertexGeometry) {
32661             _this._disposeOutline();
32662             _this._outline = _this._createOutine();
32663             _this._glObjects = [_this._outline];
32664             _this._glObjectsChanged$.next(_this);
32665         });
32666     }
32667     Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
32668         get: function () {
32669             return this._geometry;
32670         },
32671         enumerable: true,
32672         configurable: true
32673     });
32674     Object.defineProperty(OutlineCreateTag.prototype, "glObjects", {
32675         get: function () {
32676             return this._glObjects;
32677         },
32678         enumerable: true,
32679         configurable: true
32680     });
32681     Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
32682         get: function () {
32683             return this._aborted$;
32684         },
32685         enumerable: true,
32686         configurable: true
32687     });
32688     Object.defineProperty(OutlineCreateTag.prototype, "created$", {
32689         get: function () {
32690             return this._created$;
32691         },
32692         enumerable: true,
32693         configurable: true
32694     });
32695     Object.defineProperty(OutlineCreateTag.prototype, "glObjectsChanged$", {
32696         get: function () {
32697             return this._glObjectsChanged$;
32698         },
32699         enumerable: true,
32700         configurable: true
32701     });
32702     Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
32703         get: function () {
32704             var _this = this;
32705             return this._geometry.changed$.pipe(operators_1.map(function (geometry) {
32706                 return _this;
32707             }));
32708         },
32709         enumerable: true,
32710         configurable: true
32711     });
32712     OutlineCreateTag.prototype.dispose = function () {
32713         this._disposeOutline();
32714         this._geometryChangedSubscription.unsubscribe();
32715     };
32716     OutlineCreateTag.prototype.getDOMObjects = function (camera, size) {
32717         var _this = this;
32718         var vNodes = [];
32719         var container = {
32720             offsetHeight: size.height, offsetWidth: size.width,
32721         };
32722         var abort = function (e) {
32723             e.stopPropagation();
32724             _this._aborted$.next(_this);
32725         };
32726         if (this._geometry instanceof Component_1.RectGeometry) {
32727             var anchorIndex = this._geometry.anchorIndex;
32728             var vertexIndex = anchorIndex === undefined ? 1 : anchorIndex;
32729             var _a = this._geometry.getVertex2d(vertexIndex), basicX = _a[0], basicY = _a[1];
32730             var canvasPoint = this._viewportCoords.basicToCanvasSafe(basicX, basicY, container, this._transform, camera);
32731             if (canvasPoint != null) {
32732                 var background = this._colorToBackground(this._options.color);
32733                 var transform = this._canvasToTransform(canvasPoint);
32734                 var pointProperties = {
32735                     style: { background: background, transform: transform },
32736                 };
32737                 var completerProperties = {
32738                     onclick: abort,
32739                     style: { transform: transform },
32740                 };
32741                 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
32742                 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
32743             }
32744         }
32745         else if (this._geometry instanceof Component_1.PolygonGeometry) {
32746             var polygonGeometry_1 = this._geometry;
32747             var _b = polygonGeometry_1.getVertex2d(0), firstVertexBasicX = _b[0], firstVertexBasicY = _b[1];
32748             var firstVertexCanvas = this._viewportCoords.basicToCanvasSafe(firstVertexBasicX, firstVertexBasicY, container, this._transform, camera);
32749             if (firstVertexCanvas != null) {
32750                 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
32751                     function (e) {
32752                         e.stopPropagation();
32753                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
32754                         _this._created$.next(_this);
32755                     } :
32756                     abort;
32757                 var transform = this._canvasToTransform(firstVertexCanvas);
32758                 var completerProperties = {
32759                     onclick: firstOnclick,
32760                     style: { transform: transform },
32761                 };
32762                 var firstClass = polygonGeometry_1.polygon.length > 4 ?
32763                     "TagCompleter" :
32764                     "TagInteractor";
32765                 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
32766             }
32767             if (polygonGeometry_1.polygon.length > 3) {
32768                 var _c = polygonGeometry_1.getVertex2d(polygonGeometry_1.polygon.length - 3), lastVertexBasicX = _c[0], lastVertexBasicY = _c[1];
32769                 var lastVertexCanvas = this._viewportCoords.basicToCanvasSafe(lastVertexBasicX, lastVertexBasicY, container, this._transform, camera);
32770                 if (lastVertexCanvas != null) {
32771                     var remove = function (e) {
32772                         e.stopPropagation();
32773                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
32774                     };
32775                     var transform = this._canvasToTransform(lastVertexCanvas);
32776                     var completerProperties = {
32777                         onclick: remove,
32778                         style: { transform: transform },
32779                     };
32780                     vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
32781                 }
32782             }
32783             var verticesBasic = polygonGeometry_1.polygon.slice();
32784             verticesBasic.splice(-2, 2);
32785             for (var _i = 0, verticesBasic_1 = verticesBasic; _i < verticesBasic_1.length; _i++) {
32786                 var vertexBasic = verticesBasic_1[_i];
32787                 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasic[0], vertexBasic[1], container, this._transform, camera);
32788                 if (vertexCanvas != null) {
32789                     var background = this._colorToBackground(this._options.color);
32790                     var transform = this._canvasToTransform(vertexCanvas);
32791                     var pointProperties = {
32792                         style: {
32793                             background: background,
32794                             transform: transform,
32795                         },
32796                     };
32797                     vNodes.push(vd.h("div.TagVertex", pointProperties, []));
32798                 }
32799             }
32800         }
32801         return vNodes;
32802     };
32803     OutlineCreateTag.prototype.addPoint = function (point) {
32804         if (this._geometry instanceof Component_1.RectGeometry) {
32805             var rectGeometry = this._geometry;
32806             if (!rectGeometry.validate(point)) {
32807                 return;
32808             }
32809             this._created$.next(this);
32810         }
32811         else if (this._geometry instanceof Component_1.PolygonGeometry) {
32812             var polygonGeometry = this._geometry;
32813             polygonGeometry.addVertex2d(point);
32814         }
32815     };
32816     OutlineCreateTag.prototype._canvasToTransform = function (canvas) {
32817         var canvasX = Math.round(canvas[0]);
32818         var canvasY = Math.round(canvas[1]);
32819         var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
32820         return transform;
32821     };
32822     OutlineCreateTag.prototype._colorToBackground = function (color) {
32823         return "#" + ("000000" + color.toString(16)).substr(-6);
32824     };
32825     OutlineCreateTag.prototype._createOutine = function () {
32826         var polygon3d = this._geometry instanceof Component_1.RectGeometry ?
32827             this._geometry.getPoints3d(this._transform) :
32828             this._geometry.getVertices3d(this._transform);
32829         var positions = this._getLinePositions(polygon3d);
32830         var geometry = new THREE.BufferGeometry();
32831         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
32832         var material = new THREE.LineBasicMaterial({
32833             color: this._options.color,
32834             linewidth: 1,
32835         });
32836         return new THREE.Line(geometry, material);
32837     };
32838     OutlineCreateTag.prototype._disposeOutline = function () {
32839         if (this._outline == null) {
32840             return;
32841         }
32842         var line = this._outline;
32843         line.geometry.dispose();
32844         line.material.dispose();
32845         this._outline = null;
32846         this._glObjects = [];
32847     };
32848     OutlineCreateTag.prototype._getLinePositions = function (polygon3d) {
32849         var length = polygon3d.length;
32850         var positions = new Float32Array(length * 3);
32851         for (var i = 0; i < length; ++i) {
32852             var index = 3 * i;
32853             var position = polygon3d[i];
32854             positions[index] = position[0];
32855             positions[index + 1] = position[1];
32856             positions[index + 2] = position[2];
32857         }
32858         return positions;
32859     };
32860     return OutlineCreateTag;
32861 }());
32862 exports.OutlineCreateTag = OutlineCreateTag;
32863 exports.default = OutlineCreateTag;
32864
32865
32866 },{"../../../Component":274,"../../../Geo":277,"rxjs":26,"rxjs/operators":224,"three":225,"virtual-dom":230}],365:[function(require,module,exports){
32867 "use strict";
32868 var __extends = (this && this.__extends) || (function () {
32869     var extendStatics = function (d, b) {
32870         extendStatics = Object.setPrototypeOf ||
32871             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32872             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32873         return extendStatics(d, b);
32874     }
32875     return function (d, b) {
32876         extendStatics(d, b);
32877         function __() { this.constructor = d; }
32878         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32879     };
32880 })();
32881 Object.defineProperty(exports, "__esModule", { value: true });
32882 var THREE = require("three");
32883 var vd = require("virtual-dom");
32884 var Component_1 = require("../../../Component");
32885 /**
32886  * @class OutlineRenderTag
32887  * @classdesc Tag visualizing the properties of an OutlineTag.
32888  */
32889 var OutlineRenderTag = /** @class */ (function (_super) {
32890     __extends(OutlineRenderTag, _super);
32891     function OutlineRenderTag(tag, transform) {
32892         var _this = _super.call(this, tag, transform) || this;
32893         _this._fill = !transform.gpano ?
32894             _this._createFill() :
32895             null;
32896         _this._holes = _this._tag.lineWidth >= 1 ?
32897             _this._createHoles() :
32898             [];
32899         _this._outline = _this._tag.lineWidth >= 1 ?
32900             _this._createOutline() :
32901             null;
32902         _this._geometryChangedSubscription = _this._tag.geometry.changed$
32903             .subscribe(function (geometry) {
32904             if (_this._fill != null) {
32905                 _this._updateFillGeometry();
32906             }
32907             if (_this._holes.length > 0) {
32908                 _this._updateHoleGeometries();
32909             }
32910             if (_this._outline != null) {
32911                 _this._updateOulineGeometry();
32912             }
32913         });
32914         _this._changedSubscription = _this._tag.changed$
32915             .subscribe(function (changedTag) {
32916             var glObjectsChanged = false;
32917             if (_this._fill != null) {
32918                 _this._updateFillMaterial(_this._fill.material);
32919             }
32920             if (_this._outline == null) {
32921                 if (_this._tag.lineWidth >= 1) {
32922                     _this._holes = _this._createHoles();
32923                     _this._outline = _this._createOutline();
32924                     glObjectsChanged = true;
32925                 }
32926             }
32927             else {
32928                 _this._updateHoleMaterials();
32929                 _this._updateOutlineMaterial();
32930             }
32931             if (glObjectsChanged) {
32932                 _this._glObjectsChanged$.next(_this);
32933             }
32934         });
32935         return _this;
32936     }
32937     OutlineRenderTag.prototype.dispose = function () {
32938         this._disposeFill();
32939         this._disposeHoles();
32940         this._disposeOutline();
32941         this._changedSubscription.unsubscribe();
32942         this._geometryChangedSubscription.unsubscribe();
32943     };
32944     OutlineRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
32945         var _this = this;
32946         var vNodes = [];
32947         var isRect = this._tag.geometry instanceof Component_1.RectGeometry;
32948         var isPerspective = !this._transform.gpano;
32949         var container = {
32950             offsetHeight: size.height, offsetWidth: size.width,
32951         };
32952         if (this._tag.icon != null && (isRect || isPerspective)) {
32953             var _a = this._tag.geometry instanceof Component_1.RectGeometry ?
32954                 this._tag.geometry.getVertex2d(this._tag.iconIndex) :
32955                 this._tag.geometry.getPoleOfInaccessibility2d(), iconBasicX = _a[0], iconBasicY = _a[1];
32956             var iconCanvas = this._viewportCoords.basicToCanvasSafe(iconBasicX, iconBasicY, container, this._transform, camera);
32957             if (iconCanvas != null) {
32958                 var interact = function (e) {
32959                     _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
32960                 };
32961                 if (atlas.loaded) {
32962                     var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat);
32963                     var iconCanvasX = Math.round(iconCanvas[0]);
32964                     var iconCanvasY = Math.round(iconCanvas[1]);
32965                     var transform = "translate(" + iconCanvasX + "px," + iconCanvasY + "px)";
32966                     var click = function (e) {
32967                         e.stopPropagation();
32968                         _this._tag.click$.next(_this._tag);
32969                     };
32970                     var properties = {
32971                         onclick: click,
32972                         onmousedown: interact,
32973                         style: { transform: transform },
32974                     };
32975                     vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
32976                 }
32977             }
32978         }
32979         else if (this._tag.text != null && (isRect || isPerspective)) {
32980             var _b = this._tag.geometry instanceof Component_1.RectGeometry ?
32981                 this._tag.geometry.getVertex2d(3) :
32982                 this._tag.geometry.getPoleOfInaccessibility2d(), textBasicX = _b[0], textBasicY = _b[1];
32983             var textCanvas = this._viewportCoords.basicToCanvasSafe(textBasicX, textBasicY, container, this._transform, camera);
32984             if (textCanvas != null) {
32985                 var textCanvasX = Math.round(textCanvas[0]);
32986                 var textCanvasY = Math.round(textCanvas[1]);
32987                 var transform = this._tag.geometry instanceof Component_1.RectGeometry ?
32988                     "translate(" + textCanvasX + "px," + textCanvasY + "px)" :
32989                     "translate(-50%, -50%) translate(" + textCanvasX + "px," + textCanvasY + "px)";
32990                 var interact = function (e) {
32991                     _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
32992                 };
32993                 var properties = {
32994                     onmousedown: interact,
32995                     style: {
32996                         color: this._colorToCss(this._tag.textColor),
32997                         transform: transform,
32998                     },
32999                     textContent: this._tag.text,
33000                 };
33001                 vNodes.push(vd.h("span.TagSymbol", properties, []));
33002             }
33003         }
33004         if (!this._tag.editable) {
33005             return vNodes;
33006         }
33007         var lineColor = this._colorToCss(this._tag.lineColor);
33008         if (this._tag.geometry instanceof Component_1.RectGeometry) {
33009             var _c = this._tag.geometry.getCentroid2d(), centroidBasicX = _c[0], centroidBasicY = _c[1];
33010             var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
33011             if (centroidCanvas != null) {
33012                 var interact = this._interact(Component_1.TagOperation.Centroid, "move");
33013                 var centroidCanvasX = Math.round(centroidCanvas[0]);
33014                 var centroidCanvasY = Math.round(centroidCanvas[1]);
33015                 var transform = "translate(-50%, -50%) translate(" + centroidCanvasX + "px," + centroidCanvasY + "px)";
33016                 var properties = {
33017                     onmousedown: interact,
33018                     style: { background: lineColor, transform: transform },
33019                 };
33020                 vNodes.push(vd.h("div.TagMover", properties, []));
33021             }
33022         }
33023         var vertices2d = this._tag.geometry.getVertices2d();
33024         for (var i = 0; i < vertices2d.length - 1; i++) {
33025             if (isRect &&
33026                 ((this._tag.icon != null && i === this._tag.iconIndex) ||
33027                     (this._tag.icon == null && this._tag.text != null && i === 3))) {
33028                 continue;
33029             }
33030             var _d = vertices2d[i], vertexBasicX = _d[0], vertexBasicY = _d[1];
33031             var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera);
33032             if (vertexCanvas == null) {
33033                 continue;
33034             }
33035             var cursor = isRect ?
33036                 i % 2 === 0 ? "nesw-resize" : "nwse-resize" :
33037                 "crosshair";
33038             var interact = this._interact(Component_1.TagOperation.Vertex, cursor, i);
33039             var vertexCanvasX = Math.round(vertexCanvas[0]);
33040             var vertexCanvasY = Math.round(vertexCanvas[1]);
33041             var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)";
33042             var properties = {
33043                 onmousedown: interact,
33044                 style: { background: lineColor, transform: transform, cursor: cursor },
33045             };
33046             vNodes.push(vd.h("div.TagResizer", properties, []));
33047             if (!this._tag.indicateVertices) {
33048                 continue;
33049             }
33050             var pointProperties = {
33051                 style: { background: lineColor, transform: transform },
33052             };
33053             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
33054         }
33055         return vNodes;
33056     };
33057     OutlineRenderTag.prototype.getGLObjects = function () {
33058         var glObjects = [];
33059         if (this._fill != null) {
33060             glObjects.push(this._fill);
33061         }
33062         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
33063             var hole = _a[_i];
33064             glObjects.push(hole);
33065         }
33066         if (this._outline != null) {
33067             glObjects.push(this._outline);
33068         }
33069         return glObjects;
33070     };
33071     OutlineRenderTag.prototype.getRetrievableObjects = function () {
33072         return this._fill != null ? [this._fill] : [];
33073     };
33074     OutlineRenderTag.prototype._colorToCss = function (color) {
33075         return "#" + ("000000" + color.toString(16)).substr(-6);
33076     };
33077     OutlineRenderTag.prototype._createFill = function () {
33078         var triangles = this._getTriangles();
33079         var positions = new Float32Array(triangles);
33080         var geometry = new THREE.BufferGeometry();
33081         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
33082         geometry.computeBoundingSphere();
33083         var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true });
33084         this._updateFillMaterial(material);
33085         return new THREE.Mesh(geometry, material);
33086     };
33087     OutlineRenderTag.prototype._createHoles = function () {
33088         var holes = [];
33089         if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
33090             var holes3d = this._getHoles3d();
33091             for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
33092                 var holePoints3d = holes3d_1[_i];
33093                 var hole = this._createLine(holePoints3d);
33094                 holes.push(hole);
33095             }
33096         }
33097         return holes;
33098     };
33099     OutlineRenderTag.prototype._createLine = function (points3d) {
33100         var positions = this._getLinePositions(points3d);
33101         var geometry = new THREE.BufferGeometry();
33102         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
33103         geometry.computeBoundingSphere();
33104         var material = new THREE.LineBasicMaterial();
33105         this._updateLineBasicMaterial(material);
33106         var line = new THREE.Line(geometry, material);
33107         line.renderOrder = 1;
33108         return line;
33109     };
33110     OutlineRenderTag.prototype._createOutline = function () {
33111         return this._createLine(this._getPoints3d());
33112     };
33113     OutlineRenderTag.prototype._disposeFill = function () {
33114         if (this._fill == null) {
33115             return;
33116         }
33117         this._fill.geometry.dispose();
33118         this._fill.material.dispose();
33119         this._fill = null;
33120     };
33121     OutlineRenderTag.prototype._disposeHoles = function () {
33122         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
33123             var hole = _a[_i];
33124             hole.geometry.dispose();
33125             hole.material.dispose();
33126         }
33127         this._holes = [];
33128     };
33129     OutlineRenderTag.prototype._disposeOutline = function () {
33130         if (this._outline == null) {
33131             return;
33132         }
33133         this._outline.geometry.dispose();
33134         this._outline.material.dispose();
33135         this._outline = null;
33136     };
33137     OutlineRenderTag.prototype._getLinePositions = function (points3d) {
33138         var length = points3d.length;
33139         var positions = new Float32Array(length * 3);
33140         for (var i = 0; i < length; ++i) {
33141             var index = 3 * i;
33142             var position = points3d[i];
33143             positions[index + 0] = position[0];
33144             positions[index + 1] = position[1];
33145             positions[index + 2] = position[2];
33146         }
33147         return positions;
33148     };
33149     OutlineRenderTag.prototype._getHoles3d = function () {
33150         var polygonGeometry = this._tag.geometry;
33151         return this._in3dDomain() ?
33152             polygonGeometry.getHoleVertices3d(this._transform) :
33153             polygonGeometry.getHolePoints3d(this._transform);
33154     };
33155     OutlineRenderTag.prototype._getPoints3d = function () {
33156         return this._in3dDomain() ?
33157             this._tag.geometry.getVertices3d(this._transform) :
33158             this._tag.geometry.getPoints3d(this._transform);
33159     };
33160     OutlineRenderTag.prototype._getTriangles = function () {
33161         return this._in3dDomain() ?
33162             this._tag.geometry.get3dDomainTriangles3d(this._transform) :
33163             this._tag.geometry.getTriangles3d(this._transform);
33164     };
33165     OutlineRenderTag.prototype._in3dDomain = function () {
33166         return this._tag.geometry instanceof Component_1.PolygonGeometry && this._tag.domain === Component_1.TagDomain.ThreeDimensional;
33167     };
33168     OutlineRenderTag.prototype._interact = function (operation, cursor, vertexIndex) {
33169         var _this = this;
33170         return function (e) {
33171             var offsetX = e.offsetX - e.target.offsetWidth / 2;
33172             var offsetY = e.offsetY - e.target.offsetHeight / 2;
33173             _this._interact$.next({
33174                 cursor: cursor,
33175                 offsetX: offsetX,
33176                 offsetY: offsetY,
33177                 operation: operation,
33178                 tag: _this._tag,
33179                 vertexIndex: vertexIndex,
33180             });
33181         };
33182     };
33183     OutlineRenderTag.prototype._updateFillGeometry = function () {
33184         var triangles = this._getTriangles();
33185         var positions = new Float32Array(triangles);
33186         var geometry = this._fill.geometry;
33187         var attribute = geometry.getAttribute("position");
33188         if (attribute.array.length === positions.length) {
33189             attribute.set(positions);
33190             attribute.needsUpdate = true;
33191         }
33192         else {
33193             geometry.removeAttribute("position");
33194             geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
33195         }
33196         geometry.computeBoundingSphere();
33197     };
33198     OutlineRenderTag.prototype._updateFillMaterial = function (material) {
33199         material.color = new THREE.Color(this._tag.fillColor);
33200         material.opacity = this._tag.fillOpacity;
33201         material.needsUpdate = true;
33202     };
33203     OutlineRenderTag.prototype._updateHoleGeometries = function () {
33204         var holes3d = this._getHoles3d();
33205         if (holes3d.length !== this._holes.length) {
33206             throw new Error("Changing the number of holes is not supported.");
33207         }
33208         for (var i = 0; i < this._holes.length; i++) {
33209             var holePoints3d = holes3d[i];
33210             var hole = this._holes[i];
33211             this._updateLine(hole, holePoints3d);
33212         }
33213     };
33214     OutlineRenderTag.prototype._updateHoleMaterials = function () {
33215         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
33216             var hole = _a[_i];
33217             var material = hole.material;
33218             this._updateLineBasicMaterial(material);
33219         }
33220     };
33221     OutlineRenderTag.prototype._updateLine = function (line, points3d) {
33222         var positions = this._getLinePositions(points3d);
33223         var geometry = line.geometry;
33224         var attribute = geometry.getAttribute("position");
33225         attribute.set(positions);
33226         attribute.needsUpdate = true;
33227         geometry.computeBoundingSphere();
33228     };
33229     OutlineRenderTag.prototype._updateOulineGeometry = function () {
33230         this._updateLine(this._outline, this._getPoints3d());
33231     };
33232     OutlineRenderTag.prototype._updateOutlineMaterial = function () {
33233         var material = this._outline.material;
33234         this._updateLineBasicMaterial(material);
33235     };
33236     OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
33237         material.color = new THREE.Color(this._tag.lineColor);
33238         material.linewidth = Math.max(this._tag.lineWidth, 1);
33239         material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0;
33240         material.opacity = this._tag.lineOpacity;
33241         material.transparent = this._tag.lineOpacity < 1;
33242         material.needsUpdate = true;
33243     };
33244     return OutlineRenderTag;
33245 }(Component_1.RenderTag));
33246 exports.OutlineRenderTag = OutlineRenderTag;
33247
33248
33249 },{"../../../Component":274,"three":225,"virtual-dom":230}],366:[function(require,module,exports){
33250 "use strict";
33251 var __extends = (this && this.__extends) || (function () {
33252     var extendStatics = function (d, b) {
33253         extendStatics = Object.setPrototypeOf ||
33254             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33255             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33256         return extendStatics(d, b);
33257     }
33258     return function (d, b) {
33259         extendStatics(d, b);
33260         function __() { this.constructor = d; }
33261         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33262     };
33263 })();
33264 Object.defineProperty(exports, "__esModule", { value: true });
33265 var rxjs_1 = require("rxjs");
33266 var Component_1 = require("../../../Component");
33267 var Viewer_1 = require("../../../Viewer");
33268 /**
33269  * @class OutlineTag
33270  *
33271  * @classdesc Tag holding properties for visualizing a geometry outline.
33272  *
33273  * @example
33274  * ```
33275  * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]);
33276  * var tag = new Mapillary.TagComponent.OutlineTag(
33277  *     "id-1",
33278  *     geometry
33279  *     { editable: true, lineColor: 0xff0000 });
33280  *
33281  * tagComponent.add([tag]);
33282  * ```
33283  */
33284 var OutlineTag = /** @class */ (function (_super) {
33285     __extends(OutlineTag, _super);
33286     /**
33287      * Create an outline tag.
33288      *
33289      * @override
33290      * @constructor
33291      * @param {string} id - Unique identifier of the tag.
33292      * @param {VertexGeometry} geometry - Geometry defining vertices of tag.
33293      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
33294      * behavior of the outline tag.
33295      */
33296     function OutlineTag(id, geometry, options) {
33297         var _this = _super.call(this, id, geometry) || this;
33298         options = !!options ? options : {};
33299         var domain = options.domain != null && geometry instanceof Component_1.PolygonGeometry ?
33300             options.domain : Component_1.TagDomain.TwoDimensional;
33301         var twoDimensionalPolygon = _this._twoDimensionalPolygon(domain, geometry);
33302         _this._domain = domain;
33303         _this._editable = options.editable == null || twoDimensionalPolygon ? false : options.editable;
33304         _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
33305         _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
33306         _this._icon = options.icon === undefined ? null : options.icon;
33307         _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat;
33308         _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
33309         _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
33310         _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
33311         _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
33312         _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
33313         _this._text = options.text === undefined ? null : options.text;
33314         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
33315         _this._click$ = new rxjs_1.Subject();
33316         _this._click$
33317             .subscribe(function (t) {
33318             _this.fire(OutlineTag.click, _this);
33319         });
33320         return _this;
33321     }
33322     Object.defineProperty(OutlineTag.prototype, "click$", {
33323         /**
33324          * Click observable.
33325          *
33326          * @description An observable emitting the tag when the icon of the
33327          * tag has been clicked.
33328          *
33329          * @returns {Observable<Tag>}
33330          */
33331         get: function () {
33332             return this._click$;
33333         },
33334         enumerable: true,
33335         configurable: true
33336     });
33337     Object.defineProperty(OutlineTag.prototype, "domain", {
33338         /**
33339          * Get domain property.
33340          *
33341          * @description Readonly property that can only be set in constructor.
33342          *
33343          * @returns Value indicating the domain of the tag.
33344          */
33345         get: function () {
33346             return this._domain;
33347         },
33348         enumerable: true,
33349         configurable: true
33350     });
33351     Object.defineProperty(OutlineTag.prototype, "editable", {
33352         /**
33353          * Get editable property.
33354          * @returns {boolean} Value indicating if tag is editable.
33355          */
33356         get: function () {
33357             return this._editable;
33358         },
33359         /**
33360          * Set editable property.
33361          * @param {boolean}
33362          *
33363          * @fires Tag#changed
33364          */
33365         set: function (value) {
33366             if (this._twoDimensionalPolygon(this._domain, this._geometry)) {
33367                 return;
33368             }
33369             this._editable = value;
33370             this._notifyChanged$.next(this);
33371         },
33372         enumerable: true,
33373         configurable: true
33374     });
33375     Object.defineProperty(OutlineTag.prototype, "fillColor", {
33376         /**
33377          * Get fill color property.
33378          * @returns {number}
33379          */
33380         get: function () {
33381             return this._fillColor;
33382         },
33383         /**
33384          * Set fill color property.
33385          * @param {number}
33386          *
33387          * @fires Tag#changed
33388          */
33389         set: function (value) {
33390             this._fillColor = value;
33391             this._notifyChanged$.next(this);
33392         },
33393         enumerable: true,
33394         configurable: true
33395     });
33396     Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
33397         /**
33398          * Get fill opacity property.
33399          * @returns {number}
33400          */
33401         get: function () {
33402             return this._fillOpacity;
33403         },
33404         /**
33405          * Set fill opacity property.
33406          * @param {number}
33407          *
33408          * @fires Tag#changed
33409          */
33410         set: function (value) {
33411             this._fillOpacity = value;
33412             this._notifyChanged$.next(this);
33413         },
33414         enumerable: true,
33415         configurable: true
33416     });
33417     Object.defineProperty(OutlineTag.prototype, "geometry", {
33418         /** @inheritdoc */
33419         get: function () {
33420             return this._geometry;
33421         },
33422         enumerable: true,
33423         configurable: true
33424     });
33425     Object.defineProperty(OutlineTag.prototype, "icon", {
33426         /**
33427          * Get icon property.
33428          * @returns {string}
33429          */
33430         get: function () {
33431             return this._icon;
33432         },
33433         /**
33434          * Set icon property.
33435          * @param {string}
33436          *
33437          * @fires Tag#changed
33438          */
33439         set: function (value) {
33440             this._icon = value;
33441             this._notifyChanged$.next(this);
33442         },
33443         enumerable: true,
33444         configurable: true
33445     });
33446     Object.defineProperty(OutlineTag.prototype, "iconFloat", {
33447         /**
33448          * Get icon float property.
33449          * @returns {Alignment}
33450          */
33451         get: function () {
33452             return this._iconFloat;
33453         },
33454         /**
33455          * Set icon float property.
33456          * @param {Alignment}
33457          *
33458          * @fires Tag#changed
33459          */
33460         set: function (value) {
33461             this._iconFloat = value;
33462             this._notifyChanged$.next(this);
33463         },
33464         enumerable: true,
33465         configurable: true
33466     });
33467     Object.defineProperty(OutlineTag.prototype, "iconIndex", {
33468         /**
33469          * Get icon index property.
33470          * @returns {number}
33471          */
33472         get: function () {
33473             return this._iconIndex;
33474         },
33475         /**
33476          * Set icon index property.
33477          * @param {number}
33478          *
33479          * @fires Tag#changed
33480          */
33481         set: function (value) {
33482             this._iconIndex = value;
33483             this._notifyChanged$.next(this);
33484         },
33485         enumerable: true,
33486         configurable: true
33487     });
33488     Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
33489         /**
33490          * Get indicate vertices property.
33491          * @returns {boolean} Value indicating if vertices should be indicated
33492          * when tag is editable.
33493          */
33494         get: function () {
33495             return this._indicateVertices;
33496         },
33497         /**
33498          * Set indicate vertices property.
33499          * @param {boolean}
33500          *
33501          * @fires Tag#changed
33502          */
33503         set: function (value) {
33504             this._indicateVertices = value;
33505             this._notifyChanged$.next(this);
33506         },
33507         enumerable: true,
33508         configurable: true
33509     });
33510     Object.defineProperty(OutlineTag.prototype, "lineColor", {
33511         /**
33512          * Get line color property.
33513          * @returns {number}
33514          */
33515         get: function () {
33516             return this._lineColor;
33517         },
33518         /**
33519          * Set line color property.
33520          * @param {number}
33521          *
33522          * @fires Tag#changed
33523          */
33524         set: function (value) {
33525             this._lineColor = value;
33526             this._notifyChanged$.next(this);
33527         },
33528         enumerable: true,
33529         configurable: true
33530     });
33531     Object.defineProperty(OutlineTag.prototype, "lineOpacity", {
33532         /**
33533          * Get line opacity property.
33534          * @returns {number}
33535          */
33536         get: function () {
33537             return this._lineOpacity;
33538         },
33539         /**
33540          * Set line opacity property.
33541          * @param {number}
33542          *
33543          * @fires Tag#changed
33544          */
33545         set: function (value) {
33546             this._lineOpacity = value;
33547             this._notifyChanged$.next(this);
33548         },
33549         enumerable: true,
33550         configurable: true
33551     });
33552     Object.defineProperty(OutlineTag.prototype, "lineWidth", {
33553         /**
33554          * Get line width property.
33555          * @returns {number}
33556          */
33557         get: function () {
33558             return this._lineWidth;
33559         },
33560         /**
33561          * Set line width property.
33562          * @param {number}
33563          *
33564          * @fires Tag#changed
33565          */
33566         set: function (value) {
33567             this._lineWidth = value;
33568             this._notifyChanged$.next(this);
33569         },
33570         enumerable: true,
33571         configurable: true
33572     });
33573     Object.defineProperty(OutlineTag.prototype, "text", {
33574         /**
33575          * Get text property.
33576          * @returns {string}
33577          */
33578         get: function () {
33579             return this._text;
33580         },
33581         /**
33582          * Set text property.
33583          * @param {string}
33584          *
33585          * @fires Tag#changed
33586          */
33587         set: function (value) {
33588             this._text = value;
33589             this._notifyChanged$.next(this);
33590         },
33591         enumerable: true,
33592         configurable: true
33593     });
33594     Object.defineProperty(OutlineTag.prototype, "textColor", {
33595         /**
33596          * Get text color property.
33597          * @returns {number}
33598          */
33599         get: function () {
33600             return this._textColor;
33601         },
33602         /**
33603          * Set text color property.
33604          * @param {number}
33605          *
33606          * @fires Tag#changed
33607          */
33608         set: function (value) {
33609             this._textColor = value;
33610             this._notifyChanged$.next(this);
33611         },
33612         enumerable: true,
33613         configurable: true
33614     });
33615     /**
33616      * Set options for tag.
33617      *
33618      * @description Sets all the option properties provided and keeps
33619      * the rest of the values as is.
33620      *
33621      * @param {IOutlineTagOptions} options - Outline tag options
33622      *
33623      * @fires {Tag#changed}
33624      */
33625     OutlineTag.prototype.setOptions = function (options) {
33626         var twoDimensionalPolygon = this._twoDimensionalPolygon(this._domain, this._geometry);
33627         this._editable = twoDimensionalPolygon || options.editable == null ? this._editable : options.editable;
33628         this._icon = options.icon === undefined ? this._icon : options.icon;
33629         this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
33630         this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
33631         this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
33632         this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
33633         this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
33634         this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
33635         this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
33636         this._text = options.text === undefined ? this._text : options.text;
33637         this._textColor = options.textColor == null ? this._textColor : options.textColor;
33638         this._notifyChanged$.next(this);
33639     };
33640     OutlineTag.prototype._twoDimensionalPolygon = function (domain, geometry) {
33641         return domain !== Component_1.TagDomain.ThreeDimensional && geometry instanceof Component_1.PolygonGeometry;
33642     };
33643     /**
33644      * Event fired when the icon of the outline tag is clicked.
33645      *
33646      * @event OutlineTag#click
33647      * @type {OutlineTag} The tag instance that was clicked.
33648      */
33649     OutlineTag.click = "click";
33650     return OutlineTag;
33651 }(Component_1.Tag));
33652 exports.OutlineTag = OutlineTag;
33653 exports.default = OutlineTag;
33654
33655 },{"../../../Component":274,"../../../Viewer":285,"rxjs":26}],367:[function(require,module,exports){
33656 "use strict";
33657 Object.defineProperty(exports, "__esModule", { value: true });
33658 var rxjs_1 = require("rxjs");
33659 var Geo_1 = require("../../../Geo");
33660 var RenderTag = /** @class */ (function () {
33661     function RenderTag(tag, transform, viewportCoords) {
33662         this._tag = tag;
33663         this._transform = transform;
33664         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
33665         this._glObjectsChanged$ = new rxjs_1.Subject();
33666         this._interact$ = new rxjs_1.Subject();
33667     }
33668     Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
33669         get: function () {
33670             return this._glObjectsChanged$;
33671         },
33672         enumerable: true,
33673         configurable: true
33674     });
33675     Object.defineProperty(RenderTag.prototype, "interact$", {
33676         get: function () {
33677             return this._interact$;
33678         },
33679         enumerable: true,
33680         configurable: true
33681     });
33682     Object.defineProperty(RenderTag.prototype, "tag", {
33683         get: function () {
33684             return this._tag;
33685         },
33686         enumerable: true,
33687         configurable: true
33688     });
33689     return RenderTag;
33690 }());
33691 exports.RenderTag = RenderTag;
33692 exports.default = RenderTag;
33693
33694 },{"../../../Geo":277,"rxjs":26}],368:[function(require,module,exports){
33695 "use strict";
33696 var __extends = (this && this.__extends) || (function () {
33697     var extendStatics = function (d, b) {
33698         extendStatics = Object.setPrototypeOf ||
33699             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33700             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33701         return extendStatics(d, b);
33702     }
33703     return function (d, b) {
33704         extendStatics(d, b);
33705         function __() { this.constructor = d; }
33706         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33707     };
33708 })();
33709 Object.defineProperty(exports, "__esModule", { value: true });
33710 var vd = require("virtual-dom");
33711 var Component_1 = require("../../../Component");
33712 var Viewer_1 = require("../../../Viewer");
33713 /**
33714  * @class SpotRenderTag
33715  * @classdesc Tag visualizing the properties of a SpotTag.
33716  */
33717 var SpotRenderTag = /** @class */ (function (_super) {
33718     __extends(SpotRenderTag, _super);
33719     function SpotRenderTag() {
33720         return _super !== null && _super.apply(this, arguments) || this;
33721     }
33722     SpotRenderTag.prototype.dispose = function () { };
33723     SpotRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
33724         var _this = this;
33725         var tag = this._tag;
33726         var container = {
33727             offsetHeight: size.height, offsetWidth: size.width,
33728         };
33729         var vNodes = [];
33730         var _a = tag.geometry.getCentroid2d(), centroidBasicX = _a[0], centroidBasicY = _a[1];
33731         var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
33732         if (centroidCanvas != null) {
33733             var interactNone = function (e) {
33734                 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: tag });
33735             };
33736             var canvasX = Math.round(centroidCanvas[0]);
33737             var canvasY = Math.round(centroidCanvas[1]);
33738             if (tag.icon != null) {
33739                 if (atlas.loaded) {
33740                     var sprite = atlas.getDOMSprite(tag.icon, Viewer_1.Alignment.Bottom);
33741                     var iconTransform = "translate(" + canvasX + "px," + (canvasY + 8) + "px)";
33742                     var properties = {
33743                         onmousedown: interactNone,
33744                         style: {
33745                             pointerEvents: "all",
33746                             transform: iconTransform,
33747                         },
33748                     };
33749                     vNodes.push(vd.h("div", properties, [sprite]));
33750                 }
33751             }
33752             else if (tag.text != null) {
33753                 var textTransform = "translate(-50%,0%) translate(" + canvasX + "px," + (canvasY + 8) + "px)";
33754                 var properties = {
33755                     onmousedown: interactNone,
33756                     style: {
33757                         color: this._colorToCss(tag.textColor),
33758                         transform: textTransform,
33759                     },
33760                     textContent: tag.text,
33761                 };
33762                 vNodes.push(vd.h("span.TagSymbol", properties, []));
33763             }
33764             var interact = this._interact(Component_1.TagOperation.Centroid, tag, "move");
33765             var background = this._colorToCss(tag.color);
33766             var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
33767             if (tag.editable) {
33768                 var interactorProperties = {
33769                     onmousedown: interact,
33770                     style: {
33771                         background: background,
33772                         transform: transform,
33773                     },
33774                 };
33775                 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
33776             }
33777             var pointProperties = {
33778                 style: {
33779                     background: background,
33780                     transform: transform,
33781                 },
33782             };
33783             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
33784         }
33785         return vNodes;
33786     };
33787     SpotRenderTag.prototype.getGLObjects = function () { return []; };
33788     SpotRenderTag.prototype.getRetrievableObjects = function () { return []; };
33789     SpotRenderTag.prototype._colorToCss = function (color) {
33790         return "#" + ("000000" + color.toString(16)).substr(-6);
33791     };
33792     SpotRenderTag.prototype._interact = function (operation, tag, cursor, vertexIndex) {
33793         var _this = this;
33794         return function (e) {
33795             var offsetX = e.offsetX - e.target.offsetWidth / 2;
33796             var offsetY = e.offsetY - e.target.offsetHeight / 2;
33797             _this._interact$.next({
33798                 cursor: cursor,
33799                 offsetX: offsetX,
33800                 offsetY: offsetY,
33801                 operation: operation,
33802                 tag: tag,
33803                 vertexIndex: vertexIndex,
33804             });
33805         };
33806     };
33807     return SpotRenderTag;
33808 }(Component_1.RenderTag));
33809 exports.SpotRenderTag = SpotRenderTag;
33810
33811
33812 },{"../../../Component":274,"../../../Viewer":285,"virtual-dom":230}],369:[function(require,module,exports){
33813 "use strict";
33814 var __extends = (this && this.__extends) || (function () {
33815     var extendStatics = function (d, b) {
33816         extendStatics = Object.setPrototypeOf ||
33817             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33818             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33819         return extendStatics(d, b);
33820     }
33821     return function (d, b) {
33822         extendStatics(d, b);
33823         function __() { this.constructor = d; }
33824         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33825     };
33826 })();
33827 Object.defineProperty(exports, "__esModule", { value: true });
33828 var Component_1 = require("../../../Component");
33829 /**
33830  * @class SpotTag
33831  *
33832  * @classdesc Tag holding properties for visualizing the centroid of a geometry.
33833  *
33834  * @example
33835  * ```
33836  * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]);
33837  * var tag = new Mapillary.TagComponent.SpotTag(
33838  *     "id-1",
33839  *     geometry
33840  *     { editable: true, color: 0xff0000 });
33841  *
33842  * tagComponent.add([tag]);
33843  * ```
33844  */
33845 var SpotTag = /** @class */ (function (_super) {
33846     __extends(SpotTag, _super);
33847     /**
33848      * Create a spot tag.
33849      *
33850      * @override
33851      * @constructor
33852      * @param {string} id
33853      * @param {Geometry} geometry
33854      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
33855      * behavior of the spot tag.
33856      */
33857     function SpotTag(id, geometry, options) {
33858         var _this = _super.call(this, id, geometry) || this;
33859         options = !!options ? options : {};
33860         _this._color = options.color == null ? 0xFFFFFF : options.color;
33861         _this._editable = options.editable == null ? false : options.editable;
33862         _this._icon = options.icon === undefined ? null : options.icon;
33863         _this._text = options.text === undefined ? null : options.text;
33864         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
33865         return _this;
33866     }
33867     Object.defineProperty(SpotTag.prototype, "color", {
33868         /**
33869          * Get color property.
33870          * @returns {number} The color of the spot as a hexagonal number;
33871          */
33872         get: function () {
33873             return this._color;
33874         },
33875         /**
33876          * Set color property.
33877          * @param {number}
33878          *
33879          * @fires Tag#changed
33880          */
33881         set: function (value) {
33882             this._color = value;
33883             this._notifyChanged$.next(this);
33884         },
33885         enumerable: true,
33886         configurable: true
33887     });
33888     Object.defineProperty(SpotTag.prototype, "editable", {
33889         /**
33890          * Get editable property.
33891          * @returns {boolean} Value indicating if tag is editable.
33892          */
33893         get: function () {
33894             return this._editable;
33895         },
33896         /**
33897          * Set editable property.
33898          * @param {boolean}
33899          *
33900          * @fires Tag#changed
33901          */
33902         set: function (value) {
33903             this._editable = value;
33904             this._notifyChanged$.next(this);
33905         },
33906         enumerable: true,
33907         configurable: true
33908     });
33909     Object.defineProperty(SpotTag.prototype, "icon", {
33910         /**
33911          * Get icon property.
33912          * @returns {string}
33913          */
33914         get: function () {
33915             return this._icon;
33916         },
33917         /**
33918          * Set icon property.
33919          * @param {string}
33920          *
33921          * @fires Tag#changed
33922          */
33923         set: function (value) {
33924             this._icon = value;
33925             this._notifyChanged$.next(this);
33926         },
33927         enumerable: true,
33928         configurable: true
33929     });
33930     Object.defineProperty(SpotTag.prototype, "text", {
33931         /**
33932          * Get text property.
33933          * @returns {string}
33934          */
33935         get: function () {
33936             return this._text;
33937         },
33938         /**
33939          * Set text property.
33940          * @param {string}
33941          *
33942          * @fires Tag#changed
33943          */
33944         set: function (value) {
33945             this._text = value;
33946             this._notifyChanged$.next(this);
33947         },
33948         enumerable: true,
33949         configurable: true
33950     });
33951     Object.defineProperty(SpotTag.prototype, "textColor", {
33952         /**
33953          * Get text color property.
33954          * @returns {number}
33955          */
33956         get: function () {
33957             return this._textColor;
33958         },
33959         /**
33960          * Set text color property.
33961          * @param {number}
33962          *
33963          * @fires Tag#changed
33964          */
33965         set: function (value) {
33966             this._textColor = value;
33967             this._notifyChanged$.next(this);
33968         },
33969         enumerable: true,
33970         configurable: true
33971     });
33972     /**
33973      * Set options for tag.
33974      *
33975      * @description Sets all the option properties provided and keps
33976      * the rest of the values as is.
33977      *
33978      * @param {ISpotTagOptions} options - Spot tag options
33979      *
33980      * @fires {Tag#changed}
33981      */
33982     SpotTag.prototype.setOptions = function (options) {
33983         this._color = options.color == null ? this._color : options.color;
33984         this._editable = options.editable == null ? this._editable : options.editable;
33985         this._icon = options.icon === undefined ? this._icon : options.icon;
33986         this._text = options.text === undefined ? this._text : options.text;
33987         this._textColor = options.textColor == null ? this._textColor : options.textColor;
33988         this._notifyChanged$.next(this);
33989     };
33990     return SpotTag;
33991 }(Component_1.Tag));
33992 exports.SpotTag = SpotTag;
33993 exports.default = SpotTag;
33994
33995 },{"../../../Component":274}],370:[function(require,module,exports){
33996 "use strict";
33997 var __extends = (this && this.__extends) || (function () {
33998     var extendStatics = function (d, b) {
33999         extendStatics = Object.setPrototypeOf ||
34000             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34001             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34002         return extendStatics(d, b);
34003     }
34004     return function (d, b) {
34005         extendStatics(d, b);
34006         function __() { this.constructor = d; }
34007         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34008     };
34009 })();
34010 Object.defineProperty(exports, "__esModule", { value: true });
34011 var operators_1 = require("rxjs/operators");
34012 var rxjs_1 = require("rxjs");
34013 var Utils_1 = require("../../../Utils");
34014 /**
34015  * @class Tag
34016  * @abstract
34017  * @classdesc Abstract class representing the basic functionality of for a tag.
34018  */
34019 var Tag = /** @class */ (function (_super) {
34020     __extends(Tag, _super);
34021     /**
34022      * Create a tag.
34023      *
34024      * @constructor
34025      * @param {string} id
34026      * @param {Geometry} geometry
34027      */
34028     function Tag(id, geometry) {
34029         var _this = _super.call(this) || this;
34030         _this._id = id;
34031         _this._geometry = geometry;
34032         _this._notifyChanged$ = new rxjs_1.Subject();
34033         _this._notifyChanged$
34034             .subscribe(function (t) {
34035             _this.fire(Tag.changed, _this);
34036         });
34037         _this._geometry.changed$
34038             .subscribe(function (g) {
34039             _this.fire(Tag.geometrychanged, _this);
34040         });
34041         return _this;
34042     }
34043     Object.defineProperty(Tag.prototype, "id", {
34044         /**
34045          * Get id property.
34046          * @returns {string}
34047          */
34048         get: function () {
34049             return this._id;
34050         },
34051         enumerable: true,
34052         configurable: true
34053     });
34054     Object.defineProperty(Tag.prototype, "geometry", {
34055         /**
34056          * Get geometry property.
34057          * @returns {Geometry} The geometry of the tag.
34058          */
34059         get: function () {
34060             return this._geometry;
34061         },
34062         enumerable: true,
34063         configurable: true
34064     });
34065     Object.defineProperty(Tag.prototype, "changed$", {
34066         /**
34067          * Get changed observable.
34068          * @returns {Observable<Tag>}
34069          * @ignore
34070          */
34071         get: function () {
34072             return this._notifyChanged$;
34073         },
34074         enumerable: true,
34075         configurable: true
34076     });
34077     Object.defineProperty(Tag.prototype, "geometryChanged$", {
34078         /**
34079          * Get geometry changed observable.
34080          * @returns {Observable<Tag>}
34081          * @ignore
34082          */
34083         get: function () {
34084             var _this = this;
34085             return this._geometry.changed$.pipe(operators_1.map(function (geometry) {
34086                 return _this;
34087             }), operators_1.share());
34088         },
34089         enumerable: true,
34090         configurable: true
34091     });
34092     /**
34093      * Event fired when a property related to the visual appearance of the
34094      * tag has changed.
34095      *
34096      * @event Tag#changed
34097      * @type {Tag} The tag instance that has changed.
34098      */
34099     Tag.changed = "changed";
34100     /**
34101      * Event fired when the geometry of the tag has changed.
34102      *
34103      * @event Tag#geometrychanged
34104      * @type {Tag} The tag instance whose geometry has changed.
34105      */
34106     Tag.geometrychanged = "geometrychanged";
34107     return Tag;
34108 }(Utils_1.EventEmitter));
34109 exports.Tag = Tag;
34110 exports.default = Tag;
34111
34112 },{"../../../Utils":284,"rxjs":26,"rxjs/operators":224}],371:[function(require,module,exports){
34113 "use strict";
34114 Object.defineProperty(exports, "__esModule", { value: true });
34115 /**
34116  * Enumeration for tag domains.
34117  * @enum {number}
34118  * @readonly
34119  * @description Defines where lines between two vertices are treated
34120  * as straight.
34121  *
34122  * Only applicable for polygons. For rectangles lines between
34123  * vertices are always treated as straight in the distorted 2D
34124  * projection and bended in the undistorted 3D space.
34125  */
34126 var TagDomain;
34127 (function (TagDomain) {
34128     /**
34129      * Treats lines between two vertices as straight in the
34130      * distorted 2D projection, i.e. on the image. If the image
34131      * is distorted this will result in bended lines when rendered
34132      * in the undistorted 3D space.
34133      */
34134     TagDomain[TagDomain["TwoDimensional"] = 0] = "TwoDimensional";
34135     /**
34136      * Treats lines as straight in the undistorted 3D space. If the
34137      * image is distorted this will result in bended lines when rendered
34138      * on the distorted 2D projection of the image.
34139      */
34140     TagDomain[TagDomain["ThreeDimensional"] = 1] = "ThreeDimensional";
34141 })(TagDomain = exports.TagDomain || (exports.TagDomain = {}));
34142 exports.default = TagDomain;
34143
34144 },{}],372:[function(require,module,exports){
34145 "use strict";
34146 Object.defineProperty(exports, "__esModule", { value: true });
34147 var HandlerBase = /** @class */ (function () {
34148     /** @ignore */
34149     function HandlerBase(component, container, navigator) {
34150         this._component = component;
34151         this._container = container;
34152         this._navigator = navigator;
34153         this._enabled = false;
34154     }
34155     Object.defineProperty(HandlerBase.prototype, "isEnabled", {
34156         /**
34157          * Returns a Boolean indicating whether the interaction is enabled.
34158          *
34159          * @returns {boolean} `true` if the interaction is enabled.
34160          */
34161         get: function () {
34162             return this._enabled;
34163         },
34164         enumerable: true,
34165         configurable: true
34166     });
34167     /**
34168      * Enables the interaction.
34169      *
34170      * @example ```<component-name>.<handler-name>.enable();```
34171      */
34172     HandlerBase.prototype.enable = function () {
34173         if (this._enabled || !this._component.activated) {
34174             return;
34175         }
34176         this._enable();
34177         this._enabled = true;
34178         this._component.configure(this._getConfiguration(true));
34179     };
34180     /**
34181      * Disables the interaction.
34182      *
34183      * @example ```<component-name>.<handler-name>.disable();```
34184      */
34185     HandlerBase.prototype.disable = function () {
34186         if (!this._enabled) {
34187             return;
34188         }
34189         this._disable();
34190         this._enabled = false;
34191         if (this._component.activated) {
34192             this._component.configure(this._getConfiguration(false));
34193         }
34194     };
34195     return HandlerBase;
34196 }());
34197 exports.HandlerBase = HandlerBase;
34198 exports.default = HandlerBase;
34199
34200 },{}],373:[function(require,module,exports){
34201 "use strict";
34202 Object.defineProperty(exports, "__esModule", { value: true });
34203 var THREE = require("three");
34204 var Component_1 = require("../../Component");
34205 var MeshFactory = /** @class */ (function () {
34206     function MeshFactory(imagePlaneDepth, imageSphereRadius) {
34207         this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
34208         this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
34209     }
34210     MeshFactory.prototype.createMesh = function (node, transform) {
34211         var mesh = node.pano ?
34212             this._createImageSphere(node, transform) :
34213             this._createImagePlane(node, transform);
34214         return mesh;
34215     };
34216     MeshFactory.prototype.createFlatMesh = function (node, transform, basicX0, basicX1, basicY0, basicY1) {
34217         var texture = this._createTexture(node.image);
34218         var materialParameters = this._createDistortedPlaneMaterialParameters(transform, texture);
34219         var material = new THREE.ShaderMaterial(materialParameters);
34220         var geometry = this._getFlatImagePlaneGeoFromBasic(transform, basicX0, basicX1, basicY0, basicY1);
34221         return new THREE.Mesh(geometry, material);
34222     };
34223     MeshFactory.prototype.createCurtainMesh = function (node, transform) {
34224         if (node.pano && !node.fullPano) {
34225             throw new Error("Cropped panoramas cannot have curtain.");
34226         }
34227         return node.pano ?
34228             this._createSphereCurtainMesh(node, transform) :
34229             this._createCurtainMesh(node, transform);
34230     };
34231     MeshFactory.prototype.createDistortedCurtainMesh = function (node, transform) {
34232         if (node.pano) {
34233             throw new Error("Cropped panoramas cannot have curtain.");
34234         }
34235         return this._createDistortedCurtainMesh(node, transform);
34236     };
34237     MeshFactory.prototype._createCurtainMesh = function (node, transform) {
34238         var texture = this._createTexture(node.image);
34239         var materialParameters = this._createCurtainPlaneMaterialParameters(transform, texture);
34240         var material = new THREE.ShaderMaterial(materialParameters);
34241         var geometry = this._useMesh(transform, node) ?
34242             this._getImagePlaneGeo(transform, node) :
34243             this._getRegularFlatImagePlaneGeo(transform);
34244         return new THREE.Mesh(geometry, material);
34245     };
34246     MeshFactory.prototype._createDistortedCurtainMesh = function (node, transform) {
34247         var texture = this._createTexture(node.image);
34248         var materialParameters = this._createDistortedCurtainPlaneMaterialParameters(transform, texture);
34249         var material = new THREE.ShaderMaterial(materialParameters);
34250         var geometry = this._getRegularFlatImagePlaneGeo(transform);
34251         return new THREE.Mesh(geometry, material);
34252     };
34253     MeshFactory.prototype._createSphereCurtainMesh = function (node, transform) {
34254         var texture = this._createTexture(node.image);
34255         var materialParameters = this._createCurtainSphereMaterialParameters(transform, texture);
34256         var material = new THREE.ShaderMaterial(materialParameters);
34257         return this._useMesh(transform, node) ?
34258             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
34259             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
34260     };
34261     MeshFactory.prototype._createImageSphere = function (node, transform) {
34262         var texture = this._createTexture(node.image);
34263         var materialParameters = this._createSphereMaterialParameters(transform, texture);
34264         var material = new THREE.ShaderMaterial(materialParameters);
34265         var mesh = this._useMesh(transform, node) ?
34266             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
34267             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
34268         return mesh;
34269     };
34270     MeshFactory.prototype._createImagePlane = function (node, transform) {
34271         var texture = this._createTexture(node.image);
34272         var materialParameters = this._createPlaneMaterialParameters(transform, texture);
34273         var material = new THREE.ShaderMaterial(materialParameters);
34274         var geometry = this._useMesh(transform, node) ?
34275             this._getImagePlaneGeo(transform, node) :
34276             this._getRegularFlatImagePlaneGeo(transform);
34277         return new THREE.Mesh(geometry, material);
34278     };
34279     MeshFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
34280         var gpano = transform.gpano;
34281         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
34282         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
34283         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
34284         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
34285         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
34286         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
34287         var materialParameters = {
34288             depthWrite: false,
34289             fragmentShader: Component_1.Shaders.equirectangular.fragment,
34290             side: THREE.DoubleSide,
34291             transparent: true,
34292             uniforms: {
34293                 opacity: {
34294                     type: "f",
34295                     value: 1,
34296                 },
34297                 phiLength: {
34298                     type: "f",
34299                     value: phiLength,
34300                 },
34301                 phiShift: {
34302                     type: "f",
34303                     value: phiShift,
34304                 },
34305                 projectorMat: {
34306                     type: "m4",
34307                     value: transform.rt,
34308                 },
34309                 projectorTex: {
34310                     type: "t",
34311                     value: texture,
34312                 },
34313                 thetaLength: {
34314                     type: "f",
34315                     value: thetaLength,
34316                 },
34317                 thetaShift: {
34318                     type: "f",
34319                     value: thetaShift,
34320                 },
34321             },
34322             vertexShader: Component_1.Shaders.equirectangular.vertex,
34323         };
34324         return materialParameters;
34325     };
34326     MeshFactory.prototype._createCurtainSphereMaterialParameters = function (transform, texture) {
34327         var gpano = transform.gpano;
34328         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
34329         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
34330         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
34331         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
34332         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
34333         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
34334         var materialParameters = {
34335             depthWrite: false,
34336             fragmentShader: Component_1.Shaders.equirectangularCurtain.fragment,
34337             side: THREE.DoubleSide,
34338             transparent: true,
34339             uniforms: {
34340                 curtain: {
34341                     type: "f",
34342                     value: 1,
34343                 },
34344                 opacity: {
34345                     type: "f",
34346                     value: 1,
34347                 },
34348                 phiLength: {
34349                     type: "f",
34350                     value: phiLength,
34351                 },
34352                 phiShift: {
34353                     type: "f",
34354                     value: phiShift,
34355                 },
34356                 projectorMat: {
34357                     type: "m4",
34358                     value: transform.rt,
34359                 },
34360                 projectorTex: {
34361                     type: "t",
34362                     value: texture,
34363                 },
34364                 thetaLength: {
34365                     type: "f",
34366                     value: thetaLength,
34367                 },
34368                 thetaShift: {
34369                     type: "f",
34370                     value: thetaShift,
34371                 },
34372             },
34373             vertexShader: Component_1.Shaders.equirectangularCurtain.vertex,
34374         };
34375         return materialParameters;
34376     };
34377     MeshFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
34378         var materialParameters = {
34379             depthWrite: false,
34380             fragmentShader: Component_1.Shaders.perspective.fragment,
34381             side: THREE.DoubleSide,
34382             transparent: true,
34383             uniforms: {
34384                 focal: {
34385                     type: "f",
34386                     value: transform.focal,
34387                 },
34388                 k1: {
34389                     type: "f",
34390                     value: transform.ck1,
34391                 },
34392                 k2: {
34393                     type: "f",
34394                     value: transform.ck2,
34395                 },
34396                 opacity: {
34397                     type: "f",
34398                     value: 1,
34399                 },
34400                 projectorMat: {
34401                     type: "m4",
34402                     value: transform.basicRt,
34403                 },
34404                 projectorTex: {
34405                     type: "t",
34406                     value: texture,
34407                 },
34408                 radial_peak: {
34409                     type: "f",
34410                     value: !!transform.radialPeak ? transform.radialPeak : 0,
34411                 },
34412                 scale_x: {
34413                     type: "f",
34414                     value: Math.max(transform.basicHeight, transform.basicWidth) / transform.basicWidth,
34415                 },
34416                 scale_y: {
34417                     type: "f",
34418                     value: Math.max(transform.basicWidth, transform.basicHeight) / transform.basicHeight,
34419                 },
34420             },
34421             vertexShader: Component_1.Shaders.perspective.vertex,
34422         };
34423         return materialParameters;
34424     };
34425     MeshFactory.prototype._createCurtainPlaneMaterialParameters = function (transform, texture) {
34426         var materialParameters = {
34427             depthWrite: false,
34428             fragmentShader: Component_1.Shaders.perspectiveCurtain.fragment,
34429             side: THREE.DoubleSide,
34430             transparent: true,
34431             uniforms: {
34432                 curtain: {
34433                     type: "f",
34434                     value: 1,
34435                 },
34436                 focal: {
34437                     type: "f",
34438                     value: transform.focal,
34439                 },
34440                 k1: {
34441                     type: "f",
34442                     value: transform.ck1,
34443                 },
34444                 k2: {
34445                     type: "f",
34446                     value: transform.ck2,
34447                 },
34448                 opacity: {
34449                     type: "f",
34450                     value: 1,
34451                 },
34452                 projectorMat: {
34453                     type: "m4",
34454                     value: transform.basicRt,
34455                 },
34456                 projectorTex: {
34457                     type: "t",
34458                     value: texture,
34459                 },
34460                 radial_peak: {
34461                     type: "f",
34462                     value: !!transform.radialPeak ? transform.radialPeak : 0,
34463                 },
34464                 scale_x: {
34465                     type: "f",
34466                     value: Math.max(transform.basicHeight, transform.basicWidth) / transform.basicWidth,
34467                 },
34468                 scale_y: {
34469                     type: "f",
34470                     value: Math.max(transform.basicWidth, transform.basicHeight) / transform.basicHeight,
34471                 },
34472             },
34473             vertexShader: Component_1.Shaders.perspectiveCurtain.vertex,
34474         };
34475         return materialParameters;
34476     };
34477     MeshFactory.prototype._createDistortedCurtainPlaneMaterialParameters = function (transform, texture) {
34478         var materialParameters = {
34479             depthWrite: false,
34480             fragmentShader: Component_1.Shaders.perspectiveDistortedCurtain.fragment,
34481             side: THREE.DoubleSide,
34482             transparent: true,
34483             uniforms: {
34484                 curtain: {
34485                     type: "f",
34486                     value: 1,
34487                 },
34488                 opacity: {
34489                     type: "f",
34490                     value: 1,
34491                 },
34492                 projectorMat: {
34493                     type: "m4",
34494                     value: transform.projectorMatrix(),
34495                 },
34496                 projectorTex: {
34497                     type: "t",
34498                     value: texture,
34499                 },
34500             },
34501             vertexShader: Component_1.Shaders.perspectiveDistortedCurtain.vertex,
34502         };
34503         return materialParameters;
34504     };
34505     MeshFactory.prototype._createDistortedPlaneMaterialParameters = function (transform, texture) {
34506         var materialParameters = {
34507             depthWrite: false,
34508             fragmentShader: Component_1.Shaders.perspectiveDistorted.fragment,
34509             side: THREE.DoubleSide,
34510             transparent: true,
34511             uniforms: {
34512                 opacity: {
34513                     type: "f",
34514                     value: 1,
34515                 },
34516                 projectorMat: {
34517                     type: "m4",
34518                     value: transform.projectorMatrix(),
34519                 },
34520                 projectorTex: {
34521                     type: "t",
34522                     value: texture,
34523                 },
34524             },
34525             vertexShader: Component_1.Shaders.perspectiveDistorted.vertex,
34526         };
34527         return materialParameters;
34528     };
34529     MeshFactory.prototype._createTexture = function (image) {
34530         var texture = new THREE.Texture(image);
34531         texture.minFilter = THREE.LinearFilter;
34532         texture.needsUpdate = true;
34533         return texture;
34534     };
34535     MeshFactory.prototype._useMesh = function (transform, node) {
34536         return node.mesh.vertices.length && transform.hasValidScale;
34537     };
34538     MeshFactory.prototype._getImageSphereGeo = function (transform, node) {
34539         var t = new THREE.Matrix4().getInverse(transform.srt);
34540         // push everything at least 5 meters in front of the camera
34541         var minZ = 5.0 * transform.scale;
34542         var maxZ = this._imageSphereRadius * transform.scale;
34543         var vertices = node.mesh.vertices;
34544         var numVertices = vertices.length / 3;
34545         var positions = new Float32Array(vertices.length);
34546         for (var i = 0; i < numVertices; ++i) {
34547             var index = 3 * i;
34548             var x = vertices[index + 0];
34549             var y = vertices[index + 1];
34550             var z = vertices[index + 2];
34551             var l = Math.sqrt(x * x + y * y + z * z);
34552             var boundedL = Math.max(minZ, Math.min(l, maxZ));
34553             var factor = boundedL / l;
34554             var p = new THREE.Vector3(x * factor, y * factor, z * factor);
34555             p.applyMatrix4(t);
34556             positions[index + 0] = p.x;
34557             positions[index + 1] = p.y;
34558             positions[index + 2] = p.z;
34559         }
34560         var faces = node.mesh.faces;
34561         var indices = new Uint16Array(faces.length);
34562         for (var i = 0; i < faces.length; ++i) {
34563             indices[i] = faces[i];
34564         }
34565         var geometry = new THREE.BufferGeometry();
34566         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
34567         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
34568         return geometry;
34569     };
34570     MeshFactory.prototype._getImagePlaneGeo = function (transform, node) {
34571         var undistortionMarginFactor = 3;
34572         var t = new THREE.Matrix4().getInverse(transform.srt);
34573         // push everything at least 5 meters in front of the camera
34574         var minZ = 5.0 * transform.scale;
34575         var maxZ = this._imagePlaneDepth * transform.scale;
34576         var vertices = node.mesh.vertices;
34577         var numVertices = vertices.length / 3;
34578         var positions = new Float32Array(vertices.length);
34579         for (var i = 0; i < numVertices; ++i) {
34580             var index = 3 * i;
34581             var x = vertices[index + 0];
34582             var y = vertices[index + 1];
34583             var z = vertices[index + 2];
34584             if (i < 4) {
34585                 x *= undistortionMarginFactor;
34586                 y *= undistortionMarginFactor;
34587             }
34588             var boundedZ = Math.max(minZ, Math.min(z, maxZ));
34589             var factor = boundedZ / z;
34590             var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
34591             p.applyMatrix4(t);
34592             positions[index + 0] = p.x;
34593             positions[index + 1] = p.y;
34594             positions[index + 2] = p.z;
34595         }
34596         var faces = node.mesh.faces;
34597         var indices = new Uint16Array(faces.length);
34598         for (var i = 0; i < faces.length; ++i) {
34599             indices[i] = faces[i];
34600         }
34601         var geometry = new THREE.BufferGeometry();
34602         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
34603         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
34604         return geometry;
34605     };
34606     MeshFactory.prototype._getFlatImageSphereGeo = function (transform) {
34607         var gpano = transform.gpano;
34608         var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
34609         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
34610         var thetaStart = Math.PI *
34611             (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
34612             gpano.FullPanoHeightPixels;
34613         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
34614         var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
34615         geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
34616         return geometry;
34617     };
34618     MeshFactory.prototype._getRegularFlatImagePlaneGeo = function (transform) {
34619         var width = transform.width;
34620         var height = transform.height;
34621         var size = Math.max(width, height);
34622         var dx = width / 2.0 / size;
34623         var dy = height / 2.0 / size;
34624         return this._getFlatImagePlaneGeo(transform, dx, dy);
34625     };
34626     MeshFactory.prototype._getFlatImagePlaneGeo = function (transform, dx, dy) {
34627         var vertices = [];
34628         vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
34629         vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
34630         vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
34631         vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
34632         return this._createFlatGeometry(vertices);
34633     };
34634     MeshFactory.prototype._getFlatImagePlaneGeoFromBasic = function (transform, basicX0, basicX1, basicY0, basicY1) {
34635         var vertices = [];
34636         vertices.push(transform.unprojectBasic([basicX0, basicY0], this._imagePlaneDepth));
34637         vertices.push(transform.unprojectBasic([basicX1, basicY0], this._imagePlaneDepth));
34638         vertices.push(transform.unprojectBasic([basicX1, basicY1], this._imagePlaneDepth));
34639         vertices.push(transform.unprojectBasic([basicX0, basicY1], this._imagePlaneDepth));
34640         return this._createFlatGeometry(vertices);
34641     };
34642     MeshFactory.prototype._createFlatGeometry = function (vertices) {
34643         var positions = new Float32Array(12);
34644         for (var i = 0; i < vertices.length; i++) {
34645             var index = 3 * i;
34646             positions[index + 0] = vertices[i][0];
34647             positions[index + 1] = vertices[i][1];
34648             positions[index + 2] = vertices[i][2];
34649         }
34650         var indices = new Uint16Array(6);
34651         indices[0] = 0;
34652         indices[1] = 1;
34653         indices[2] = 3;
34654         indices[3] = 1;
34655         indices[4] = 2;
34656         indices[5] = 3;
34657         var geometry = new THREE.BufferGeometry();
34658         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
34659         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
34660         return geometry;
34661     };
34662     return MeshFactory;
34663 }());
34664 exports.MeshFactory = MeshFactory;
34665 exports.default = MeshFactory;
34666
34667 },{"../../Component":274,"three":225}],374:[function(require,module,exports){
34668 "use strict";
34669 Object.defineProperty(exports, "__esModule", { value: true });
34670 var THREE = require("three");
34671 var MeshScene = /** @class */ (function () {
34672     function MeshScene() {
34673         this.scene = new THREE.Scene();
34674         this.sceneOld = new THREE.Scene();
34675         this.imagePlanes = [];
34676         this.imagePlanesOld = [];
34677     }
34678     MeshScene.prototype.updateImagePlanes = function (planes) {
34679         this._dispose(this.imagePlanesOld, this.sceneOld);
34680         for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
34681             var plane = _a[_i];
34682             this.scene.remove(plane);
34683             this.sceneOld.add(plane);
34684         }
34685         for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
34686             var plane = planes_1[_b];
34687             this.scene.add(plane);
34688         }
34689         this.imagePlanesOld = this.imagePlanes;
34690         this.imagePlanes = planes;
34691     };
34692     MeshScene.prototype.addImagePlanes = function (planes) {
34693         for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
34694             var plane = planes_2[_i];
34695             this.scene.add(plane);
34696             this.imagePlanes.push(plane);
34697         }
34698     };
34699     MeshScene.prototype.addImagePlanesOld = function (planes) {
34700         for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
34701             var plane = planes_3[_i];
34702             this.sceneOld.add(plane);
34703             this.imagePlanesOld.push(plane);
34704         }
34705     };
34706     MeshScene.prototype.setImagePlanes = function (planes) {
34707         this._clear();
34708         this.addImagePlanes(planes);
34709     };
34710     MeshScene.prototype.setImagePlanesOld = function (planes) {
34711         this._clearOld();
34712         this.addImagePlanesOld(planes);
34713     };
34714     MeshScene.prototype.clear = function () {
34715         this._clear();
34716         this._clearOld();
34717     };
34718     MeshScene.prototype._clear = function () {
34719         this._dispose(this.imagePlanes, this.scene);
34720         this.imagePlanes.length = 0;
34721     };
34722     MeshScene.prototype._clearOld = function () {
34723         this._dispose(this.imagePlanesOld, this.sceneOld);
34724         this.imagePlanesOld.length = 0;
34725     };
34726     MeshScene.prototype._dispose = function (planes, scene) {
34727         for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
34728             var plane = planes_4[_i];
34729             scene.remove(plane);
34730             plane.geometry.dispose();
34731             plane.material.dispose();
34732             var texture = plane.material.uniforms.projectorTex.value;
34733             if (texture != null) {
34734                 texture.dispose();
34735             }
34736         }
34737     };
34738     return MeshScene;
34739 }());
34740 exports.MeshScene = MeshScene;
34741 exports.default = MeshScene;
34742
34743 },{"three":225}],375:[function(require,module,exports){
34744 "use strict";
34745 Object.defineProperty(exports, "__esModule", { value: true });
34746 var rxjs_1 = require("rxjs");
34747 var operators_1 = require("rxjs/operators");
34748 var MouseOperator = /** @class */ (function () {
34749     function MouseOperator() {
34750     }
34751     MouseOperator.filteredPairwiseMouseDrag$ = function (name, mouseService) {
34752         return mouseService
34753             .filtered$(name, mouseService.mouseDragStart$).pipe(operators_1.switchMap(function (mouseDragStart) {
34754             var mouseDragging$ = rxjs_1.concat(rxjs_1.of(mouseDragStart), mouseService
34755                 .filtered$(name, mouseService.mouseDrag$));
34756             var mouseDragEnd$ = mouseService
34757                 .filtered$(name, mouseService.mouseDragEnd$).pipe(operators_1.map(function () {
34758                 return null;
34759             }));
34760             return rxjs_1.merge(mouseDragging$, mouseDragEnd$).pipe(operators_1.takeWhile(function (e) {
34761                 return !!e;
34762             }), operators_1.startWith(null));
34763         }), operators_1.pairwise(), operators_1.filter(function (pair) {
34764             return pair[0] != null && pair[1] != null;
34765         }));
34766     };
34767     return MouseOperator;
34768 }());
34769 exports.MouseOperator = MouseOperator;
34770 exports.default = MouseOperator;
34771
34772 },{"rxjs":26,"rxjs/operators":224}],376:[function(require,module,exports){
34773 "use strict";
34774 var __extends = (this && this.__extends) || (function () {
34775     var extendStatics = function (d, b) {
34776         extendStatics = Object.setPrototypeOf ||
34777             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34778             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34779         return extendStatics(d, b);
34780     }
34781     return function (d, b) {
34782         extendStatics(d, b);
34783         function __() { this.constructor = d; }
34784         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34785     };
34786 })();
34787 Object.defineProperty(exports, "__esModule", { value: true });
34788 var rxjs_1 = require("rxjs");
34789 var operators_1 = require("rxjs/operators");
34790 var vd = require("virtual-dom");
34791 var Component_1 = require("../../Component");
34792 var Geo_1 = require("../../Geo");
34793 var State_1 = require("../../State");
34794 var ZoomComponent = /** @class */ (function (_super) {
34795     __extends(ZoomComponent, _super);
34796     function ZoomComponent(name, container, navigator) {
34797         var _this = _super.call(this, name, container, navigator) || this;
34798         _this._viewportCoords = new Geo_1.ViewportCoords();
34799         _this._zoomDelta$ = new rxjs_1.Subject();
34800         return _this;
34801     }
34802     ZoomComponent.prototype._activate = function () {
34803         var _this = this;
34804         this._renderSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentState$, this._navigator.stateService.state$).pipe(operators_1.map(function (_a) {
34805             var frame = _a[0], state = _a[1];
34806             return [frame.state.zoom, state];
34807         }), operators_1.map(function (_a) {
34808             var zoom = _a[0], state = _a[1];
34809             var zoomInIcon = vd.h("div.ZoomInIcon", []);
34810             var zoomInButton = zoom >= 3 || state === State_1.State.Waiting ?
34811                 vd.h("div.ZoomInButtonDisabled", [zoomInIcon]) :
34812                 vd.h("div.ZoomInButton", { onclick: function () { _this._zoomDelta$.next(1); } }, [zoomInIcon]);
34813             var zoomOutIcon = vd.h("div.ZoomOutIcon", []);
34814             var zoomOutButton = zoom <= 0 || state === State_1.State.Waiting ?
34815                 vd.h("div.ZoomOutButtonDisabled", [zoomOutIcon]) :
34816                 vd.h("div.ZoomOutButton", { onclick: function () { _this._zoomDelta$.next(-1); } }, [zoomOutIcon]);
34817             return {
34818                 name: _this._name,
34819                 vnode: vd.h("div.ZoomContainer", { oncontextmenu: function (event) { event.preventDefault(); } }, [zoomInButton, zoomOutButton]),
34820             };
34821         }))
34822             .subscribe(this._container.domRenderer.render$);
34823         this._zoomSubscription = this._zoomDelta$.pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
34824             .subscribe(function (_a) {
34825             var zoomDelta = _a[0], render = _a[1], transform = _a[2];
34826             var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
34827             var reference = transform.projectBasic(unprojected.toArray());
34828             _this._navigator.stateService.zoomIn(zoomDelta, reference);
34829         });
34830     };
34831     ZoomComponent.prototype._deactivate = function () {
34832         this._renderSubscription.unsubscribe();
34833         this._zoomSubscription.unsubscribe();
34834     };
34835     ZoomComponent.prototype._getDefaultConfiguration = function () {
34836         return {};
34837     };
34838     ZoomComponent.componentName = "zoom";
34839     return ZoomComponent;
34840 }(Component_1.Component));
34841 exports.ZoomComponent = ZoomComponent;
34842 Component_1.ComponentService.register(ZoomComponent);
34843 exports.default = ZoomComponent;
34844
34845 },{"../../Component":274,"../../Geo":277,"../../State":281,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],377:[function(require,module,exports){
34846 "use strict";
34847 var __extends = (this && this.__extends) || (function () {
34848     var extendStatics = function (d, b) {
34849         extendStatics = Object.setPrototypeOf ||
34850             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34851             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34852         return extendStatics(d, b);
34853     }
34854     return function (d, b) {
34855         extendStatics(d, b);
34856         function __() { this.constructor = d; }
34857         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34858     };
34859 })();
34860 Object.defineProperty(exports, "__esModule", { value: true });
34861 var MapillaryError_1 = require("./MapillaryError");
34862 /**
34863  * @class AbortMapillaryError
34864  *
34865  * @classdesc Error thrown when a move to request has been
34866  * aborted before completing because of a subsequent request.
34867  */
34868 var AbortMapillaryError = /** @class */ (function (_super) {
34869     __extends(AbortMapillaryError, _super);
34870     function AbortMapillaryError(message) {
34871         var _this = _super.call(this, message != null ? message : "The request was aborted.") || this;
34872         Object.setPrototypeOf(_this, AbortMapillaryError.prototype);
34873         _this.name = "AbortMapillaryError";
34874         return _this;
34875     }
34876     return AbortMapillaryError;
34877 }(MapillaryError_1.MapillaryError));
34878 exports.AbortMapillaryError = AbortMapillaryError;
34879 exports.default = AbortMapillaryError;
34880
34881 },{"./MapillaryError":380}],378:[function(require,module,exports){
34882 "use strict";
34883 var __extends = (this && this.__extends) || (function () {
34884     var extendStatics = function (d, b) {
34885         extendStatics = Object.setPrototypeOf ||
34886             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34887             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34888         return extendStatics(d, b);
34889     }
34890     return function (d, b) {
34891         extendStatics(d, b);
34892         function __() { this.constructor = d; }
34893         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34894     };
34895 })();
34896 Object.defineProperty(exports, "__esModule", { value: true });
34897 var MapillaryError_1 = require("./MapillaryError");
34898 var ArgumentMapillaryError = /** @class */ (function (_super) {
34899     __extends(ArgumentMapillaryError, _super);
34900     function ArgumentMapillaryError(message) {
34901         var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
34902         Object.setPrototypeOf(_this, ArgumentMapillaryError.prototype);
34903         _this.name = "ArgumentMapillaryError";
34904         return _this;
34905     }
34906     return ArgumentMapillaryError;
34907 }(MapillaryError_1.MapillaryError));
34908 exports.ArgumentMapillaryError = ArgumentMapillaryError;
34909 exports.default = ArgumentMapillaryError;
34910
34911 },{"./MapillaryError":380}],379:[function(require,module,exports){
34912 "use strict";
34913 var __extends = (this && this.__extends) || (function () {
34914     var extendStatics = function (d, b) {
34915         extendStatics = Object.setPrototypeOf ||
34916             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34917             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34918         return extendStatics(d, b);
34919     }
34920     return function (d, b) {
34921         extendStatics(d, b);
34922         function __() { this.constructor = d; }
34923         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34924     };
34925 })();
34926 Object.defineProperty(exports, "__esModule", { value: true });
34927 var MapillaryError_1 = require("./MapillaryError");
34928 var GraphMapillaryError = /** @class */ (function (_super) {
34929     __extends(GraphMapillaryError, _super);
34930     function GraphMapillaryError(message) {
34931         var _this = _super.call(this, message) || this;
34932         Object.setPrototypeOf(_this, GraphMapillaryError.prototype);
34933         _this.name = "GraphMapillaryError";
34934         return _this;
34935     }
34936     return GraphMapillaryError;
34937 }(MapillaryError_1.MapillaryError));
34938 exports.GraphMapillaryError = GraphMapillaryError;
34939 exports.default = GraphMapillaryError;
34940
34941 },{"./MapillaryError":380}],380:[function(require,module,exports){
34942 "use strict";
34943 var __extends = (this && this.__extends) || (function () {
34944     var extendStatics = function (d, b) {
34945         extendStatics = Object.setPrototypeOf ||
34946             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34947             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34948         return extendStatics(d, b);
34949     }
34950     return function (d, b) {
34951         extendStatics(d, b);
34952         function __() { this.constructor = d; }
34953         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34954     };
34955 })();
34956 Object.defineProperty(exports, "__esModule", { value: true });
34957 var MapillaryError = /** @class */ (function (_super) {
34958     __extends(MapillaryError, _super);
34959     function MapillaryError(message) {
34960         var _this = _super.call(this, message) || this;
34961         Object.setPrototypeOf(_this, MapillaryError.prototype);
34962         _this.name = "MapillaryError";
34963         return _this;
34964     }
34965     return MapillaryError;
34966 }(Error));
34967 exports.MapillaryError = MapillaryError;
34968 exports.default = MapillaryError;
34969
34970 },{}],381:[function(require,module,exports){
34971 "use strict";
34972 Object.defineProperty(exports, "__esModule", { value: true });
34973 var THREE = require("three");
34974 /**
34975  * @class Camera
34976  *
34977  * @classdesc Holds information about a camera.
34978  */
34979 var Camera = /** @class */ (function () {
34980     /**
34981      * Create a new camera instance.
34982      * @param {Transform} [transform] - Optional transform instance.
34983      */
34984     function Camera(transform) {
34985         if (transform != null) {
34986             this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
34987             this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
34988             this._up = transform.upVector();
34989             this._focal = this._getFocal(transform);
34990         }
34991         else {
34992             this._position = new THREE.Vector3(0, 0, 0);
34993             this._lookat = new THREE.Vector3(0, 0, 1);
34994             this._up = new THREE.Vector3(0, -1, 0);
34995             this._focal = 1;
34996         }
34997     }
34998     Object.defineProperty(Camera.prototype, "position", {
34999         /**
35000          * Get position.
35001          * @returns {THREE.Vector3} The position vector.
35002          */
35003         get: function () {
35004             return this._position;
35005         },
35006         enumerable: true,
35007         configurable: true
35008     });
35009     Object.defineProperty(Camera.prototype, "lookat", {
35010         /**
35011          * Get lookat.
35012          * @returns {THREE.Vector3} The lookat vector.
35013          */
35014         get: function () {
35015             return this._lookat;
35016         },
35017         enumerable: true,
35018         configurable: true
35019     });
35020     Object.defineProperty(Camera.prototype, "up", {
35021         /**
35022          * Get up.
35023          * @returns {THREE.Vector3} The up vector.
35024          */
35025         get: function () {
35026             return this._up;
35027         },
35028         enumerable: true,
35029         configurable: true
35030     });
35031     Object.defineProperty(Camera.prototype, "focal", {
35032         /**
35033          * Get focal.
35034          * @returns {number} The focal length.
35035          */
35036         get: function () {
35037             return this._focal;
35038         },
35039         /**
35040          * Set focal.
35041          */
35042         set: function (value) {
35043             this._focal = value;
35044         },
35045         enumerable: true,
35046         configurable: true
35047     });
35048     /**
35049      * Update this camera to the linearly interpolated value of two other cameras.
35050      *
35051      * @param {Camera} a - First camera.
35052      * @param {Camera} b - Second camera.
35053      * @param {number} alpha - Interpolation value on the interval [0, 1].
35054      */
35055     Camera.prototype.lerpCameras = function (a, b, alpha) {
35056         this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
35057         this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
35058         this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
35059         this._focal = (1 - alpha) * a.focal + alpha * b.focal;
35060     };
35061     /**
35062      * Copy the properties of another camera to this camera.
35063      *
35064      * @param {Camera} other - Another camera.
35065      */
35066     Camera.prototype.copy = function (other) {
35067         this._position.copy(other.position);
35068         this._lookat.copy(other.lookat);
35069         this._up.copy(other.up);
35070         this._focal = other.focal;
35071     };
35072     /**
35073      * Clone this camera.
35074      *
35075      * @returns {Camera} A camera with cloned properties equal to this camera.
35076      */
35077     Camera.prototype.clone = function () {
35078         var camera = new Camera();
35079         camera.position.copy(this._position);
35080         camera.lookat.copy(this._lookat);
35081         camera.up.copy(this._up);
35082         camera.focal = this._focal;
35083         return camera;
35084     };
35085     /**
35086      * Determine the distance between this camera and another camera.
35087      *
35088      * @param {Camera} other - Another camera.
35089      * @returns {number} The distance between the cameras.
35090      */
35091     Camera.prototype.diff = function (other) {
35092         var pd = this._position.distanceToSquared(other.position);
35093         var ld = this._lookat.distanceToSquared(other.lookat);
35094         var ud = this._up.distanceToSquared(other.up);
35095         var fd = 100 * Math.abs(this._focal - other.focal);
35096         return Math.max(pd, ld, ud, fd);
35097     };
35098     /**
35099      * Get the focal length based on the transform.
35100      *
35101      * @description Returns the focal length of the transform if gpano info is not available.
35102      * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
35103      * the gpano information if available.
35104      *
35105      * @returns {number} Focal length.
35106      */
35107     Camera.prototype._getFocal = function (transform) {
35108         if (transform.gpano == null) {
35109             return transform.focal;
35110         }
35111         var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
35112         var focal = 0.5 / Math.tan(vFov / 2);
35113         return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
35114     };
35115     return Camera;
35116 }());
35117 exports.Camera = Camera;
35118
35119 },{"three":225}],382:[function(require,module,exports){
35120 "use strict";
35121 Object.defineProperty(exports, "__esModule", { value: true });
35122 var Geo_1 = require("../Geo");
35123 var geoCoords = new Geo_1.GeoCoords();
35124 var spatial = new Geo_1.Spatial();
35125 function computeTranslation(position, rotation, reference) {
35126     var C = geoCoords.geodeticToEnu(position.lat, position.lon, position.alt, reference.lat, reference.lon, reference.alt);
35127     var RC = spatial.rotate(C, rotation);
35128     var translation = [-RC.x, -RC.y, -RC.z];
35129     return translation;
35130 }
35131 exports.computeTranslation = computeTranslation;
35132
35133 },{"../Geo":277}],383:[function(require,module,exports){
35134 "use strict";
35135 Object.defineProperty(exports, "__esModule", { value: true });
35136 /**
35137  * @class GeoCoords
35138  *
35139  * @classdesc Converts coordinates between the geodetic (WGS84),
35140  * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
35141  * East, North, Up (ENU) reference frames.
35142  *
35143  * The WGS84 has latitude (degrees), longitude (degrees) and
35144  * altitude (meters) values.
35145  *
35146  * The ECEF Z-axis pierces the north pole and the
35147  * XY-axis defines the equatorial plane. The X-axis extends
35148  * from the geocenter to the intersection of the Equator and
35149  * the Greenwich Meridian. All values in meters.
35150  *
35151  * The WGS84 parameters are:
35152  *
35153  * a = 6378137
35154  * b = a * (1 - f)
35155  * f = 1 / 298.257223563
35156  * e = Math.sqrt((a^2 - b^2) / a^2)
35157  * e' = Math.sqrt((a^2 - b^2) / b^2)
35158  *
35159  * The WGS84 to ECEF conversion is performed using the following:
35160  *
35161  * X = (N - h) * cos(phi) * cos(lambda)
35162  * Y = (N + h) * cos(phi) * sin(lambda)
35163  * Z = (b^2 * N / a^2 + h) * sin(phi)
35164  *
35165  * where
35166  *
35167  * phi = latitude
35168  * lambda = longitude
35169  * h = height above ellipsoid (altitude)
35170  * N = Radius of curvature (meters)
35171  *   = a / Math.sqrt(1 - e^2 * sin(phi)^2)
35172  *
35173  * The ECEF to WGS84 conversion is performed using the following:
35174  *
35175  * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
35176  * lambda = arctan(Y / X)
35177  * h = p / cos(phi) - N
35178  *
35179  * where
35180  *
35181  * p = Math.sqrt(X^2 + Y^2)
35182  * theta = arctan(Z * a / p * b)
35183  *
35184  * In the ENU reference frame the x-axis points to the
35185  * East, the y-axis to the North and the z-axis Up. All values
35186  * in meters.
35187  *
35188  * The ECEF to ENU conversion is performed using the following:
35189  *
35190  * | x |   |       -sin(lambda_r)                cos(lambda_r)             0      | | X - X_r |
35191  * | y | = | -sin(phi_r) * cos(lambda_r)  -sin(phi_r) * sin(lambda_r)  cos(phi_r) | | Y - Y_r |
35192  * | z |   |  cos(phi_r) * cos(lambda_r)   cos(phi_r) * sin(lambda_r)  sin(phi_r) | | Z - Z_r |
35193  *
35194  * where
35195  *
35196  * phi_r = latitude of reference
35197  * lambda_r = longitude of reference
35198  * X_r, Y_r, Z_r = ECEF coordinates of reference
35199  *
35200  * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
35201  *
35202  * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
35203  * the first step for both conversions.
35204  */
35205 var GeoCoords = /** @class */ (function () {
35206     function GeoCoords() {
35207         this._wgs84a = 6378137.0;
35208         this._wgs84b = 6356752.31424518;
35209     }
35210     /**
35211      * Convert coordinates from geodetic (WGS84) reference to local topocentric
35212      * (ENU) reference.
35213      *
35214      * @param {number} lat Latitude in degrees.
35215      * @param {number} lon Longitude in degrees.
35216      * @param {number} alt Altitude in meters.
35217      * @param {number} refLat Reference latitude in degrees.
35218      * @param {number} refLon Reference longitude in degrees.
35219      * @param {number} refAlt Reference altitude in meters.
35220      * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
35221      */
35222     GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
35223         var ecef = this.geodeticToEcef(lat, lon, alt);
35224         return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
35225     };
35226     /**
35227      * Convert coordinates from local topocentric (ENU) reference to
35228      * geodetic (WGS84) reference.
35229      *
35230      * @param {number} x Topocentric ENU coordinate in East direction.
35231      * @param {number} y Topocentric ENU coordinate in North direction.
35232      * @param {number} z Topocentric ENU coordinate in Up direction.
35233      * @param {number} refLat Reference latitude in degrees.
35234      * @param {number} refLon Reference longitude in degrees.
35235      * @param {number} refAlt Reference altitude in meters.
35236      * @returns {Array<number>} The latitude and longitude in degrees
35237      *                          as well as altitude in meters.
35238      */
35239     GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
35240         var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
35241         return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
35242     };
35243     /**
35244      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
35245      * to local topocentric (ENU) reference.
35246      *
35247      * @param {number} X ECEF X-value.
35248      * @param {number} Y ECEF Y-value.
35249      * @param {number} Z ECEF Z-value.
35250      * @param {number} refLat Reference latitude in degrees.
35251      * @param {number} refLon Reference longitude in degrees.
35252      * @param {number} refAlt Reference altitude in meters.
35253      * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
35254      * and Up directions respectively.
35255      */
35256     GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
35257         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
35258         var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
35259         refLat = refLat * Math.PI / 180.0;
35260         refLon = refLon * Math.PI / 180.0;
35261         var cosLat = Math.cos(refLat);
35262         var sinLat = Math.sin(refLat);
35263         var cosLon = Math.cos(refLon);
35264         var sinLon = Math.sin(refLon);
35265         var x = -sinLon * V[0] + cosLon * V[1];
35266         var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
35267         var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
35268         return [x, y, z];
35269     };
35270     /**
35271      * Convert coordinates from local topocentric (ENU) reference
35272      * to Earth-Centered, Earth-Fixed (ECEF) reference.
35273      *
35274      * @param {number} x Topocentric ENU coordinate in East direction.
35275      * @param {number} y Topocentric ENU coordinate in North direction.
35276      * @param {number} z Topocentric ENU coordinate in Up direction.
35277      * @param {number} refLat Reference latitude in degrees.
35278      * @param {number} refLon Reference longitude in degrees.
35279      * @param {number} refAlt Reference altitude in meters.
35280      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
35281      */
35282     GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
35283         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
35284         refLat = refLat * Math.PI / 180.0;
35285         refLon = refLon * Math.PI / 180.0;
35286         var cosLat = Math.cos(refLat);
35287         var sinLat = Math.sin(refLat);
35288         var cosLon = Math.cos(refLon);
35289         var sinLon = Math.sin(refLon);
35290         var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
35291         var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
35292         var Z = cosLat * y + sinLat * z + refEcef[2];
35293         return [X, Y, Z];
35294     };
35295     /**
35296      * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
35297      * Earth-Fixed (ECEF) reference.
35298      *
35299      * @param {number} lat Latitude in degrees.
35300      * @param {number} lon Longitude in degrees.
35301      * @param {number} alt Altitude in meters.
35302      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
35303      */
35304     GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
35305         var a = this._wgs84a;
35306         var b = this._wgs84b;
35307         lat = lat * Math.PI / 180.0;
35308         lon = lon * Math.PI / 180.0;
35309         var cosLat = Math.cos(lat);
35310         var sinLat = Math.sin(lat);
35311         var cosLon = Math.cos(lon);
35312         var sinLon = Math.sin(lon);
35313         var a2 = a * a;
35314         var b2 = b * b;
35315         var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
35316         var nhcl = (a2 * L + alt) * cosLat;
35317         var X = nhcl * cosLon;
35318         var Y = nhcl * sinLon;
35319         var Z = (b2 * L + alt) * sinLat;
35320         return [X, Y, Z];
35321     };
35322     /**
35323      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
35324      * to geodetic reference (WGS84).
35325      *
35326      * @param {number} X ECEF X-value.
35327      * @param {number} Y ECEF Y-value.
35328      * @param {number} Z ECEF Z-value.
35329      * @returns {Array<number>} The latitude and longitude in degrees
35330      *                          as well as altitude in meters.
35331      */
35332     GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
35333         var a = this._wgs84a;
35334         var b = this._wgs84b;
35335         var a2 = a * a;
35336         var b2 = b * b;
35337         var a2mb2 = a2 - b2;
35338         var ea = Math.sqrt(a2mb2 / a2);
35339         var eb = Math.sqrt(a2mb2 / b2);
35340         var p = Math.sqrt(X * X + Y * Y);
35341         var theta = Math.atan2(Z * a, p * b);
35342         var sinTheta = Math.sin(theta);
35343         var cosTheta = Math.cos(theta);
35344         var lon = Math.atan2(Y, X);
35345         var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
35346         var sinLat = Math.sin(lat);
35347         var cosLat = Math.cos(lat);
35348         var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
35349         var alt = p / cosLat - N;
35350         return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
35351     };
35352     return GeoCoords;
35353 }());
35354 exports.GeoCoords = GeoCoords;
35355 exports.default = GeoCoords;
35356
35357 },{}],384:[function(require,module,exports){
35358 "use strict";
35359 Object.defineProperty(exports, "__esModule", { value: true });
35360 function sign(n) {
35361     return n > 0 ? 1 : n < 0 ? -1 : 0;
35362 }
35363 function colinearPointOnSegment(p, s) {
35364     return p.x <= Math.max(s.p1.x, s.p2.x) &&
35365         p.x >= Math.min(s.p1.x, s.p2.x) &&
35366         p.y >= Math.max(s.p1.y, s.p2.y) &&
35367         p.y >= Math.min(s.p1.y, s.p2.y);
35368 }
35369 function parallel(s1, s2) {
35370     var ux = s1.p2.x - s1.p1.x;
35371     var uy = s1.p2.y - s1.p1.y;
35372     var vx = s2.p2.x - s2.p1.x;
35373     var vy = s2.p2.y - s2.p1.y;
35374     var cross = ux * vy - uy * vx;
35375     var u2 = ux * ux + uy * uy;
35376     var v2 = vx * vx + vy * vy;
35377     var epsilon2 = 1e-10;
35378     return cross * cross < epsilon2 * u2 * v2;
35379 }
35380 function tripletOrientation(p1, p2, p3) {
35381     var orientation = (p2.y - p1.y) * (p3.x - p2.x) -
35382         (p3.y - p2.y) * (p2.x - p1.x);
35383     return sign(orientation);
35384 }
35385 function segmentsIntersect(s1, s2) {
35386     if (parallel(s1, s2)) {
35387         return false;
35388     }
35389     var o1 = tripletOrientation(s1.p1, s1.p2, s2.p1);
35390     var o2 = tripletOrientation(s1.p1, s1.p2, s2.p2);
35391     var o3 = tripletOrientation(s2.p1, s2.p2, s1.p1);
35392     var o4 = tripletOrientation(s2.p1, s2.p2, s1.p2);
35393     if (o1 !== o2 && o3 !== o4) {
35394         return true;
35395     }
35396     if (o1 === 0 && colinearPointOnSegment(s2.p1, s1)) {
35397         return true;
35398     }
35399     if (o2 === 0 && colinearPointOnSegment(s2.p2, s1)) {
35400         return true;
35401     }
35402     if (o3 === 0 && colinearPointOnSegment(s1.p1, s2)) {
35403         return true;
35404     }
35405     if (o4 === 0 && colinearPointOnSegment(s1.p2, s2)) {
35406         return true;
35407     }
35408     return false;
35409 }
35410 exports.segmentsIntersect = segmentsIntersect;
35411 function segmentIntersection(s1, s2) {
35412     if (parallel(s1, s2)) {
35413         return undefined;
35414     }
35415     var x1 = s1.p1.x;
35416     var x2 = s1.p2.x;
35417     var y1 = s1.p1.y;
35418     var y2 = s1.p2.y;
35419     var x3 = s2.p1.x;
35420     var x4 = s2.p2.x;
35421     var y3 = s2.p1.y;
35422     var y4 = s2.p2.y;
35423     var den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
35424     var xNum = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4);
35425     var yNum = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4);
35426     return { x: xNum / den, y: yNum / den };
35427 }
35428 exports.segmentIntersection = segmentIntersection;
35429
35430 },{}],385:[function(require,module,exports){
35431 "use strict";
35432 Object.defineProperty(exports, "__esModule", { value: true });
35433 var THREE = require("three");
35434 /**
35435  * @class Spatial
35436  *
35437  * @classdesc Provides methods for scalar, vector and matrix calculations.
35438  */
35439 var Spatial = /** @class */ (function () {
35440     function Spatial() {
35441         this._epsilon = 1e-9;
35442     }
35443     /**
35444      * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
35445      * bearing (clockwise with origin at north or Y-axis).
35446      *
35447      * @param {number} phi - Azimuthal phi angle in radians.
35448      * @returns {number} Bearing in radians.
35449      */
35450     Spatial.prototype.azimuthalToBearing = function (phi) {
35451         return -phi + Math.PI / 2;
35452     };
35453     /**
35454      * Converts degrees to radians.
35455      *
35456      * @param {number} deg - Degrees.
35457      * @returns {number} Radians.
35458      */
35459     Spatial.prototype.degToRad = function (deg) {
35460         return Math.PI * deg / 180;
35461     };
35462     /**
35463      * Converts radians to degrees.
35464      *
35465      * @param {number} rad - Radians.
35466      * @returns {number} Degrees.
35467      */
35468     Spatial.prototype.radToDeg = function (rad) {
35469         return 180 * rad / Math.PI;
35470     };
35471     /**
35472      * Creates a rotation matrix from an angle-axis vector.
35473      *
35474      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
35475      * @returns {THREE.Matrix4} Rotation matrix.
35476      */
35477     Spatial.prototype.rotationMatrix = function (angleAxis) {
35478         var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
35479         var angle = axis.length();
35480         if (angle > 0) {
35481             axis.normalize();
35482         }
35483         return new THREE.Matrix4().makeRotationAxis(axis, angle);
35484     };
35485     /**
35486      * Rotates a vector according to a angle-axis rotation vector.
35487      *
35488      * @param {Array<number>} vector - Vector to rotate.
35489      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
35490      * @returns {THREE.Vector3} Rotated vector.
35491      */
35492     Spatial.prototype.rotate = function (vector, angleAxis) {
35493         var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
35494         var rotationMatrix = this.rotationMatrix(angleAxis);
35495         v.applyMatrix4(rotationMatrix);
35496         return v;
35497     };
35498     /**
35499      * Calculates the optical center from a rotation vector
35500      * on the angle-axis representation and a translation vector
35501      * according to C = -R^T t.
35502      *
35503      * @param {Array<number>} rotation - Angle-axis representation of a rotation.
35504      * @param {Array<number>} translation - Translation vector.
35505      * @returns {THREE.Vector3} Optical center.
35506      */
35507     Spatial.prototype.opticalCenter = function (rotation, translation) {
35508         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
35509         var vector = [-translation[0], -translation[1], -translation[2]];
35510         return this.rotate(vector, angleAxis);
35511     };
35512     /**
35513      * Calculates the viewing direction from a rotation vector
35514      * on the angle-axis representation.
35515      *
35516      * @param {number[]} rotation - Angle-axis representation of a rotation.
35517      * @returns {THREE.Vector3} Viewing direction.
35518      */
35519     Spatial.prototype.viewingDirection = function (rotation) {
35520         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
35521         return this.rotate([0, 0, 1], angleAxis);
35522     };
35523     /**
35524      * Wrap a number on the interval [min, max].
35525      *
35526      * @param {number} value - Value to wrap.
35527      * @param {number} min - Lower endpoint of interval.
35528      * @param {number} max - Upper endpoint of interval.
35529      * @returns {number} The wrapped number.
35530      */
35531     Spatial.prototype.wrap = function (value, min, max) {
35532         if (max < min) {
35533             throw new Error("Invalid arguments: max must be larger than min.");
35534         }
35535         var interval = (max - min);
35536         while (value > max || value < min) {
35537             if (value > max) {
35538                 value = value - interval;
35539             }
35540             else if (value < min) {
35541                 value = value + interval;
35542             }
35543         }
35544         return value;
35545     };
35546     /**
35547      * Wrap an angle on the interval [-Pi, Pi].
35548      *
35549      * @param {number} angle - Value to wrap.
35550      * @returns {number} Wrapped angle.
35551      */
35552     Spatial.prototype.wrapAngle = function (angle) {
35553         return this.wrap(angle, -Math.PI, Math.PI);
35554     };
35555     /**
35556      * Limit the value to the interval [min, max] by changing the value to
35557      * the nearest available one when it is outside the interval.
35558      *
35559      * @param {number} value - Value to clamp.
35560      * @param {number} min - Minimum of the interval.
35561      * @param {number} max - Maximum of the interval.
35562      * @returns {number} Clamped value.
35563      */
35564     Spatial.prototype.clamp = function (value, min, max) {
35565         if (value < min) {
35566             return min;
35567         }
35568         if (value > max) {
35569             return max;
35570         }
35571         return value;
35572     };
35573     /**
35574      * Calculates the counter-clockwise angle from the first
35575      * vector (x1, y1)^T to the second (x2, y2)^T.
35576      *
35577      * @param {number} x1 - X coordinate of first vector.
35578      * @param {number} y1 - Y coordinate of first vector.
35579      * @param {number} x2 - X coordinate of second vector.
35580      * @param {number} y2 - Y coordinate of second vector.
35581      * @returns {number} Counter clockwise angle between the vectors.
35582      */
35583     Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
35584         var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
35585         return this.wrapAngle(angle);
35586     };
35587     /**
35588      * Calculates the minimum (absolute) angle change for rotation
35589      * from one angle to another on the [-Pi, Pi] interval.
35590      *
35591      * @param {number} angle1 - Start angle.
35592      * @param {number} angle2 - Destination angle.
35593      * @returns {number} Absolute angle change between angles.
35594      */
35595     Spatial.prototype.angleDifference = function (angle1, angle2) {
35596         var angle = angle2 - angle1;
35597         return this.wrapAngle(angle);
35598     };
35599     /**
35600      * Calculates the relative rotation angle between two
35601      * angle-axis vectors.
35602      *
35603      * @param {number} rotation1 - First angle-axis vector.
35604      * @param {number} rotation2 - Second angle-axis vector.
35605      * @returns {number} Relative rotation angle.
35606      */
35607     Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
35608         var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
35609         var R2 = this.rotationMatrix(rotation2);
35610         var R = R1T.multiply(R2);
35611         var elements = R.elements;
35612         // from Tr(R) = 1 + 2 * cos(theta)
35613         var tr = elements[0] + elements[5] + elements[10];
35614         var theta = Math.acos(Math.max(Math.min((tr - 1) / 2, 1), -1));
35615         return theta;
35616     };
35617     /**
35618      * Calculates the angle from a vector to a plane.
35619      *
35620      * @param {Array<number>} vector - The vector.
35621      * @param {Array<number>} planeNormal - Normal of the plane.
35622      * @returns {number} Angle from between plane and vector.
35623      */
35624     Spatial.prototype.angleToPlane = function (vector, planeNormal) {
35625         var v = new THREE.Vector3().fromArray(vector);
35626         var norm = v.length();
35627         if (norm < this._epsilon) {
35628             return 0;
35629         }
35630         var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
35631         return Math.asin(projection / norm);
35632     };
35633     /**
35634      * Calculates the distance between two coordinates
35635      * (latitude longitude pairs) in meters according to
35636      * the haversine formula.
35637      *
35638      * @param {number} lat1 - Latitude of the first coordinate in degrees.
35639      * @param {number} lon1 - Longitude of the first coordinate in degrees.
35640      * @param {number} lat2 - Latitude of the second coordinate in degrees.
35641      * @param {number} lon2 - Longitude of the second coordinate in degrees.
35642      * @returns {number} Distance between lat lon positions in meters.
35643      */
35644     Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
35645         var r = 6371000;
35646         var dLat = this.degToRad(lat2 - lat1);
35647         var dLon = this.degToRad(lon2 - lon1);
35648         var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
35649             Math.cos(this.degToRad(lat1)) * Math.cos(this.degToRad(lat2)) *
35650                 Math.sin(dLon / 2) * Math.sin(dLon / 2);
35651         var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
35652         return d;
35653     };
35654     return Spatial;
35655 }());
35656 exports.Spatial = Spatial;
35657 exports.default = Spatial;
35658
35659 },{"three":225}],386:[function(require,module,exports){
35660 "use strict";
35661 Object.defineProperty(exports, "__esModule", { value: true });
35662 var THREE = require("three");
35663 /**
35664  * @class Transform
35665  *
35666  * @classdesc Class used for calculating coordinate transformations
35667  * and projections.
35668  */
35669 var Transform = /** @class */ (function () {
35670     /**
35671      * Create a new transform instance.
35672      * @param {number} orientation - Image orientation.
35673      * @param {number} width - Image height.
35674      * @param {number} height - Image width.
35675      * @param {number} focal - Focal length.
35676      * @param {number} scale - Atomic scale.
35677      * @param {IGPano} gpano - Panorama properties.
35678      * @param {Array<number>} rotation - Rotation vector in three dimensions.
35679      * @param {Array<number>} translation - Translation vector in three dimensions.
35680      * @param {HTMLImageElement} image - Image for fallback size calculations.
35681      */
35682     function Transform(orientation, width, height, focal, scale, gpano, rotation, translation, image, textureScale, ck1, ck2) {
35683         this._orientation = this._getValue(orientation, 1);
35684         var imageWidth = image != null ? image.width : 4;
35685         var imageHeight = image != null ? image.height : 3;
35686         var keepOrientation = this._orientation < 5;
35687         this._width = this._getValue(width, keepOrientation ? imageWidth : imageHeight);
35688         this._height = this._getValue(height, keepOrientation ? imageHeight : imageWidth);
35689         this._basicAspect = keepOrientation ?
35690             this._width / this._height :
35691             this._height / this._width;
35692         this._basicWidth = keepOrientation ? width : height;
35693         this._basicHeight = keepOrientation ? height : width;
35694         this._focal = this._getValue(focal, 1);
35695         this._scale = this._getValue(scale, 0);
35696         this._gpano = gpano != null ? gpano : null;
35697         this._rt = this._getRt(rotation, translation);
35698         this._srt = this._getSrt(this._rt, this._scale);
35699         this._basicRt = this._getBasicRt(this._rt, orientation);
35700         this._textureScale = !!textureScale ? textureScale : [1, 1];
35701         this._ck1 = !!ck1 ? ck1 : 0;
35702         this._ck2 = !!ck2 ? ck2 : 0;
35703         this._radialPeak = this._getRadialPeak(this._ck1, this._ck2);
35704     }
35705     Object.defineProperty(Transform.prototype, "ck1", {
35706         get: function () {
35707             return this._ck1;
35708         },
35709         enumerable: true,
35710         configurable: true
35711     });
35712     Object.defineProperty(Transform.prototype, "ck2", {
35713         get: function () {
35714             return this._ck2;
35715         },
35716         enumerable: true,
35717         configurable: true
35718     });
35719     Object.defineProperty(Transform.prototype, "basicAspect", {
35720         /**
35721          * Get basic aspect.
35722          * @returns {number} The orientation adjusted aspect ratio.
35723          */
35724         get: function () {
35725             return this._basicAspect;
35726         },
35727         enumerable: true,
35728         configurable: true
35729     });
35730     Object.defineProperty(Transform.prototype, "basicHeight", {
35731         /**
35732          * Get basic height.
35733          *
35734          * @description Does not fall back to node image height but
35735          * uses original value from API so can be faulty.
35736          *
35737          * @returns {number} The height of the basic version image
35738          * (adjusted for orientation).
35739          */
35740         get: function () {
35741             return this._basicHeight;
35742         },
35743         enumerable: true,
35744         configurable: true
35745     });
35746     Object.defineProperty(Transform.prototype, "basicRt", {
35747         get: function () {
35748             return this._basicRt;
35749         },
35750         enumerable: true,
35751         configurable: true
35752     });
35753     Object.defineProperty(Transform.prototype, "basicWidth", {
35754         /**
35755          * Get basic width.
35756          *
35757          * @description Does not fall back to node image width but
35758          * uses original value from API so can be faulty.
35759          *
35760          * @returns {number} The width of the basic version image
35761          * (adjusted for orientation).
35762          */
35763         get: function () {
35764             return this._basicWidth;
35765         },
35766         enumerable: true,
35767         configurable: true
35768     });
35769     Object.defineProperty(Transform.prototype, "focal", {
35770         /**
35771          * Get focal.
35772          * @returns {number} The node focal length.
35773          */
35774         get: function () {
35775             return this._focal;
35776         },
35777         enumerable: true,
35778         configurable: true
35779     });
35780     Object.defineProperty(Transform.prototype, "fullPano", {
35781         /**
35782          * Get fullPano.
35783          *
35784          * @returns {boolean} Value indicating whether the node is a complete
35785          * 360 panorama.
35786          */
35787         get: function () {
35788             return this._gpano != null &&
35789                 this._gpano.CroppedAreaLeftPixels === 0 &&
35790                 this._gpano.CroppedAreaTopPixels === 0 &&
35791                 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
35792                 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
35793         },
35794         enumerable: true,
35795         configurable: true
35796     });
35797     Object.defineProperty(Transform.prototype, "gpano", {
35798         /**
35799          * Get gpano.
35800          * @returns {number} The node gpano information.
35801          */
35802         get: function () {
35803             return this._gpano;
35804         },
35805         enumerable: true,
35806         configurable: true
35807     });
35808     Object.defineProperty(Transform.prototype, "height", {
35809         /**
35810          * Get height.
35811          *
35812          * @description Falls back to the node image height if
35813          * the API data is faulty.
35814          *
35815          * @returns {number} The orientation adjusted image height.
35816          */
35817         get: function () {
35818             return this._height;
35819         },
35820         enumerable: true,
35821         configurable: true
35822     });
35823     Object.defineProperty(Transform.prototype, "orientation", {
35824         /**
35825          * Get orientation.
35826          * @returns {number} The image orientation.
35827          */
35828         get: function () {
35829             return this._orientation;
35830         },
35831         enumerable: true,
35832         configurable: true
35833     });
35834     Object.defineProperty(Transform.prototype, "rt", {
35835         /**
35836          * Get rt.
35837          * @returns {THREE.Matrix4} The extrinsic camera matrix.
35838          */
35839         get: function () {
35840             return this._rt;
35841         },
35842         enumerable: true,
35843         configurable: true
35844     });
35845     Object.defineProperty(Transform.prototype, "srt", {
35846         /**
35847          * Get srt.
35848          * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
35849          */
35850         get: function () {
35851             return this._srt;
35852         },
35853         enumerable: true,
35854         configurable: true
35855     });
35856     Object.defineProperty(Transform.prototype, "scale", {
35857         /**
35858          * Get scale.
35859          * @returns {number} The node atomic reconstruction scale.
35860          */
35861         get: function () {
35862             return this._scale;
35863         },
35864         enumerable: true,
35865         configurable: true
35866     });
35867     Object.defineProperty(Transform.prototype, "hasValidScale", {
35868         /**
35869          * Get has valid scale.
35870          * @returns {boolean} Value indicating if the scale of the transform is valid.
35871          */
35872         get: function () {
35873             return this._scale > 1e-2 && this._scale < 50;
35874         },
35875         enumerable: true,
35876         configurable: true
35877     });
35878     Object.defineProperty(Transform.prototype, "radialPeak", {
35879         /**
35880          * Get radial peak.
35881          * @returns {number} Value indicating the radius where the radial
35882          * undistortion function peaks.
35883          */
35884         get: function () {
35885             return this._radialPeak;
35886         },
35887         enumerable: true,
35888         configurable: true
35889     });
35890     Object.defineProperty(Transform.prototype, "width", {
35891         /**
35892          * Get width.
35893          *
35894          * @description Falls back to the node image width if
35895          * the API data is faulty.
35896          *
35897          * @returns {number} The orientation adjusted image width.
35898          */
35899         get: function () {
35900             return this._width;
35901         },
35902         enumerable: true,
35903         configurable: true
35904     });
35905     /**
35906      * Calculate the up vector for the node transform.
35907      *
35908      * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
35909      */
35910     Transform.prototype.upVector = function () {
35911         var rte = this._rt.elements;
35912         switch (this._orientation) {
35913             case 1:
35914                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
35915             case 3:
35916                 return new THREE.Vector3(rte[1], rte[5], rte[9]);
35917             case 6:
35918                 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
35919             case 8:
35920                 return new THREE.Vector3(rte[0], rte[4], rte[8]);
35921             default:
35922                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
35923         }
35924     };
35925     /**
35926      * Calculate projector matrix for projecting 3D points to texture map
35927      * coordinates (u and v).
35928      *
35929      * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
35930      * map coordinate calculations.
35931      */
35932     Transform.prototype.projectorMatrix = function () {
35933         var projector = this._normalizedToTextureMatrix();
35934         var f = this._focal;
35935         var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
35936         projector.multiply(projection);
35937         projector.multiply(this._rt);
35938         return projector;
35939     };
35940     /**
35941      * Project 3D world coordinates to basic coordinates.
35942      *
35943      * @param {Array<number>} point3d - 3D world coordinates.
35944      * @return {Array<number>} 2D basic coordinates.
35945      */
35946     Transform.prototype.projectBasic = function (point3d) {
35947         var sfm = this.projectSfM(point3d);
35948         return this._sfmToBasic(sfm);
35949     };
35950     /**
35951      * Unproject basic coordinates to 3D world coordinates.
35952      *
35953      * @param {Array<number>} basic - 2D basic coordinates.
35954      * @param {Array<number>} distance - Distance to unproject from camera center.
35955      * @param {boolean} [depth] - Treat the distance value as depth from camera center.
35956      *                            Only applicable for perspective images. Will be
35957      *                            ignored for panoramas.
35958      * @returns {Array<number>} Unprojected 3D world coordinates.
35959      */
35960     Transform.prototype.unprojectBasic = function (basic, distance, depth) {
35961         var sfm = this._basicToSfm(basic);
35962         return this.unprojectSfM(sfm, distance, depth);
35963     };
35964     /**
35965      * Project 3D world coordinates to SfM coordinates.
35966      *
35967      * @param {Array<number>} point3d - 3D world coordinates.
35968      * @return {Array<number>} 2D SfM coordinates.
35969      */
35970     Transform.prototype.projectSfM = function (point3d) {
35971         var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
35972         v.applyMatrix4(this._rt);
35973         return this._bearingToSfm([v.x, v.y, v.z]);
35974     };
35975     /**
35976      * Unproject SfM coordinates to a 3D world coordinates.
35977      *
35978      * @param {Array<number>} sfm - 2D SfM coordinates.
35979      * @param {Array<number>} distance - Distance to unproject from camera center.
35980      * @param {boolean} [depth] - Treat the distance value as depth from camera center.
35981      *                            Only applicable for perspective images. Will be
35982      *                            ignored for panoramas.
35983      * @returns {Array<number>} Unprojected 3D world coordinates.
35984      */
35985     Transform.prototype.unprojectSfM = function (sfm, distance, depth) {
35986         var bearing = this._sfmToBearing(sfm);
35987         var v = depth && !this.gpano ?
35988             new THREE.Vector4(distance * bearing[0] / bearing[2], distance * bearing[1] / bearing[2], distance, 1) :
35989             new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
35990         v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
35991         return [v.x / v.w, v.y / v.w, v.z / v.w];
35992     };
35993     /**
35994      * Transform SfM coordinates to bearing vector (3D cartesian
35995      * coordinates on the unit sphere).
35996      *
35997      * @param {Array<number>} sfm - 2D SfM coordinates.
35998      * @returns {Array<number>} Bearing vector (3D cartesian coordinates
35999      * on the unit sphere).
36000      */
36001     Transform.prototype._sfmToBearing = function (sfm) {
36002         if (this._fullPano()) {
36003             var lon = sfm[0] * 2 * Math.PI;
36004             var lat = -sfm[1] * 2 * Math.PI;
36005             var x = Math.cos(lat) * Math.sin(lon);
36006             var y = -Math.sin(lat);
36007             var z = Math.cos(lat) * Math.cos(lon);
36008             return [x, y, z];
36009         }
36010         else if (this._gpano) {
36011             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
36012             var fullPanoPixel = [
36013                 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
36014                 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
36015             ];
36016             var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
36017             var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
36018             var x = Math.cos(lat) * Math.sin(lon);
36019             var y = -Math.sin(lat);
36020             var z = Math.cos(lat) * Math.cos(lon);
36021             return [x, y, z];
36022         }
36023         else {
36024             var _a = [sfm[0] / this._focal, sfm[1] / this._focal], dxn = _a[0], dyn = _a[1];
36025             var rp = this._radialPeak;
36026             var dr = Math.sqrt(dxn * dxn + dyn * dyn);
36027             var d = 1.0;
36028             for (var i = 0; i < 10; i++) {
36029                 var r = dr / d;
36030                 if (r > rp) {
36031                     r = rp;
36032                 }
36033                 d = 1 + this._ck1 * Math.pow(r, 2) + this._ck2 * Math.pow(r, 4);
36034             }
36035             var xn = dxn / d;
36036             var yn = dyn / d;
36037             var v = new THREE.Vector3(xn, yn, 1);
36038             v.normalize();
36039             return [v.x, v.y, v.z];
36040         }
36041     };
36042     /**
36043      * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
36044      * SfM coordinates.
36045      *
36046      * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
36047      * unit sphere).
36048      * @returns {Array<number>} 2D SfM coordinates.
36049      */
36050     Transform.prototype._bearingToSfm = function (bearing) {
36051         if (this._fullPano()) {
36052             var x = bearing[0];
36053             var y = bearing[1];
36054             var z = bearing[2];
36055             var lon = Math.atan2(x, z);
36056             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
36057             return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
36058         }
36059         else if (this._gpano) {
36060             var x = bearing[0];
36061             var y = bearing[1];
36062             var z = bearing[2];
36063             var lon = Math.atan2(x, z);
36064             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
36065             var fullPanoPixel = [
36066                 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
36067                 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
36068             ];
36069             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
36070             return [
36071                 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
36072                 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
36073             ];
36074         }
36075         else {
36076             if (bearing[2] > 0) {
36077                 var _a = [bearing[0] / bearing[2], bearing[1] / bearing[2]], xn = _a[0], yn = _a[1];
36078                 var r2 = xn * xn + yn * yn;
36079                 var rp2 = Math.pow(this._radialPeak, 2);
36080                 if (r2 > rp2) {
36081                     r2 = rp2;
36082                 }
36083                 var d = 1 + this._ck1 * r2 + this._ck2 * Math.pow(r2, 2);
36084                 return [
36085                     this._focal * d * xn,
36086                     this._focal * d * yn,
36087                 ];
36088             }
36089             else {
36090                 return [
36091                     bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
36092                     bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
36093                 ];
36094             }
36095         }
36096     };
36097     /**
36098      * Convert basic coordinates to SfM coordinates.
36099      *
36100      * @param {Array<number>} basic - 2D basic coordinates.
36101      * @returns {Array<number>} 2D SfM coordinates.
36102      */
36103     Transform.prototype._basicToSfm = function (basic) {
36104         var rotatedX;
36105         var rotatedY;
36106         switch (this._orientation) {
36107             case 1:
36108                 rotatedX = basic[0];
36109                 rotatedY = basic[1];
36110                 break;
36111             case 3:
36112                 rotatedX = 1 - basic[0];
36113                 rotatedY = 1 - basic[1];
36114                 break;
36115             case 6:
36116                 rotatedX = basic[1];
36117                 rotatedY = 1 - basic[0];
36118                 break;
36119             case 8:
36120                 rotatedX = 1 - basic[1];
36121                 rotatedY = basic[0];
36122                 break;
36123             default:
36124                 rotatedX = basic[0];
36125                 rotatedY = basic[1];
36126                 break;
36127         }
36128         var w = this._width;
36129         var h = this._height;
36130         var s = Math.max(w, h);
36131         var sfmX = rotatedX * w / s - w / s / 2;
36132         var sfmY = rotatedY * h / s - h / s / 2;
36133         return [sfmX, sfmY];
36134     };
36135     /**
36136      * Convert SfM coordinates to basic coordinates.
36137      *
36138      * @param {Array<number>} sfm - 2D SfM coordinates.
36139      * @returns {Array<number>} 2D basic coordinates.
36140      */
36141     Transform.prototype._sfmToBasic = function (sfm) {
36142         var w = this._width;
36143         var h = this._height;
36144         var s = Math.max(w, h);
36145         var rotatedX = (sfm[0] + w / s / 2) / w * s;
36146         var rotatedY = (sfm[1] + h / s / 2) / h * s;
36147         var basicX;
36148         var basicY;
36149         switch (this._orientation) {
36150             case 1:
36151                 basicX = rotatedX;
36152                 basicY = rotatedY;
36153                 break;
36154             case 3:
36155                 basicX = 1 - rotatedX;
36156                 basicY = 1 - rotatedY;
36157                 break;
36158             case 6:
36159                 basicX = 1 - rotatedY;
36160                 basicY = rotatedX;
36161                 break;
36162             case 8:
36163                 basicX = rotatedY;
36164                 basicY = 1 - rotatedX;
36165                 break;
36166             default:
36167                 basicX = rotatedX;
36168                 basicY = rotatedY;
36169                 break;
36170         }
36171         return [basicX, basicY];
36172     };
36173     /**
36174      * Determines if the gpano information indicates a full panorama.
36175      *
36176      * @returns {boolean} Value determining if the gpano information indicates
36177      * a full panorama.
36178      */
36179     Transform.prototype._fullPano = function () {
36180         return this.gpano != null &&
36181             this.gpano.CroppedAreaLeftPixels === 0 &&
36182             this.gpano.CroppedAreaTopPixels === 0 &&
36183             this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
36184             this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
36185     };
36186     /**
36187      * Checks a value and returns it if it exists and is larger than 0.
36188      * Fallbacks if it is null.
36189      *
36190      * @param {number} value - Value to check.
36191      * @param {number} fallback - Value to fall back to.
36192      * @returns {number} The value or its fallback value if it is not defined or negative.
36193      */
36194     Transform.prototype._getValue = function (value, fallback) {
36195         return value != null && value > 0 ? value : fallback;
36196     };
36197     /**
36198      * Creates the extrinsic camera matrix [ R | t ].
36199      *
36200      * @param {Array<number>} rotation - Rotation vector in angle axis representation.
36201      * @param {Array<number>} translation - Translation vector.
36202      * @returns {THREE.Matrix4} Extrisic camera matrix.
36203      */
36204     Transform.prototype._getRt = function (rotation, translation) {
36205         var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
36206         var angle = axis.length();
36207         if (angle > 0) {
36208             axis.normalize();
36209         }
36210         var rt = new THREE.Matrix4();
36211         rt.makeRotationAxis(axis, angle);
36212         rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
36213         return rt;
36214     };
36215     /**
36216      * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
36217      *
36218      * @param {THREE.Matrix4} rt - Extrisic camera matrix.
36219      * @param {number} scale - Scale factor.
36220      * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
36221      */
36222     Transform.prototype._getSrt = function (rt, scale) {
36223         var srt = rt.clone();
36224         var elements = srt.elements;
36225         elements[12] = scale * elements[12];
36226         elements[13] = scale * elements[13];
36227         elements[14] = scale * elements[14];
36228         srt.scale(new THREE.Vector3(scale, scale, scale));
36229         return srt;
36230     };
36231     Transform.prototype._getBasicRt = function (rt, orientation) {
36232         var axis = new THREE.Vector3(0, 0, 1);
36233         var angle = 0;
36234         switch (orientation) {
36235             case 3:
36236                 angle = Math.PI;
36237                 break;
36238             case 6:
36239                 angle = Math.PI / 2;
36240                 break;
36241             case 8:
36242                 angle = 3 * Math.PI / 2;
36243                 break;
36244             default:
36245                 break;
36246         }
36247         return new THREE.Matrix4()
36248             .makeRotationAxis(axis, angle)
36249             .multiply(rt);
36250     };
36251     Transform.prototype._getRadialPeak = function (k1, k2) {
36252         var a = 5 * k2;
36253         var b = 3 * k1;
36254         var c = 1;
36255         var d = Math.pow(b, 2) - 4 * a * c;
36256         if (d < 0) {
36257             return undefined;
36258         }
36259         var root1 = (-b - Math.sqrt(d)) / 2 / a;
36260         var root2 = (-b + Math.sqrt(d)) / 2 / a;
36261         var minRoot = Math.min(root1, root2);
36262         var maxRoot = Math.max(root1, root2);
36263         return minRoot > 0 ?
36264             Math.sqrt(minRoot) :
36265             maxRoot > 0 ?
36266                 Math.sqrt(maxRoot) :
36267                 undefined;
36268     };
36269     /**
36270      * Calculate a transformation matrix from normalized coordinates for
36271      * texture map coordinates.
36272      *
36273      * @returns {THREE.Matrix4} Normalized coordinates to texture map
36274      * coordinates transformation matrix.
36275      */
36276     Transform.prototype._normalizedToTextureMatrix = function () {
36277         var size = Math.max(this._width, this._height);
36278         var scaleX = this._orientation < 5 ? this._textureScale[0] : this._textureScale[1];
36279         var scaleY = this._orientation < 5 ? this._textureScale[1] : this._textureScale[0];
36280         var w = size / this._width * scaleX;
36281         var h = size / this._height * scaleY;
36282         switch (this._orientation) {
36283             case 1:
36284                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
36285             case 3:
36286                 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
36287             case 6:
36288                 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
36289             case 8:
36290                 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
36291             default:
36292                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
36293         }
36294     };
36295     return Transform;
36296 }());
36297 exports.Transform = Transform;
36298
36299 },{"three":225}],387:[function(require,module,exports){
36300 "use strict";
36301 Object.defineProperty(exports, "__esModule", { value: true });
36302 var THREE = require("three");
36303 /**
36304  * @class ViewportCoords
36305  *
36306  * @classdesc Provides methods for calculating 2D coordinate conversions
36307  * as well as 3D projection and unprojection.
36308  *
36309  * Basic coordinates are 2D coordinates on the [0, 1] interval and
36310  * have the origin point, (0, 0), at the top left corner and the
36311  * maximum value, (1, 1), at the bottom right corner of the original
36312  * image.
36313  *
36314  * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
36315  * have the origin point in the center. The bottom left corner point is
36316  * (-1, -1) and the top right corner point is (1, 1).
36317  *
36318  * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
36319  * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
36320  * corner and the maximum value is (canvasWidth, canvasHeight) is in the
36321  * bottom right corner.
36322  *
36323  * 3D coordinates are in the topocentric world reference frame.
36324  */
36325 var ViewportCoords = /** @class */ (function () {
36326     function ViewportCoords() {
36327         this._unprojectDepth = 200;
36328     }
36329     /**
36330      * Convert basic coordinates to canvas coordinates.
36331      *
36332      * @description Transform origin and camera position needs to be the
36333      * equal for reliable return value.
36334      *
36335      * @param {number} basicX - Basic X coordinate.
36336      * @param {number} basicY - Basic Y coordinate.
36337      * @param {HTMLElement} container - The viewer container.
36338      * @param {Transform} transform - Transform of the node to unproject from.
36339      * @param {THREE.Camera} camera - Camera used in rendering.
36340      * @returns {Array<number>} 2D canvas coordinates.
36341      */
36342     ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) {
36343         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
36344         var canvas = this.projectToCanvas(point3d, container, camera);
36345         return canvas;
36346     };
36347     /**
36348      * Convert basic coordinates to canvas coordinates safely. If 3D point is
36349      * behind camera null will be returned.
36350      *
36351      * @description Transform origin and camera position needs to be the
36352      * equal for reliable return value.
36353      *
36354      * @param {number} basicX - Basic X coordinate.
36355      * @param {number} basicY - Basic Y coordinate.
36356      * @param {HTMLElement} container - The viewer container.
36357      * @param {Transform} transform - Transform of the node to unproject from.
36358      * @param {THREE.Camera} camera - Camera used in rendering.
36359      * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point
36360      * in front of the camera, otherwise null.
36361      */
36362     ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) {
36363         var viewport = this.basicToViewportSafe(basicX, basicY, transform, camera);
36364         if (viewport === null) {
36365             return null;
36366         }
36367         var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
36368         return canvas;
36369     };
36370     /**
36371      * Convert basic coordinates to viewport coordinates.
36372      *
36373      * @description Transform origin and camera position needs to be the
36374      * equal for reliable return value.
36375      *
36376      * @param {number} basicX - Basic X coordinate.
36377      * @param {number} basicY - Basic Y coordinate.
36378      * @param {Transform} transform - Transform of the node to unproject from.
36379      * @param {THREE.Camera} camera - Camera used in rendering.
36380      * @returns {Array<number>} 2D viewport coordinates.
36381      */
36382     ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) {
36383         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
36384         var viewport = this.projectToViewport(point3d, camera);
36385         return viewport;
36386     };
36387     /**
36388      * Convert basic coordinates to viewport coordinates safely. If 3D point is
36389      * behind camera null will be returned.
36390      *
36391      * @description Transform origin and camera position needs to be the
36392      * equal for reliable return value.
36393      *
36394      * @param {number} basicX - Basic X coordinate.
36395      * @param {number} basicY - Basic Y coordinate.
36396      * @param {Transform} transform - Transform of the node to unproject from.
36397      * @param {THREE.Camera} camera - Camera used in rendering.
36398      * @returns {Array<number>} 2D viewport coordinates.
36399      */
36400     ViewportCoords.prototype.basicToViewportSafe = function (basicX, basicY, transform, camera) {
36401         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
36402         var pointCamera = this.worldToCamera(point3d, camera);
36403         if (pointCamera[2] > 0) {
36404             return null;
36405         }
36406         var viewport = this.projectToViewport(point3d, camera);
36407         return viewport;
36408     };
36409     /**
36410      * Convert camera 3D coordinates to viewport coordinates.
36411      *
36412      * @param {number} pointCamera - 3D point in camera coordinate system.
36413      * @param {THREE.Camera} camera - Camera used in rendering.
36414      * @returns {Array<number>} 2D viewport coordinates.
36415      */
36416     ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) {
36417         var viewport = new THREE.Vector3().fromArray(pointCamera)
36418             .applyMatrix4(camera.projectionMatrix);
36419         return [viewport.x, viewport.y];
36420     };
36421     /**
36422      * Get canvas pixel position from event.
36423      *
36424      * @param {Event} event - Event containing clientX and clientY properties.
36425      * @param {HTMLElement} element - HTML element.
36426      * @returns {Array<number>} 2D canvas coordinates.
36427      */
36428     ViewportCoords.prototype.canvasPosition = function (event, element) {
36429         var clientRect = element.getBoundingClientRect();
36430         var canvasX = event.clientX - clientRect.left - element.clientLeft;
36431         var canvasY = event.clientY - clientRect.top - element.clientTop;
36432         return [canvasX, canvasY];
36433     };
36434     /**
36435      * Convert canvas coordinates to basic coordinates.
36436      *
36437      * @description Transform origin and camera position needs to be the
36438      * equal for reliable return value.
36439      *
36440      * @param {number} canvasX - Canvas X coordinate.
36441      * @param {number} canvasY - Canvas Y coordinate.
36442      * @param {HTMLElement} container - The viewer container.
36443      * @param {Transform} transform - Transform of the node to unproject from.
36444      * @param {THREE.Camera} camera - Camera used in rendering.
36445      * @returns {Array<number>} 2D basic coordinates.
36446      */
36447     ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) {
36448         var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera)
36449             .toArray();
36450         var basic = transform.projectBasic(point3d);
36451         return basic;
36452     };
36453     /**
36454      * Convert canvas coordinates to viewport coordinates.
36455      *
36456      * @param {number} canvasX - Canvas X coordinate.
36457      * @param {number} canvasY - Canvas Y coordinate.
36458      * @param {HTMLElement} container - The viewer container.
36459      * @returns {Array<number>} 2D viewport coordinates.
36460      */
36461     ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
36462         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
36463         var viewportX = 2 * canvasX / canvasWidth - 1;
36464         var viewportY = 1 - 2 * canvasY / canvasHeight;
36465         return [viewportX, viewportY];
36466     };
36467     /**
36468      * Determines the width and height of the container in canvas coordinates.
36469      *
36470      * @param {HTMLElement} container - The viewer container.
36471      * @returns {Array<number>} 2D canvas coordinates.
36472      */
36473     ViewportCoords.prototype.containerToCanvas = function (container) {
36474         return [container.offsetWidth, container.offsetHeight];
36475     };
36476     /**
36477      * Determine basic distances from image to canvas corners.
36478      *
36479      * @description Transform origin and camera position needs to be the
36480      * equal for reliable return value.
36481      *
36482      * Determines the smallest basic distance for every side of the canvas.
36483      *
36484      * @param {Transform} transform - Transform of the node to unproject from.
36485      * @param {THREE.Camera} camera - Camera used in rendering.
36486      * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
36487      */
36488     ViewportCoords.prototype.getBasicDistances = function (transform, camera) {
36489         var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
36490         var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
36491         var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
36492         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
36493         var topBasicDistance = 0;
36494         var rightBasicDistance = 0;
36495         var bottomBasicDistance = 0;
36496         var leftBasicDistance = 0;
36497         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
36498             topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
36499                 -topLeftBasic[1] :
36500                 -topRightBasic[1];
36501         }
36502         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
36503             rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
36504                 topRightBasic[0] - 1 :
36505                 bottomRightBasic[0] - 1;
36506         }
36507         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
36508             bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
36509                 bottomRightBasic[1] - 1 :
36510                 bottomLeftBasic[1] - 1;
36511         }
36512         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
36513             leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
36514                 -bottomLeftBasic[0] :
36515                 -topLeftBasic[0];
36516         }
36517         return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
36518     };
36519     /**
36520      * Determine pixel distances from image to canvas corners.
36521      *
36522      * @description Transform origin and camera position needs to be the
36523      * equal for reliable return value.
36524      *
36525      * Determines the smallest pixel distance for every side of the canvas.
36526      *
36527      * @param {HTMLElement} container - The viewer container.
36528      * @param {Transform} transform - Transform of the node to unproject from.
36529      * @param {THREE.Camera} camera - Camera used in rendering.
36530      * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
36531      */
36532     ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) {
36533         var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
36534         var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
36535         var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
36536         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
36537         var topPixelDistance = 0;
36538         var rightPixelDistance = 0;
36539         var bottomPixelDistance = 0;
36540         var leftPixelDistance = 0;
36541         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
36542         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
36543             var basicX = topLeftBasic[1] > topRightBasic[1] ?
36544                 topLeftBasic[0] :
36545                 topRightBasic[0];
36546             var canvas = this.basicToCanvas(basicX, 0, container, transform, camera);
36547             topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
36548         }
36549         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
36550             var basicY = topRightBasic[0] < bottomRightBasic[0] ?
36551                 topRightBasic[1] :
36552                 bottomRightBasic[1];
36553             var canvas = this.basicToCanvas(1, basicY, container, transform, camera);
36554             rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
36555         }
36556         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
36557             var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
36558                 bottomRightBasic[0] :
36559                 bottomLeftBasic[0];
36560             var canvas = this.basicToCanvas(basicX, 1, container, transform, camera);
36561             bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
36562         }
36563         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
36564             var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
36565                 bottomLeftBasic[1] :
36566                 topLeftBasic[1];
36567             var canvas = this.basicToCanvas(0, basicY, container, transform, camera);
36568             leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
36569         }
36570         return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
36571     };
36572     /**
36573      * Determine if an event occured inside an element.
36574      *
36575      * @param {Event} event - Event containing clientX and clientY properties.
36576      * @param {HTMLElement} element - HTML element.
36577      * @returns {boolean} Value indicating if the event occured inside the element or not.
36578      */
36579     ViewportCoords.prototype.insideElement = function (event, element) {
36580         var clientRect = element.getBoundingClientRect();
36581         var minX = clientRect.left + element.clientLeft;
36582         var maxX = minX + element.clientWidth;
36583         var minY = clientRect.top + element.clientTop;
36584         var maxY = minY + element.clientHeight;
36585         return event.clientX > minX &&
36586             event.clientX < maxX &&
36587             event.clientY > minY &&
36588             event.clientY < maxY;
36589     };
36590     /**
36591      * Project 3D world coordinates to canvas coordinates.
36592      *
36593      * @param {Array<number>} point3D - 3D world coordinates.
36594      * @param {HTMLElement} container - The viewer container.
36595      * @param {THREE.Camera} camera - Camera used in rendering.
36596      * @returns {Array<number>} 2D canvas coordinates.
36597      */
36598     ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) {
36599         var viewport = this.projectToViewport(point3d, camera);
36600         var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
36601         return canvas;
36602     };
36603     /**
36604      * Project 3D world coordinates to viewport coordinates.
36605      *
36606      * @param {Array<number>} point3D - 3D world coordinates.
36607      * @param {THREE.Camera} camera - Camera used in rendering.
36608      * @returns {Array<number>} 2D viewport coordinates.
36609      */
36610     ViewportCoords.prototype.projectToViewport = function (point3d, camera) {
36611         var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
36612             .project(camera);
36613         return [viewport.x, viewport.y];
36614     };
36615     /**
36616      * Uproject canvas coordinates to 3D world coordinates.
36617      *
36618      * @param {number} canvasX - Canvas X coordinate.
36619      * @param {number} canvasY - Canvas Y coordinate.
36620      * @param {HTMLElement} container - The viewer container.
36621      * @param {THREE.Camera} camera - Camera used in rendering.
36622      * @returns {Array<number>} 3D world coordinates.
36623      */
36624     ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) {
36625         var viewport = this.canvasToViewport(canvasX, canvasY, container);
36626         var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera);
36627         return point3d;
36628     };
36629     /**
36630      * Unproject viewport coordinates to 3D world coordinates.
36631      *
36632      * @param {number} viewportX - Viewport X coordinate.
36633      * @param {number} viewportY - Viewport Y coordinate.
36634      * @param {THREE.Camera} camera - Camera used in rendering.
36635      * @returns {Array<number>} 3D world coordinates.
36636      */
36637     ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) {
36638         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
36639             .unproject(camera);
36640         return point3d;
36641     };
36642     /**
36643      * Convert viewport coordinates to basic coordinates.
36644      *
36645      * @description Transform origin and camera position needs to be the
36646      * equal for reliable return value.
36647      *
36648      * @param {number} viewportX - Viewport X coordinate.
36649      * @param {number} viewportY - Viewport Y coordinate.
36650      * @param {Transform} transform - Transform of the node to unproject from.
36651      * @param {THREE.Camera} camera - Camera used in rendering.
36652      * @returns {Array<number>} 2D basic coordinates.
36653      */
36654     ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) {
36655         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
36656             .unproject(camera)
36657             .toArray();
36658         var basic = transform.projectBasic(point3d);
36659         return basic;
36660     };
36661     /**
36662      * Convert viewport coordinates to canvas coordinates.
36663      *
36664      * @param {number} viewportX - Viewport X coordinate.
36665      * @param {number} viewportY - Viewport Y coordinate.
36666      * @param {HTMLElement} container - The viewer container.
36667      * @returns {Array<number>} 2D canvas coordinates.
36668      */
36669     ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
36670         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
36671         var canvasX = canvasWidth * (viewportX + 1) / 2;
36672         var canvasY = -canvasHeight * (viewportY - 1) / 2;
36673         return [canvasX, canvasY];
36674     };
36675     /**
36676      * Convert 3D world coordinates to 3D camera coordinates.
36677      *
36678      * @param {number} point3D - 3D point in world coordinate system.
36679      * @param {THREE.Camera} camera - Camera used in rendering.
36680      * @returns {Array<number>} 3D camera coordinates.
36681      */
36682     ViewportCoords.prototype.worldToCamera = function (point3d, camera) {
36683         var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
36684             .applyMatrix4(camera.matrixWorldInverse);
36685         return pointCamera.toArray();
36686     };
36687     return ViewportCoords;
36688 }());
36689 exports.ViewportCoords = ViewportCoords;
36690 exports.default = ViewportCoords;
36691
36692
36693 },{"three":225}],388:[function(require,module,exports){
36694 "use strict";
36695 Object.defineProperty(exports, "__esModule", { value: true });
36696 /**
36697  * @class Filter
36698  *
36699  * @classdesc Represents a class for creating node filters. Implementation and
36700  * definitions based on https://github.com/mapbox/feature-filter.
36701  */
36702 var FilterCreator = /** @class */ (function () {
36703     function FilterCreator() {
36704     }
36705     /**
36706      * Create a filter from a filter expression.
36707      *
36708      * @description The following filters are supported:
36709      *
36710      * Comparison
36711      * `==`
36712      * `!=`
36713      * `<`
36714      * `<=`
36715      * `>`
36716      * `>=`
36717      *
36718      * Set membership
36719      * `in`
36720      * `!in`
36721      *
36722      * Combining
36723      * `all`
36724      *
36725      * @param {FilterExpression} filter - Comparison, set membership or combinding filter
36726      * expression.
36727      * @returns {FilterFunction} Function taking a node and returning a boolean that
36728      * indicates whether the node passed the test or not.
36729      */
36730     FilterCreator.prototype.createFilter = function (filter) {
36731         return new Function("node", "return " + this._compile(filter) + ";");
36732     };
36733     FilterCreator.prototype._compile = function (filter) {
36734         if (filter == null || filter.length <= 1) {
36735             return "true";
36736         }
36737         var operator = filter[0];
36738         var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
36739             operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
36740                 operator === ">" ||
36741                     operator === ">=" ||
36742                     operator === "<" ||
36743                     operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
36744                     operator === "in" ?
36745                         this._compileInOp(filter[1], filter.slice(2)) :
36746                         operator === "!in" ?
36747                             this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
36748                             operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
36749                                 "true";
36750         return "(" + operation + ")";
36751     };
36752     FilterCreator.prototype._compare = function (a, b) {
36753         return a < b ? -1 : a > b ? 1 : 0;
36754     };
36755     FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
36756         var left = this._compilePropertyReference(property);
36757         var right = JSON.stringify(value);
36758         return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
36759     };
36760     FilterCreator.prototype._compileInOp = function (property, values) {
36761         var compare = this._compare;
36762         var left = JSON.stringify(values.sort(compare));
36763         var right = this._compilePropertyReference(property);
36764         return left + ".indexOf(" + right + ")!==-1";
36765     };
36766     FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
36767         var compile = this._compile.bind(this);
36768         return filters.map(compile).join(operator);
36769     };
36770     FilterCreator.prototype._compileNegation = function (expression) {
36771         return "!(" + expression + ")";
36772     };
36773     FilterCreator.prototype._compilePropertyReference = function (property) {
36774         return "node[" + JSON.stringify(property) + "]";
36775     };
36776     return FilterCreator;
36777 }());
36778 exports.FilterCreator = FilterCreator;
36779 exports.default = FilterCreator;
36780
36781 },{}],389:[function(require,module,exports){
36782 "use strict";
36783 Object.defineProperty(exports, "__esModule", { value: true });
36784 var rxjs_1 = require("rxjs");
36785 var operators_1 = require("rxjs/operators");
36786 var rbush = require("rbush");
36787 var Edge_1 = require("../Edge");
36788 var Error_1 = require("../Error");
36789 var Graph_1 = require("../Graph");
36790 /**
36791  * @class Graph
36792  *
36793  * @classdesc Represents a graph of nodes with edges.
36794  */
36795 var Graph = /** @class */ (function () {
36796     /**
36797      * Create a new graph instance.
36798      *
36799      * @param {APIv3} [apiV3] - API instance for retrieving data.
36800      * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
36801      * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
36802      * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
36803      * @param {FilterCreator} [filterCreator] - Instance for  filter creation.
36804      * @param {IGraphConfiguration} [configuration] - Configuration struct.
36805      */
36806     function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
36807         this._apiV3 = apiV3;
36808         this._cachedNodes = {};
36809         this._cachedNodeTiles = {};
36810         this._cachedSequenceNodes = {};
36811         this._cachedSpatialEdges = {};
36812         this._cachedTiles = {};
36813         this._cachingFill$ = {};
36814         this._cachingFull$ = {};
36815         this._cachingSequenceNodes$ = {};
36816         this._cachingSequences$ = {};
36817         this._cachingSpatialArea$ = {};
36818         this._cachingTiles$ = {};
36819         this._changed$ = new rxjs_1.Subject();
36820         this._defaultAlt = 2;
36821         this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
36822         this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
36823         this._filter = this._filterCreator.createFilter(undefined);
36824         this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
36825         this._configuration = configuration != null ?
36826             configuration :
36827             {
36828                 maxSequences: 50,
36829                 maxUnusedNodes: 100,
36830                 maxUnusedPreStoredNodes: 30,
36831                 maxUnusedTiles: 20,
36832             };
36833         this._nodes = {};
36834         this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
36835         this._nodeIndexTiles = {};
36836         this._nodeToTile = {};
36837         this._preStored = {};
36838         this._requiredNodeTiles = {};
36839         this._requiredSpatialArea = {};
36840         this._sequences = {};
36841         this._tilePrecision = 7;
36842         this._tileThreshold = 20;
36843     }
36844     Object.defineProperty(Graph.prototype, "changed$", {
36845         /**
36846          * Get changed$.
36847          *
36848          * @returns {Observable<Graph>} Observable emitting
36849          * the graph every time it has changed.
36850          */
36851         get: function () {
36852             return this._changed$;
36853         },
36854         enumerable: true,
36855         configurable: true
36856     });
36857     /**
36858      * Caches the full node data for all images within a bounding
36859      * box.
36860      *
36861      * @description The node assets are not cached.
36862      *
36863      * @param {ILatLon} sw - South west corner of bounding box.
36864      * @param {ILatLon} ne - North east corner of bounding box.
36865      * @returns {Observable<Graph>} Observable emitting the full
36866      * nodes in the bounding box.
36867      */
36868     Graph.prototype.cacheBoundingBox$ = function (sw, ne) {
36869         var _this = this;
36870         var cacheTiles$ = this._graphCalculator.encodeHsFromBoundingBox(sw, ne)
36871             .filter(function (h) {
36872             return !(h in _this._cachedTiles);
36873         })
36874             .map(function (h) {
36875             return h in _this._cachingTiles$ ?
36876                 _this._cachingTiles$[h] :
36877                 _this._cacheTile$(h);
36878         });
36879         if (cacheTiles$.length === 0) {
36880             cacheTiles$.push(rxjs_1.of(this));
36881         }
36882         return rxjs_1.from(cacheTiles$).pipe(operators_1.mergeAll(), operators_1.last(), operators_1.mergeMap(function (graph) {
36883             var nodes = _this._nodeIndex
36884                 .search({
36885                 maxX: ne.lat,
36886                 maxY: ne.lon,
36887                 minX: sw.lat,
36888                 minY: sw.lon,
36889             })
36890                 .map(function (item) {
36891                 return item.node;
36892             });
36893             var fullNodes = [];
36894             var coreNodes = [];
36895             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
36896                 var node = nodes_1[_i];
36897                 if (node.full) {
36898                     fullNodes.push(node);
36899                 }
36900                 else {
36901                     coreNodes.push(node.key);
36902                 }
36903             }
36904             var coreNodeBatches = [];
36905             var batchSize = 200;
36906             while (coreNodes.length > 0) {
36907                 coreNodeBatches.push(coreNodes.splice(0, batchSize));
36908             }
36909             var fullNodes$ = rxjs_1.of(fullNodes);
36910             var fillNodes$ = coreNodeBatches
36911                 .map(function (batch) {
36912                 return _this._apiV3.imageByKeyFill$(batch).pipe(operators_1.map(function (imageByKeyFill) {
36913                     var filledNodes = [];
36914                     for (var fillKey in imageByKeyFill) {
36915                         if (!imageByKeyFill.hasOwnProperty(fillKey)) {
36916                             continue;
36917                         }
36918                         if (_this.hasNode(fillKey)) {
36919                             var node = _this.getNode(fillKey);
36920                             if (!node.full) {
36921                                 _this._makeFull(node, imageByKeyFill[fillKey]);
36922                             }
36923                             filledNodes.push(node);
36924                         }
36925                     }
36926                     return filledNodes;
36927                 }));
36928             });
36929             return rxjs_1.merge(fullNodes$, rxjs_1.from(fillNodes$).pipe(operators_1.mergeAll()));
36930         }), operators_1.reduce(function (acc, value) {
36931             return acc.concat(value);
36932         }));
36933     };
36934     /**
36935      * Retrieve and cache node fill properties.
36936      *
36937      * @param {string} key - Key of node to fill.
36938      * @returns {Observable<Graph>} Observable emitting the graph
36939      * when the node has been updated.
36940      * @throws {GraphMapillaryError} When the operation is not valid on the
36941      * current graph.
36942      */
36943     Graph.prototype.cacheFill$ = function (key) {
36944         var _this = this;
36945         if (key in this._cachingFull$) {
36946             throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
36947         }
36948         if (!this.hasNode(key)) {
36949             throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
36950         }
36951         if (key in this._cachingFill$) {
36952             return this._cachingFill$[key];
36953         }
36954         var node = this.getNode(key);
36955         if (node.full) {
36956             throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
36957         }
36958         this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key]).pipe(operators_1.tap(function (imageByKeyFill) {
36959             if (!node.full) {
36960                 _this._makeFull(node, imageByKeyFill[key]);
36961             }
36962             delete _this._cachingFill$[key];
36963         }), operators_1.map(function (imageByKeyFill) {
36964             return _this;
36965         }), operators_1.finalize(function () {
36966             if (key in _this._cachingFill$) {
36967                 delete _this._cachingFill$[key];
36968             }
36969             _this._changed$.next(_this);
36970         }), operators_1.publish(), operators_1.refCount());
36971         return this._cachingFill$[key];
36972     };
36973     /**
36974      * Retrieve and cache full node properties.
36975      *
36976      * @param {string} key - Key of node to fill.
36977      * @returns {Observable<Graph>} Observable emitting the graph
36978      * when the node has been updated.
36979      * @throws {GraphMapillaryError} When the operation is not valid on the
36980      * current graph.
36981      */
36982     Graph.prototype.cacheFull$ = function (key) {
36983         var _this = this;
36984         if (key in this._cachingFull$) {
36985             return this._cachingFull$[key];
36986         }
36987         if (this.hasNode(key)) {
36988             throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
36989         }
36990         this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key]).pipe(operators_1.tap(function (imageByKeyFull) {
36991             var fn = imageByKeyFull[key];
36992             if (_this.hasNode(key)) {
36993                 var node = _this.getNode(key);
36994                 if (!node.full) {
36995                     _this._makeFull(node, fn);
36996                 }
36997             }
36998             else {
36999                 if (fn.sequence_key == null) {
37000                     throw new Error_1.GraphMapillaryError("Node has no sequence key (" + key + ").");
37001                 }
37002                 var node = new Graph_1.Node(fn);
37003                 _this._makeFull(node, fn);
37004                 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
37005                 _this._preStore(h, node);
37006                 _this._setNode(node);
37007                 delete _this._cachingFull$[key];
37008             }
37009         }), operators_1.map(function (imageByKeyFull) {
37010             return _this;
37011         }), operators_1.finalize(function () {
37012             if (key in _this._cachingFull$) {
37013                 delete _this._cachingFull$[key];
37014             }
37015             _this._changed$.next(_this);
37016         }), operators_1.publish(), operators_1.refCount());
37017         return this._cachingFull$[key];
37018     };
37019     /**
37020      * Retrieve and cache a node sequence.
37021      *
37022      * @param {string} key - Key of node for which to retrieve sequence.
37023      * @returns {Observable<Graph>} Observable emitting the graph
37024      * when the sequence has been retrieved.
37025      * @throws {GraphMapillaryError} When the operation is not valid on the
37026      * current graph.
37027      */
37028     Graph.prototype.cacheNodeSequence$ = function (key) {
37029         if (!this.hasNode(key)) {
37030             throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
37031         }
37032         var node = this.getNode(key);
37033         if (node.sequenceKey in this._sequences) {
37034             throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
37035         }
37036         return this._cacheSequence$(node.sequenceKey);
37037     };
37038     /**
37039      * Retrieve and cache a sequence.
37040      *
37041      * @param {string} sequenceKey - Key of sequence to cache.
37042      * @returns {Observable<Graph>} Observable emitting the graph
37043      * when the sequence has been retrieved.
37044      * @throws {GraphMapillaryError} When the operation is not valid on the
37045      * current graph.
37046      */
37047     Graph.prototype.cacheSequence$ = function (sequenceKey) {
37048         if (sequenceKey in this._sequences) {
37049             throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
37050         }
37051         return this._cacheSequence$(sequenceKey);
37052     };
37053     /**
37054      * Cache sequence edges for a node.
37055      *
37056      * @param {string} key - Key of node.
37057      * @throws {GraphMapillaryError} When the operation is not valid on the
37058      * current graph.
37059      */
37060     Graph.prototype.cacheSequenceEdges = function (key) {
37061         var node = this.getNode(key);
37062         if (!(node.sequenceKey in this._sequences)) {
37063             throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
37064         }
37065         var sequence = this._sequences[node.sequenceKey].sequence;
37066         var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
37067         node.cacheSequenceEdges(edges);
37068     };
37069     /**
37070      * Retrieve and cache full nodes for all keys in a sequence.
37071      *
37072      * @param {string} sequenceKey - Key of sequence.
37073      * @param {string} referenceNodeKey - Key of node to use as reference
37074      * for optimized caching.
37075      * @returns {Observable<Graph>} Observable emitting the graph
37076      * when the nodes of the sequence has been cached.
37077      */
37078     Graph.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
37079         var _this = this;
37080         if (!this.hasSequence(sequenceKey)) {
37081             throw new Error_1.GraphMapillaryError("Cannot cache sequence nodes of sequence that does not exist in graph (" + sequenceKey + ").");
37082         }
37083         if (this.hasSequenceNodes(sequenceKey)) {
37084             throw new Error_1.GraphMapillaryError("Sequence nodes already cached (" + sequenceKey + ").");
37085         }
37086         var sequence = this.getSequence(sequenceKey);
37087         if (sequence.key in this._cachingSequenceNodes$) {
37088             return this._cachingSequenceNodes$[sequence.key];
37089         }
37090         var batches = [];
37091         var keys = sequence.keys.slice();
37092         var referenceBatchSize = 50;
37093         if (!!referenceNodeKey && keys.length > referenceBatchSize) {
37094             var referenceIndex = keys.indexOf(referenceNodeKey);
37095             var startIndex = Math.max(0, Math.min(referenceIndex - referenceBatchSize / 2, keys.length - referenceBatchSize));
37096             batches.push(keys.splice(startIndex, referenceBatchSize));
37097         }
37098         var batchSize = 200;
37099         while (keys.length > 0) {
37100             batches.push(keys.splice(0, batchSize));
37101         }
37102         var batchesToCache = batches.length;
37103         var sequenceNodes$ = rxjs_1.from(batches).pipe(operators_1.mergeMap(function (batch) {
37104             return _this._apiV3.imageByKeyFull$(batch).pipe(operators_1.tap(function (imageByKeyFull) {
37105                 for (var fullKey in imageByKeyFull) {
37106                     if (!imageByKeyFull.hasOwnProperty(fullKey)) {
37107                         continue;
37108                     }
37109                     var fn = imageByKeyFull[fullKey];
37110                     if (_this.hasNode(fullKey)) {
37111                         var node = _this.getNode(fn.key);
37112                         if (!node.full) {
37113                             _this._makeFull(node, fn);
37114                         }
37115                     }
37116                     else {
37117                         if (fn.sequence_key == null) {
37118                             console.warn("Sequence missing, discarding node (" + fn.key + ")");
37119                         }
37120                         var node = new Graph_1.Node(fn);
37121                         _this._makeFull(node, fn);
37122                         var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
37123                         _this._preStore(h, node);
37124                         _this._setNode(node);
37125                     }
37126                 }
37127                 batchesToCache--;
37128             }), operators_1.map(function (imageByKeyFull) {
37129                 return _this;
37130             }));
37131         }, 6), operators_1.last(), operators_1.finalize(function () {
37132             delete _this._cachingSequenceNodes$[sequence.key];
37133             if (batchesToCache === 0) {
37134                 _this._cachedSequenceNodes[sequence.key] = true;
37135             }
37136         }), operators_1.publish(), operators_1.refCount());
37137         this._cachingSequenceNodes$[sequence.key] = sequenceNodes$;
37138         return sequenceNodes$;
37139     };
37140     /**
37141      * Retrieve and cache full nodes for a node spatial area.
37142      *
37143      * @param {string} key - Key of node for which to retrieve sequence.
37144      * @returns {Observable<Graph>} Observable emitting the graph
37145      * when the nodes in the spatial area has been made full.
37146      * @throws {GraphMapillaryError} When the operation is not valid on the
37147      * current graph.
37148      */
37149     Graph.prototype.cacheSpatialArea$ = function (key) {
37150         var _this = this;
37151         if (!this.hasNode(key)) {
37152             throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
37153         }
37154         if (key in this._cachedSpatialEdges) {
37155             throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
37156         }
37157         if (!(key in this._requiredSpatialArea)) {
37158             throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
37159         }
37160         var spatialArea = this._requiredSpatialArea[key];
37161         if (Object.keys(spatialArea.cacheNodes).length === 0) {
37162             throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
37163         }
37164         if (key in this._cachingSpatialArea$) {
37165             return this._cachingSpatialArea$[key];
37166         }
37167         var batches = [];
37168         while (spatialArea.cacheKeys.length > 0) {
37169             batches.push(spatialArea.cacheKeys.splice(0, 200));
37170         }
37171         var batchesToCache = batches.length;
37172         var spatialNodes$ = [];
37173         var _loop_1 = function (batch) {
37174             var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch).pipe(operators_1.tap(function (imageByKeyFill) {
37175                 for (var fillKey in imageByKeyFill) {
37176                     if (!imageByKeyFill.hasOwnProperty(fillKey)) {
37177                         continue;
37178                     }
37179                     var spatialNode = spatialArea.cacheNodes[fillKey];
37180                     if (spatialNode.full) {
37181                         delete spatialArea.cacheNodes[fillKey];
37182                         continue;
37183                     }
37184                     var fillNode = imageByKeyFill[fillKey];
37185                     _this._makeFull(spatialNode, fillNode);
37186                     delete spatialArea.cacheNodes[fillKey];
37187                 }
37188                 if (--batchesToCache === 0) {
37189                     delete _this._cachingSpatialArea$[key];
37190                 }
37191             }), operators_1.map(function (imageByKeyFill) {
37192                 return _this;
37193             }), operators_1.catchError(function (error) {
37194                 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
37195                     var batchKey = batch_1[_i];
37196                     if (batchKey in spatialArea.all) {
37197                         delete spatialArea.all[batchKey];
37198                     }
37199                     if (batchKey in spatialArea.cacheNodes) {
37200                         delete spatialArea.cacheNodes[batchKey];
37201                     }
37202                 }
37203                 if (--batchesToCache === 0) {
37204                     delete _this._cachingSpatialArea$[key];
37205                 }
37206                 throw error;
37207             }), operators_1.finalize(function () {
37208                 if (Object.keys(spatialArea.cacheNodes).length === 0) {
37209                     _this._changed$.next(_this);
37210                 }
37211             }), operators_1.publish(), operators_1.refCount());
37212             spatialNodes$.push(spatialNodeBatch$);
37213         };
37214         var this_1 = this;
37215         for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
37216             var batch = batches_1[_i];
37217             _loop_1(batch);
37218         }
37219         this._cachingSpatialArea$[key] = spatialNodes$;
37220         return spatialNodes$;
37221     };
37222     /**
37223      * Cache spatial edges for a node.
37224      *
37225      * @param {string} key - Key of node.
37226      * @throws {GraphMapillaryError} When the operation is not valid on the
37227      * current graph.
37228      */
37229     Graph.prototype.cacheSpatialEdges = function (key) {
37230         if (key in this._cachedSpatialEdges) {
37231             throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
37232         }
37233         var node = this.getNode(key);
37234         var sequence = this._sequences[node.sequenceKey].sequence;
37235         var fallbackKeys = [];
37236         var prevKey = sequence.findPrevKey(node.key);
37237         if (prevKey != null) {
37238             fallbackKeys.push(prevKey);
37239         }
37240         var nextKey = sequence.findNextKey(node.key);
37241         if (nextKey != null) {
37242             fallbackKeys.push(nextKey);
37243         }
37244         var allSpatialNodes = this._requiredSpatialArea[key].all;
37245         var potentialNodes = [];
37246         var filter = this._filter;
37247         for (var spatialNodeKey in allSpatialNodes) {
37248             if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
37249                 continue;
37250             }
37251             var spatialNode = allSpatialNodes[spatialNodeKey];
37252             if (filter(spatialNode)) {
37253                 potentialNodes.push(spatialNode);
37254             }
37255         }
37256         var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
37257         var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
37258         edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
37259         edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
37260         edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
37261         edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
37262         node.cacheSpatialEdges(edges);
37263         this._cachedSpatialEdges[key] = node;
37264         delete this._requiredSpatialArea[key];
37265         delete this._cachedNodeTiles[key];
37266     };
37267     /**
37268      * Retrieve and cache geohash tiles for a node.
37269      *
37270      * @param {string} key - Key of node for which to retrieve tiles.
37271      * @returns {Array<Observable<Graph>>} Array of observables emitting
37272      * the graph for each tile required for the node has been cached.
37273      * @throws {GraphMapillaryError} When the operation is not valid on the
37274      * current graph.
37275      */
37276     Graph.prototype.cacheTiles$ = function (key) {
37277         var _this = this;
37278         if (key in this._cachedNodeTiles) {
37279             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
37280         }
37281         if (key in this._cachedSpatialEdges) {
37282             throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
37283         }
37284         if (!(key in this._requiredNodeTiles)) {
37285             throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
37286         }
37287         var nodeTiles = this._requiredNodeTiles[key];
37288         if (nodeTiles.cache.length === 0 &&
37289             nodeTiles.caching.length === 0) {
37290             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
37291         }
37292         if (!this.hasNode(key)) {
37293             throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
37294         }
37295         var hs = nodeTiles.cache.slice();
37296         nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
37297         nodeTiles.cache = [];
37298         var cacheTiles$ = [];
37299         var _loop_2 = function (h) {
37300             var cacheTile$ = h in this_2._cachingTiles$ ?
37301                 this_2._cachingTiles$[h] :
37302                 this_2._cacheTile$(h);
37303             cacheTiles$.push(cacheTile$.pipe(operators_1.tap(function (graph) {
37304                 var index = nodeTiles.caching.indexOf(h);
37305                 if (index > -1) {
37306                     nodeTiles.caching.splice(index, 1);
37307                 }
37308                 if (nodeTiles.caching.length === 0 &&
37309                     nodeTiles.cache.length === 0) {
37310                     delete _this._requiredNodeTiles[key];
37311                     _this._cachedNodeTiles[key] = true;
37312                 }
37313             }), operators_1.catchError(function (error) {
37314                 var index = nodeTiles.caching.indexOf(h);
37315                 if (index > -1) {
37316                     nodeTiles.caching.splice(index, 1);
37317                 }
37318                 if (nodeTiles.caching.length === 0 &&
37319                     nodeTiles.cache.length === 0) {
37320                     delete _this._requiredNodeTiles[key];
37321                     _this._cachedNodeTiles[key] = true;
37322                 }
37323                 throw error;
37324             }), operators_1.finalize(function () {
37325                 _this._changed$.next(_this);
37326             }), operators_1.publish(), operators_1.refCount()));
37327         };
37328         var this_2 = this;
37329         for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
37330             var h = _a[_i];
37331             _loop_2(h);
37332         }
37333         return cacheTiles$;
37334     };
37335     /**
37336      * Initialize the cache for a node.
37337      *
37338      * @param {string} key - Key of node.
37339      * @throws {GraphMapillaryError} When the operation is not valid on the
37340      * current graph.
37341      */
37342     Graph.prototype.initializeCache = function (key) {
37343         if (key in this._cachedNodes) {
37344             throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
37345         }
37346         var node = this.getNode(key);
37347         node.initializeCache(new Graph_1.NodeCache());
37348         var accessed = new Date().getTime();
37349         this._cachedNodes[key] = { accessed: accessed, node: node };
37350         this._updateCachedTileAccess(key, accessed);
37351     };
37352     /**
37353      * Get a value indicating if the graph is fill caching a node.
37354      *
37355      * @param {string} key - Key of node.
37356      * @returns {boolean} Value indicating if the node is being fill cached.
37357      */
37358     Graph.prototype.isCachingFill = function (key) {
37359         return key in this._cachingFill$;
37360     };
37361     /**
37362      * Get a value indicating if the graph is fully caching a node.
37363      *
37364      * @param {string} key - Key of node.
37365      * @returns {boolean} Value indicating if the node is being fully cached.
37366      */
37367     Graph.prototype.isCachingFull = function (key) {
37368         return key in this._cachingFull$;
37369     };
37370     /**
37371      * Get a value indicating if the graph is caching a sequence of a node.
37372      *
37373      * @param {string} key - Key of node.
37374      * @returns {boolean} Value indicating if the sequence of a node is
37375      * being cached.
37376      */
37377     Graph.prototype.isCachingNodeSequence = function (key) {
37378         var node = this.getNode(key);
37379         return node.sequenceKey in this._cachingSequences$;
37380     };
37381     /**
37382      * Get a value indicating if the graph is caching a sequence.
37383      *
37384      * @param {string} sequenceKey - Key of sequence.
37385      * @returns {boolean} Value indicating if the sequence is
37386      * being cached.
37387      */
37388     Graph.prototype.isCachingSequence = function (sequenceKey) {
37389         return sequenceKey in this._cachingSequences$;
37390     };
37391     /**
37392      * Get a value indicating if the graph is caching sequence nodes.
37393      *
37394      * @param {string} sequenceKey - Key of sequence.
37395      * @returns {boolean} Value indicating if the sequence nodes are
37396      * being cached.
37397      */
37398     Graph.prototype.isCachingSequenceNodes = function (sequenceKey) {
37399         return sequenceKey in this._cachingSequenceNodes$;
37400     };
37401     /**
37402      * Get a value indicating if the graph is caching the tiles
37403      * required for calculating spatial edges of a node.
37404      *
37405      * @param {string} key - Key of node.
37406      * @returns {boolean} Value indicating if the tiles of
37407      * a node are being cached.
37408      */
37409     Graph.prototype.isCachingTiles = function (key) {
37410         return key in this._requiredNodeTiles &&
37411             this._requiredNodeTiles[key].cache.length === 0 &&
37412             this._requiredNodeTiles[key].caching.length > 0;
37413     };
37414     /**
37415      * Get a value indicating if the cache has been initialized
37416      * for a node.
37417      *
37418      * @param {string} key - Key of node.
37419      * @returns {boolean} Value indicating if the cache has been
37420      * initialized for a node.
37421      */
37422     Graph.prototype.hasInitializedCache = function (key) {
37423         return key in this._cachedNodes;
37424     };
37425     /**
37426      * Get a value indicating if a node exist in the graph.
37427      *
37428      * @param {string} key - Key of node.
37429      * @returns {boolean} Value indicating if a node exist in the graph.
37430      */
37431     Graph.prototype.hasNode = function (key) {
37432         var accessed = new Date().getTime();
37433         this._updateCachedNodeAccess(key, accessed);
37434         this._updateCachedTileAccess(key, accessed);
37435         return key in this._nodes;
37436     };
37437     /**
37438      * Get a value indicating if a node sequence exist in the graph.
37439      *
37440      * @param {string} key - Key of node.
37441      * @returns {boolean} Value indicating if a node sequence exist
37442      * in the graph.
37443      */
37444     Graph.prototype.hasNodeSequence = function (key) {
37445         var node = this.getNode(key);
37446         var sequenceKey = node.sequenceKey;
37447         var hasNodeSequence = sequenceKey in this._sequences;
37448         if (hasNodeSequence) {
37449             this._sequences[sequenceKey].accessed = new Date().getTime();
37450         }
37451         return hasNodeSequence;
37452     };
37453     /**
37454      * Get a value indicating if a sequence exist in the graph.
37455      *
37456      * @param {string} sequenceKey - Key of sequence.
37457      * @returns {boolean} Value indicating if a sequence exist
37458      * in the graph.
37459      */
37460     Graph.prototype.hasSequence = function (sequenceKey) {
37461         var hasSequence = sequenceKey in this._sequences;
37462         if (hasSequence) {
37463             this._sequences[sequenceKey].accessed = new Date().getTime();
37464         }
37465         return hasSequence;
37466     };
37467     /**
37468      * Get a value indicating if sequence nodes has been cached in the graph.
37469      *
37470      * @param {string} sequenceKey - Key of sequence.
37471      * @returns {boolean} Value indicating if a sequence nodes has been
37472      * cached in the graph.
37473      */
37474     Graph.prototype.hasSequenceNodes = function (sequenceKey) {
37475         return sequenceKey in this._cachedSequenceNodes;
37476     };
37477     /**
37478      * Get a value indicating if the graph has fully cached
37479      * all nodes in the spatial area of a node.
37480      *
37481      * @param {string} key - Key of node.
37482      * @returns {boolean} Value indicating if the spatial area
37483      * of a node has been cached.
37484      */
37485     Graph.prototype.hasSpatialArea = function (key) {
37486         if (!this.hasNode(key)) {
37487             throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
37488         }
37489         if (key in this._cachedSpatialEdges) {
37490             return true;
37491         }
37492         if (key in this._requiredSpatialArea) {
37493             return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
37494         }
37495         var node = this.getNode(key);
37496         var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
37497         var spatialItems = this._nodeIndex.search({
37498             maxX: bbox[1].lat,
37499             maxY: bbox[1].lon,
37500             minX: bbox[0].lat,
37501             minY: bbox[0].lon,
37502         });
37503         var spatialNodes = {
37504             all: {},
37505             cacheKeys: [],
37506             cacheNodes: {},
37507         };
37508         for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
37509             var spatialItem = spatialItems_1[_i];
37510             spatialNodes.all[spatialItem.node.key] = spatialItem.node;
37511             if (!spatialItem.node.full) {
37512                 spatialNodes.cacheKeys.push(spatialItem.node.key);
37513                 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
37514             }
37515         }
37516         this._requiredSpatialArea[key] = spatialNodes;
37517         return spatialNodes.cacheKeys.length === 0;
37518     };
37519     /**
37520      * Get a value indicating if the graph has a tiles required
37521      * for a node.
37522      *
37523      * @param {string} key - Key of node.
37524      * @returns {boolean} Value indicating if the the tiles required
37525      * by a node has been cached.
37526      */
37527     Graph.prototype.hasTiles = function (key) {
37528         var _this = this;
37529         if (key in this._cachedNodeTiles) {
37530             return true;
37531         }
37532         if (key in this._cachedSpatialEdges) {
37533             return true;
37534         }
37535         if (!this.hasNode(key)) {
37536             throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
37537         }
37538         var nodeTiles = { cache: [], caching: [] };
37539         if (!(key in this._requiredNodeTiles)) {
37540             var node = this.getNode(key);
37541             nodeTiles.cache = this._graphCalculator
37542                 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
37543                 .filter(function (h) {
37544                 return !(h in _this._cachedTiles);
37545             });
37546             if (nodeTiles.cache.length > 0) {
37547                 this._requiredNodeTiles[key] = nodeTiles;
37548             }
37549         }
37550         else {
37551             nodeTiles = this._requiredNodeTiles[key];
37552         }
37553         return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
37554     };
37555     /**
37556      * Get a node.
37557      *
37558      * @param {string} key - Key of node.
37559      * @returns {Node} Retrieved node.
37560      */
37561     Graph.prototype.getNode = function (key) {
37562         var accessed = new Date().getTime();
37563         this._updateCachedNodeAccess(key, accessed);
37564         this._updateCachedTileAccess(key, accessed);
37565         return this._nodes[key];
37566     };
37567     /**
37568      * Get a sequence.
37569      *
37570      * @param {string} sequenceKey - Key of sequence.
37571      * @returns {Node} Retrieved sequence.
37572      */
37573     Graph.prototype.getSequence = function (sequenceKey) {
37574         var sequenceAccess = this._sequences[sequenceKey];
37575         sequenceAccess.accessed = new Date().getTime();
37576         return sequenceAccess.sequence;
37577     };
37578     /**
37579      * Reset all spatial edges of the graph nodes.
37580      */
37581     Graph.prototype.resetSpatialEdges = function () {
37582         var cachedKeys = Object.keys(this._cachedSpatialEdges);
37583         for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
37584             var cachedKey = cachedKeys_1[_i];
37585             var node = this._cachedSpatialEdges[cachedKey];
37586             node.resetSpatialEdges();
37587             delete this._cachedSpatialEdges[cachedKey];
37588         }
37589     };
37590     /**
37591      * Reset the complete graph but keep the nodes corresponding
37592      * to the supplied keys. All other nodes will be disposed.
37593      *
37594      * @param {Array<string>} keepKeys - Keys for nodes to keep
37595      * in graph after reset.
37596      */
37597     Graph.prototype.reset = function (keepKeys) {
37598         var nodes = [];
37599         for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
37600             var key = keepKeys_1[_i];
37601             if (!this.hasNode(key)) {
37602                 throw new Error("Node does not exist " + key);
37603             }
37604             var node = this.getNode(key);
37605             node.resetSequenceEdges();
37606             node.resetSpatialEdges();
37607             nodes.push(node);
37608         }
37609         for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
37610             var cachedKey = _b[_a];
37611             if (keepKeys.indexOf(cachedKey) !== -1) {
37612                 continue;
37613             }
37614             this._cachedNodes[cachedKey].node.dispose();
37615             delete this._cachedNodes[cachedKey];
37616         }
37617         this._cachedNodeTiles = {};
37618         this._cachedSpatialEdges = {};
37619         this._cachedTiles = {};
37620         this._cachingFill$ = {};
37621         this._cachingFull$ = {};
37622         this._cachingSequences$ = {};
37623         this._cachingSpatialArea$ = {};
37624         this._cachingTiles$ = {};
37625         this._nodes = {};
37626         this._nodeToTile = {};
37627         this._preStored = {};
37628         for (var _c = 0, nodes_2 = nodes; _c < nodes_2.length; _c++) {
37629             var node = nodes_2[_c];
37630             this._nodes[node.key] = node;
37631             var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
37632             this._preStore(h, node);
37633         }
37634         this._requiredNodeTiles = {};
37635         this._requiredSpatialArea = {};
37636         this._sequences = {};
37637         this._nodeIndexTiles = {};
37638         this._nodeIndex.clear();
37639     };
37640     /**
37641      * Set the spatial node filter.
37642      *
37643      * @param {FilterExpression} filter - Filter expression to be applied
37644      * when calculating spatial edges.
37645      */
37646     Graph.prototype.setFilter = function (filter) {
37647         this._filter = this._filterCreator.createFilter(filter);
37648     };
37649     /**
37650      * Uncache the graph according to the graph configuration.
37651      *
37652      * @description Uncaches unused tiles, unused nodes and
37653      * sequences according to the numbers specified in the
37654      * graph configuration. Sequences does not have a direct
37655      * reference to either tiles or nodes and may be uncached
37656      * even if they are related to the nodes that should be kept.
37657      *
37658      * @param {Array<string>} keepKeys - Keys of nodes to keep in
37659      * graph unrelated to last access. Tiles related to those keys
37660      * will also be kept in graph.
37661      * @param {string} keepSequenceKey - Optional key of sequence
37662      * for which the belonging nodes should not be disposed or
37663      * removed from the graph. These nodes may still be uncached if
37664      * not specified in keep keys param.
37665      */
37666     Graph.prototype.uncache = function (keepKeys, keepSequenceKey) {
37667         var keysInUse = {};
37668         this._addNewKeys(keysInUse, this._cachingFull$);
37669         this._addNewKeys(keysInUse, this._cachingFill$);
37670         this._addNewKeys(keysInUse, this._cachingSpatialArea$);
37671         this._addNewKeys(keysInUse, this._requiredNodeTiles);
37672         this._addNewKeys(keysInUse, this._requiredSpatialArea);
37673         for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
37674             var key = keepKeys_2[_i];
37675             if (key in keysInUse) {
37676                 continue;
37677             }
37678             keysInUse[key] = true;
37679         }
37680         var keepHs = {};
37681         for (var key in keysInUse) {
37682             if (!keysInUse.hasOwnProperty(key)) {
37683                 continue;
37684             }
37685             var node = this._nodes[key];
37686             var nodeHs = this._graphCalculator.encodeHs(node.latLon);
37687             for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
37688                 var nodeH = nodeHs_1[_a];
37689                 if (!(nodeH in keepHs)) {
37690                     keepHs[nodeH] = true;
37691                 }
37692             }
37693         }
37694         var potentialHs = [];
37695         for (var h in this._cachedTiles) {
37696             if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
37697                 continue;
37698             }
37699             potentialHs.push([h, this._cachedTiles[h]]);
37700         }
37701         var uncacheHs = potentialHs
37702             .sort(function (h1, h2) {
37703             return h2[1].accessed - h1[1].accessed;
37704         })
37705             .slice(this._configuration.maxUnusedTiles)
37706             .map(function (h) {
37707             return h[0];
37708         });
37709         for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
37710             var uncacheH = uncacheHs_1[_b];
37711             this._uncacheTile(uncacheH, keepSequenceKey);
37712         }
37713         var potentialPreStored = [];
37714         var nonCachedPreStored = [];
37715         for (var h in this._preStored) {
37716             if (!this._preStored.hasOwnProperty(h) || h in this._cachingTiles$) {
37717                 continue;
37718             }
37719             var prestoredNodes = this._preStored[h];
37720             for (var key in prestoredNodes) {
37721                 if (!prestoredNodes.hasOwnProperty(key) || key in keysInUse) {
37722                     continue;
37723                 }
37724                 if (prestoredNodes[key].sequenceKey === keepSequenceKey) {
37725                     continue;
37726                 }
37727                 if (key in this._cachedNodes) {
37728                     potentialPreStored.push([this._cachedNodes[key], h]);
37729                 }
37730                 else {
37731                     nonCachedPreStored.push([key, h]);
37732                 }
37733             }
37734         }
37735         var uncachePreStored = potentialPreStored
37736             .sort(function (_a, _b) {
37737             var na1 = _a[0], h1 = _a[1];
37738             var na2 = _b[0], h2 = _b[1];
37739             return na2.accessed - na1.accessed;
37740         })
37741             .slice(this._configuration.maxUnusedPreStoredNodes)
37742             .map(function (_a) {
37743             var na = _a[0], h = _a[1];
37744             return [na.node.key, h];
37745         });
37746         this._uncachePreStored(nonCachedPreStored);
37747         this._uncachePreStored(uncachePreStored);
37748         var potentialNodes = [];
37749         for (var key in this._cachedNodes) {
37750             if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
37751                 continue;
37752             }
37753             potentialNodes.push(this._cachedNodes[key]);
37754         }
37755         var uncacheNodes = potentialNodes
37756             .sort(function (n1, n2) {
37757             return n2.accessed - n1.accessed;
37758         })
37759             .slice(this._configuration.maxUnusedNodes);
37760         for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
37761             var nodeAccess = uncacheNodes_1[_c];
37762             nodeAccess.node.uncache();
37763             var key = nodeAccess.node.key;
37764             delete this._cachedNodes[key];
37765             if (key in this._cachedNodeTiles) {
37766                 delete this._cachedNodeTiles[key];
37767             }
37768             if (key in this._cachedSpatialEdges) {
37769                 delete this._cachedSpatialEdges[key];
37770             }
37771         }
37772         var potentialSequences = [];
37773         for (var sequenceKey in this._sequences) {
37774             if (!this._sequences.hasOwnProperty(sequenceKey) ||
37775                 sequenceKey in this._cachingSequences$ ||
37776                 sequenceKey === keepSequenceKey) {
37777                 continue;
37778             }
37779             potentialSequences.push(this._sequences[sequenceKey]);
37780         }
37781         var uncacheSequences = potentialSequences
37782             .sort(function (s1, s2) {
37783             return s2.accessed - s1.accessed;
37784         })
37785             .slice(this._configuration.maxSequences);
37786         for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
37787             var sequenceAccess = uncacheSequences_1[_d];
37788             var sequenceKey = sequenceAccess.sequence.key;
37789             delete this._sequences[sequenceKey];
37790             if (sequenceKey in this._cachedSequenceNodes) {
37791                 delete this._cachedSequenceNodes[sequenceKey];
37792             }
37793             sequenceAccess.sequence.dispose();
37794         }
37795     };
37796     Graph.prototype._addNewKeys = function (keys, dict) {
37797         for (var key in dict) {
37798             if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
37799                 continue;
37800             }
37801             if (!(key in keys)) {
37802                 keys[key] = true;
37803             }
37804         }
37805     };
37806     Graph.prototype._cacheSequence$ = function (sequenceKey) {
37807         var _this = this;
37808         if (sequenceKey in this._cachingSequences$) {
37809             return this._cachingSequences$[sequenceKey];
37810         }
37811         this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey]).pipe(operators_1.tap(function (sequenceByKey) {
37812             if (!(sequenceKey in _this._sequences)) {
37813                 _this._sequences[sequenceKey] = {
37814                     accessed: new Date().getTime(),
37815                     sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
37816                 };
37817             }
37818             delete _this._cachingSequences$[sequenceKey];
37819         }), operators_1.map(function (sequenceByKey) {
37820             return _this;
37821         }), operators_1.finalize(function () {
37822             if (sequenceKey in _this._cachingSequences$) {
37823                 delete _this._cachingSequences$[sequenceKey];
37824             }
37825             _this._changed$.next(_this);
37826         }), operators_1.publish(), operators_1.refCount());
37827         return this._cachingSequences$[sequenceKey];
37828     };
37829     Graph.prototype._cacheTile$ = function (h) {
37830         var _this = this;
37831         this._cachingTiles$[h] = this._apiV3.imagesByH$([h]).pipe(operators_1.tap(function (imagesByH) {
37832             var coreNodes = imagesByH[h];
37833             if (h in _this._cachedTiles) {
37834                 return;
37835             }
37836             _this._nodeIndexTiles[h] = [];
37837             _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
37838             var hCache = _this._cachedTiles[h].nodes;
37839             var preStored = _this._removeFromPreStore(h);
37840             for (var index in coreNodes) {
37841                 if (!coreNodes.hasOwnProperty(index)) {
37842                     continue;
37843                 }
37844                 var coreNode = coreNodes[index];
37845                 if (coreNode == null) {
37846                     break;
37847                 }
37848                 if (coreNode.sequence_key == null) {
37849                     console.warn("Sequence missing, discarding node (" + coreNode.key + ")");
37850                     continue;
37851                 }
37852                 if (preStored != null && coreNode.key in preStored) {
37853                     var preStoredNode = preStored[coreNode.key];
37854                     delete preStored[coreNode.key];
37855                     hCache.push(preStoredNode);
37856                     var preStoredNodeIndexItem = {
37857                         lat: preStoredNode.latLon.lat,
37858                         lon: preStoredNode.latLon.lon,
37859                         node: preStoredNode,
37860                     };
37861                     _this._nodeIndex.insert(preStoredNodeIndexItem);
37862                     _this._nodeIndexTiles[h].push(preStoredNodeIndexItem);
37863                     _this._nodeToTile[preStoredNode.key] = h;
37864                     continue;
37865                 }
37866                 var node = new Graph_1.Node(coreNode);
37867                 hCache.push(node);
37868                 var nodeIndexItem = {
37869                     lat: node.latLon.lat,
37870                     lon: node.latLon.lon,
37871                     node: node,
37872                 };
37873                 _this._nodeIndex.insert(nodeIndexItem);
37874                 _this._nodeIndexTiles[h].push(nodeIndexItem);
37875                 _this._nodeToTile[node.key] = h;
37876                 _this._setNode(node);
37877             }
37878             delete _this._cachingTiles$[h];
37879         }), operators_1.map(function (imagesByH) {
37880             return _this;
37881         }), operators_1.catchError(function (error) {
37882             delete _this._cachingTiles$[h];
37883             throw error;
37884         }), operators_1.publish(), operators_1.refCount());
37885         return this._cachingTiles$[h];
37886     };
37887     Graph.prototype._makeFull = function (node, fillNode) {
37888         if (fillNode.calt == null) {
37889             fillNode.calt = this._defaultAlt;
37890         }
37891         if (fillNode.c_rotation == null) {
37892             fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
37893         }
37894         node.makeFull(fillNode);
37895     };
37896     Graph.prototype._preStore = function (h, node) {
37897         if (!(h in this._preStored)) {
37898             this._preStored[h] = {};
37899         }
37900         this._preStored[h][node.key] = node;
37901     };
37902     Graph.prototype._removeFromPreStore = function (h) {
37903         var preStored = null;
37904         if (h in this._preStored) {
37905             preStored = this._preStored[h];
37906             delete this._preStored[h];
37907         }
37908         return preStored;
37909     };
37910     Graph.prototype._setNode = function (node) {
37911         var key = node.key;
37912         if (this.hasNode(key)) {
37913             throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
37914         }
37915         this._nodes[key] = node;
37916     };
37917     Graph.prototype._uncacheTile = function (h, keepSequenceKey) {
37918         for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
37919             var node = _a[_i];
37920             var key = node.key;
37921             delete this._nodeToTile[key];
37922             if (key in this._cachedNodes) {
37923                 delete this._cachedNodes[key];
37924             }
37925             if (key in this._cachedNodeTiles) {
37926                 delete this._cachedNodeTiles[key];
37927             }
37928             if (key in this._cachedSpatialEdges) {
37929                 delete this._cachedSpatialEdges[key];
37930             }
37931             if (node.sequenceKey === keepSequenceKey) {
37932                 this._preStore(h, node);
37933                 node.uncache();
37934             }
37935             else {
37936                 delete this._nodes[key];
37937                 if (node.sequenceKey in this._cachedSequenceNodes) {
37938                     delete this._cachedSequenceNodes[node.sequenceKey];
37939                 }
37940                 node.dispose();
37941             }
37942         }
37943         for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
37944             var nodeIndexItem = _c[_b];
37945             this._nodeIndex.remove(nodeIndexItem);
37946         }
37947         delete this._nodeIndexTiles[h];
37948         delete this._cachedTiles[h];
37949     };
37950     Graph.prototype._uncachePreStored = function (preStored) {
37951         var hs = {};
37952         for (var _i = 0, preStored_1 = preStored; _i < preStored_1.length; _i++) {
37953             var _a = preStored_1[_i], key = _a[0], h = _a[1];
37954             if (key in this._nodes) {
37955                 delete this._nodes[key];
37956             }
37957             if (key in this._cachedNodes) {
37958                 delete this._cachedNodes[key];
37959             }
37960             var node = this._preStored[h][key];
37961             if (node.sequenceKey in this._cachedSequenceNodes) {
37962                 delete this._cachedSequenceNodes[node.sequenceKey];
37963             }
37964             delete this._preStored[h][key];
37965             node.dispose();
37966             hs[h] = true;
37967         }
37968         for (var h in hs) {
37969             if (!hs.hasOwnProperty(h)) {
37970                 continue;
37971             }
37972             if (Object.keys(this._preStored[h]).length === 0) {
37973                 delete this._preStored[h];
37974             }
37975         }
37976     };
37977     Graph.prototype._updateCachedTileAccess = function (key, accessed) {
37978         if (key in this._nodeToTile) {
37979             this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
37980         }
37981     };
37982     Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
37983         if (key in this._cachedNodes) {
37984             this._cachedNodes[key].accessed = accessed;
37985         }
37986     };
37987     return Graph;
37988 }());
37989 exports.Graph = Graph;
37990 exports.default = Graph;
37991
37992 },{"../Edge":275,"../Error":276,"../Graph":278,"rbush":25,"rxjs":26,"rxjs/operators":224}],390:[function(require,module,exports){
37993 "use strict";
37994 Object.defineProperty(exports, "__esModule", { value: true });
37995 var geohash = require("latlon-geohash");
37996 var THREE = require("three");
37997 var Error_1 = require("../Error");
37998 var Geo_1 = require("../Geo");
37999 /**
38000  * @class GraphCalculator
38001  *
38002  * @classdesc Represents a calculator for graph entities.
38003  */
38004 var GraphCalculator = /** @class */ (function () {
38005     /**
38006      * Create a new graph calculator instance.
38007      *
38008      * @param {GeoCoords} geoCoords - Geo coords instance.
38009      */
38010     function GraphCalculator(geoCoords) {
38011         this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
38012     }
38013     /**
38014      * Encode the geohash tile for geodetic coordinates.
38015      *
38016      * @param {ILatLon} latlon - Latitude and longitude to encode.
38017      * @param {number} precision - Precision of the encoding.
38018      *
38019      * @returns {string} The geohash tile for the lat, lon and precision.
38020      */
38021     GraphCalculator.prototype.encodeH = function (latLon, precision) {
38022         if (precision === void 0) { precision = 7; }
38023         return geohash.encode(latLon.lat, latLon.lon, precision);
38024     };
38025     /**
38026      * Encode the geohash tiles within a threshold from a position
38027      * using Manhattan distance.
38028      *
38029      * @param {ILatLon} latlon - Latitude and longitude to encode.
38030      * @param {number} precision - Precision of the encoding.
38031      * @param {number} threshold - Threshold of the encoding in meters.
38032      *
38033      * @returns {string} The geohash tiles reachable within the threshold.
38034      */
38035     GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
38036         if (precision === void 0) { precision = 7; }
38037         if (threshold === void 0) { threshold = 20; }
38038         var h = geohash.encode(latLon.lat, latLon.lon, precision);
38039         var bounds = geohash.bounds(h);
38040         var ne = bounds.ne;
38041         var sw = bounds.sw;
38042         var neighbours = geohash.neighbours(h);
38043         var bl = [0, 0, 0];
38044         var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
38045         var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
38046         var left = position[0] - bl[0];
38047         var right = tr[0] - position[0];
38048         var bottom = position[1] - bl[1];
38049         var top = tr[1] - position[1];
38050         var l = left < threshold;
38051         var r = right < threshold;
38052         var b = bottom < threshold;
38053         var t = top < threshold;
38054         var hs = [h];
38055         if (t) {
38056             hs.push(neighbours.n);
38057         }
38058         if (t && l) {
38059             hs.push(neighbours.nw);
38060         }
38061         if (l) {
38062             hs.push(neighbours.w);
38063         }
38064         if (l && b) {
38065             hs.push(neighbours.sw);
38066         }
38067         if (b) {
38068             hs.push(neighbours.s);
38069         }
38070         if (b && r) {
38071             hs.push(neighbours.se);
38072         }
38073         if (r) {
38074             hs.push(neighbours.e);
38075         }
38076         if (r && t) {
38077             hs.push(neighbours.ne);
38078         }
38079         return hs;
38080     };
38081     /**
38082      * Encode the minimum set of geohash tiles containing a bounding box.
38083      *
38084      * @description The current algorithm does expect the bounding box
38085      * to be sufficiently small to be contained in an area with the size
38086      * of maximally four tiles. Up to nine adjacent tiles may be returned.
38087      * The method currently uses the largest side as the threshold leading to
38088      * more tiles being returned than needed in edge cases.
38089      *
38090      * @param {ILatLon} sw - South west corner of bounding box.
38091      * @param {ILatLon} ne - North east corner of bounding box.
38092      * @param {number} precision - Precision of the encoding.
38093      *
38094      * @returns {string} The geohash tiles containing the bounding box.
38095      */
38096     GraphCalculator.prototype.encodeHsFromBoundingBox = function (sw, ne, precision) {
38097         if (precision === void 0) { precision = 7; }
38098         if (ne.lat <= sw.lat || ne.lon <= sw.lon) {
38099             throw new Error_1.GraphMapillaryError("North east needs to be top right of south west");
38100         }
38101         var centerLat = (sw.lat + ne.lat) / 2;
38102         var centerLon = (sw.lon + ne.lon) / 2;
38103         var enu = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, centerLat, centerLon, 0);
38104         var threshold = Math.max(enu[0], enu[1]);
38105         return this.encodeHs({ lat: centerLat, lon: centerLon }, precision, threshold);
38106     };
38107     /**
38108      * Get the bounding box corners for a circle with radius of a threshold
38109      * with center in a geodetic position.
38110      *
38111      * @param {ILatLon} latlon - Latitude and longitude to encode.
38112      * @param {number} threshold - Threshold distance from the position in meters.
38113      *
38114      * @returns {Array<ILatLon>} The south west and north east corners of the
38115      * bounding box.
38116      */
38117     GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
38118         var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
38119         var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
38120         return [
38121             { lat: bl[0], lon: bl[1] },
38122             { lat: tr[0], lon: tr[1] },
38123         ];
38124     };
38125     /**
38126      * Convert a compass angle to an angle axis rotation vector.
38127      *
38128      * @param {number} compassAngle - The compass angle in degrees.
38129      * @param {number} orientation - The orientation of the original image.
38130      *
38131      * @returns {Array<number>} Angle axis rotation vector.
38132      */
38133     GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
38134         var x = 0;
38135         var y = 0;
38136         var z = 0;
38137         switch (orientation) {
38138             case 1:
38139                 x = Math.PI / 2;
38140                 break;
38141             case 3:
38142                 x = -Math.PI / 2;
38143                 z = Math.PI;
38144                 break;
38145             case 6:
38146                 y = -Math.PI / 2;
38147                 z = -Math.PI / 2;
38148                 break;
38149             case 8:
38150                 y = Math.PI / 2;
38151                 z = Math.PI / 2;
38152                 break;
38153             default:
38154                 break;
38155         }
38156         var rz = new THREE.Matrix4().makeRotationZ(z);
38157         var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
38158         var re = new THREE.Matrix4().makeRotationFromEuler(euler);
38159         var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
38160         return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
38161     };
38162     return GraphCalculator;
38163 }());
38164 exports.GraphCalculator = GraphCalculator;
38165 exports.default = GraphCalculator;
38166
38167 },{"../Error":276,"../Geo":277,"latlon-geohash":21,"three":225}],391:[function(require,module,exports){
38168 "use strict";
38169 Object.defineProperty(exports, "__esModule", { value: true });
38170 /**
38171  * Enumeration for graph modes.
38172  * @enum {number}
38173  * @readonly
38174  * @description Modes for the retrieval and caching performed
38175  * by the graph service on the graph.
38176  */
38177 var GraphMode;
38178 (function (GraphMode) {
38179     /**
38180      * Caching is performed on sequences only and sequence edges are
38181      * calculated. Spatial tiles
38182      * are not retrieved and spatial edges are not calculated when
38183      * caching nodes. Complete sequences are being cached for requested
38184      * nodes within the graph.
38185      */
38186     GraphMode[GraphMode["Sequence"] = 0] = "Sequence";
38187     /**
38188      * Caching is performed with emphasis on spatial data. Sequence edges
38189      * as well as spatial edges are cached. Sequence data
38190      * is still requested but complete sequences are not being cached
38191      * for requested nodes.
38192      *
38193      * This is the initial mode of the graph service.
38194      */
38195     GraphMode[GraphMode["Spatial"] = 1] = "Spatial";
38196 })(GraphMode = exports.GraphMode || (exports.GraphMode = {}));
38197 exports.default = GraphMode;
38198
38199 },{}],392:[function(require,module,exports){
38200 "use strict";
38201 Object.defineProperty(exports, "__esModule", { value: true });
38202 var rxjs_1 = require("rxjs");
38203 var operators_1 = require("rxjs/operators");
38204 var Graph_1 = require("../Graph");
38205 /**
38206  * @class GraphService
38207  *
38208  * @classdesc Represents a service for graph operations.
38209  */
38210 var GraphService = /** @class */ (function () {
38211     /**
38212      * Create a new graph service instance.
38213      *
38214      * @param {Graph} graph - Graph instance to be operated on.
38215      */
38216     function GraphService(graph, imageLoadingService) {
38217         this._graph$ = rxjs_1.concat(rxjs_1.of(graph), graph.changed$).pipe(operators_1.publishReplay(1), operators_1.refCount());
38218         this._graph$.subscribe(function () { });
38219         this._graphMode = Graph_1.GraphMode.Spatial;
38220         this._graphModeSubject$ = new rxjs_1.Subject();
38221         this._graphMode$ = this._graphModeSubject$.pipe(operators_1.startWith(this._graphMode), operators_1.publishReplay(1), operators_1.refCount());
38222         this._graphMode$.subscribe(function () { });
38223         this._imageLoadingService = imageLoadingService;
38224         this._firstGraphSubjects$ = [];
38225         this._initializeCacheSubscriptions = [];
38226         this._sequenceSubscriptions = [];
38227         this._spatialSubscriptions = [];
38228     }
38229     Object.defineProperty(GraphService.prototype, "graphMode$", {
38230         /**
38231          * Get graph mode observable.
38232          *
38233          * @description Emits the current graph mode.
38234          *
38235          * @returns {Observable<GraphMode>} Observable
38236          * emitting the current graph mode when it changes.
38237          */
38238         get: function () {
38239             return this._graphMode$;
38240         },
38241         enumerable: true,
38242         configurable: true
38243     });
38244     /**
38245      * Cache full nodes in a bounding box.
38246      *
38247      * @description When called, the full properties of
38248      * the node are retrieved. The node cache is not initialized
38249      * for any new nodes retrieved and the node assets are not
38250      * retrieved, {@link cacheNode$} needs to be called for caching
38251      * assets.
38252      *
38253      * @param {ILatLon} sw - South west corner of bounding box.
38254      * @param {ILatLon} ne - North east corner of bounding box.
38255      * @return {Observable<Array<Node>>} Observable emitting a single item,
38256      * the nodes of the bounding box, when they have all been retrieved.
38257      * @throws {Error} Propagates any IO node caching errors to the caller.
38258      */
38259     GraphService.prototype.cacheBoundingBox$ = function (sw, ne) {
38260         return this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
38261             return graph.cacheBoundingBox$(sw, ne);
38262         }));
38263     };
38264     /**
38265      * Cache a node in the graph and retrieve it.
38266      *
38267      * @description When called, the full properties of
38268      * the node are retrieved and the node cache is initialized.
38269      * After that the node assets are cached and the node
38270      * is emitted to the observable when.
38271      * In parallel to caching the node assets, the sequence and
38272      * spatial edges of the node are cached. For this, the sequence
38273      * of the node and the required tiles and spatial nodes are
38274      * retrieved. The sequence and spatial edges may be set before
38275      * or after the node is returned.
38276      *
38277      * @param {string} key - Key of the node to cache.
38278      * @return {Observable<Node>} Observable emitting a single item,
38279      * the node, when it has been retrieved and its assets are cached.
38280      * @throws {Error} Propagates any IO node caching errors to the caller.
38281      */
38282     GraphService.prototype.cacheNode$ = function (key) {
38283         var _this = this;
38284         var firstGraphSubject$ = new rxjs_1.Subject();
38285         this._firstGraphSubjects$.push(firstGraphSubject$);
38286         var firstGraph$ = firstGraphSubject$.pipe(operators_1.publishReplay(1), operators_1.refCount());
38287         var node$ = firstGraph$.pipe(operators_1.map(function (graph) {
38288             return graph.getNode(key);
38289         }), operators_1.mergeMap(function (node) {
38290             return node.assetsCached ?
38291                 rxjs_1.of(node) :
38292                 node.cacheAssets$();
38293         }), operators_1.publishReplay(1), operators_1.refCount());
38294         node$.subscribe(function (node) {
38295             _this._imageLoadingService.loadnode$.next(node);
38296         }, function (error) {
38297             console.error("Failed to cache node (" + key + ")", error);
38298         });
38299         var initializeCacheSubscription = this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
38300             if (graph.isCachingFull(key) || !graph.hasNode(key)) {
38301                 return graph.cacheFull$(key);
38302             }
38303             if (graph.isCachingFill(key) || !graph.getNode(key).full) {
38304                 return graph.cacheFill$(key);
38305             }
38306             return rxjs_1.of(graph);
38307         }), operators_1.tap(function (graph) {
38308             if (!graph.hasInitializedCache(key)) {
38309                 graph.initializeCache(key);
38310             }
38311         }), operators_1.finalize(function () {
38312             if (initializeCacheSubscription == null) {
38313                 return;
38314             }
38315             _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
38316             _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
38317         }))
38318             .subscribe(function (graph) {
38319             firstGraphSubject$.next(graph);
38320             firstGraphSubject$.complete();
38321         }, function (error) {
38322             firstGraphSubject$.error(error);
38323         });
38324         if (!initializeCacheSubscription.closed) {
38325             this._initializeCacheSubscriptions.push(initializeCacheSubscription);
38326         }
38327         var graphSequence$ = firstGraph$.pipe(operators_1.mergeMap(function (graph) {
38328             if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
38329                 return graph.cacheNodeSequence$(key);
38330             }
38331             return rxjs_1.of(graph);
38332         }), operators_1.publishReplay(1), operators_1.refCount());
38333         var sequenceSubscription = graphSequence$.pipe(operators_1.tap(function (graph) {
38334             if (!graph.getNode(key).sequenceEdges.cached) {
38335                 graph.cacheSequenceEdges(key);
38336             }
38337         }), operators_1.finalize(function () {
38338             if (sequenceSubscription == null) {
38339                 return;
38340             }
38341             _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
38342         }))
38343             .subscribe(function (graph) { return; }, function (error) {
38344             console.error("Failed to cache sequence edges (" + key + ").", error);
38345         });
38346         if (!sequenceSubscription.closed) {
38347             this._sequenceSubscriptions.push(sequenceSubscription);
38348         }
38349         if (this._graphMode === Graph_1.GraphMode.Spatial) {
38350             var spatialSubscription_1 = firstGraph$.pipe(operators_1.expand(function (graph) {
38351                 if (graph.hasTiles(key)) {
38352                     return rxjs_1.empty();
38353                 }
38354                 return rxjs_1.from(graph.cacheTiles$(key)).pipe(operators_1.mergeMap(function (graph$) {
38355                     return graph$.pipe(operators_1.mergeMap(function (g) {
38356                         if (g.isCachingTiles(key)) {
38357                             return rxjs_1.empty();
38358                         }
38359                         return rxjs_1.of(g);
38360                     }), operators_1.catchError(function (error, caught$) {
38361                         console.error("Failed to cache tile data (" + key + ").", error);
38362                         return rxjs_1.empty();
38363                     }));
38364                 }));
38365             }), operators_1.last(), operators_1.mergeMap(function (graph) {
38366                 if (graph.hasSpatialArea(key)) {
38367                     return rxjs_1.of(graph);
38368                 }
38369                 return rxjs_1.from(graph.cacheSpatialArea$(key)).pipe(operators_1.mergeMap(function (graph$) {
38370                     return graph$.pipe(operators_1.catchError(function (error, caught$) {
38371                         console.error("Failed to cache spatial nodes (" + key + ").", error);
38372                         return rxjs_1.empty();
38373                     }));
38374                 }));
38375             }), operators_1.last(), operators_1.mergeMap(function (graph) {
38376                 return graph.hasNodeSequence(key) ?
38377                     rxjs_1.of(graph) :
38378                     graph.cacheNodeSequence$(key);
38379             }), operators_1.tap(function (graph) {
38380                 if (!graph.getNode(key).spatialEdges.cached) {
38381                     graph.cacheSpatialEdges(key);
38382                 }
38383             }), operators_1.finalize(function () {
38384                 if (spatialSubscription_1 == null) {
38385                     return;
38386                 }
38387                 _this._removeFromArray(spatialSubscription_1, _this._spatialSubscriptions);
38388             }))
38389                 .subscribe(function (graph) { return; }, function (error) {
38390                 console.error("Failed to cache spatial edges (" + key + ").", error);
38391             });
38392             if (!spatialSubscription_1.closed) {
38393                 this._spatialSubscriptions.push(spatialSubscription_1);
38394             }
38395         }
38396         return node$.pipe(operators_1.first(function (node) {
38397             return node.assetsCached;
38398         }));
38399     };
38400     /**
38401      * Cache a sequence in the graph and retrieve it.
38402      *
38403      * @param {string} sequenceKey - Sequence key.
38404      * @returns {Observable<Sequence>} Observable emitting a single item,
38405      * the sequence, when it has been retrieved and its assets are cached.
38406      * @throws {Error} Propagates any IO node caching errors to the caller.
38407      */
38408     GraphService.prototype.cacheSequence$ = function (sequenceKey) {
38409         return this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
38410             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
38411                 return graph.cacheSequence$(sequenceKey);
38412             }
38413             return rxjs_1.of(graph);
38414         }), operators_1.map(function (graph) {
38415             return graph.getSequence(sequenceKey);
38416         }));
38417     };
38418     /**
38419      * Cache a sequence and its nodes in the graph and retrieve the sequence.
38420      *
38421      * @description Caches a sequence and its assets are cached and
38422      * retrieves all nodes belonging to the sequence. The node assets
38423      * or edges will not be cached.
38424      *
38425      * @param {string} sequenceKey - Sequence key.
38426      * @param {string} referenceNodeKey - Key of node to use as reference
38427      * for optimized caching.
38428      * @returns {Observable<Sequence>} Observable emitting a single item,
38429      * the sequence, when it has been retrieved, its assets are cached and
38430      * all nodes belonging to the sequence has been retrieved.
38431      * @throws {Error} Propagates any IO node caching errors to the caller.
38432      */
38433     GraphService.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
38434         return this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
38435             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
38436                 return graph.cacheSequence$(sequenceKey);
38437             }
38438             return rxjs_1.of(graph);
38439         }), operators_1.mergeMap(function (graph) {
38440             if (graph.isCachingSequenceNodes(sequenceKey) || !graph.hasSequenceNodes(sequenceKey)) {
38441                 return graph.cacheSequenceNodes$(sequenceKey, referenceNodeKey);
38442             }
38443             return rxjs_1.of(graph);
38444         }), operators_1.map(function (graph) {
38445             return graph.getSequence(sequenceKey);
38446         }));
38447     };
38448     /**
38449      * Set a spatial edge filter on the graph.
38450      *
38451      * @description Resets the spatial edges of all cached nodes.
38452      *
38453      * @param {FilterExpression} filter - Filter expression to be applied.
38454      * @return {Observable<Graph>} Observable emitting a single item,
38455      * the graph, when the spatial edges have been reset.
38456      */
38457     GraphService.prototype.setFilter$ = function (filter) {
38458         this._resetSubscriptions(this._spatialSubscriptions);
38459         return this._graph$.pipe(operators_1.first(), operators_1.tap(function (graph) {
38460             graph.resetSpatialEdges();
38461             graph.setFilter(filter);
38462         }), operators_1.map(function (graph) {
38463             return undefined;
38464         }));
38465     };
38466     /**
38467      * Set the graph mode.
38468      *
38469      * @description If graph mode is set to spatial, caching
38470      * is performed with emphasis on spatial edges. If graph
38471      * mode is set to sequence no tile data is requested and
38472      * no spatial edges are computed.
38473      *
38474      * When setting graph mode to sequence all spatial
38475      * subscriptions are aborted.
38476      *
38477      * @param {GraphMode} mode - Graph mode to set.
38478      */
38479     GraphService.prototype.setGraphMode = function (mode) {
38480         if (this._graphMode === mode) {
38481             return;
38482         }
38483         if (mode === Graph_1.GraphMode.Sequence) {
38484             this._resetSubscriptions(this._spatialSubscriptions);
38485         }
38486         this._graphMode = mode;
38487         this._graphModeSubject$.next(this._graphMode);
38488     };
38489     /**
38490      * Reset the graph.
38491      *
38492      * @description Resets the graph but keeps the nodes of the
38493      * supplied keys.
38494      *
38495      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
38496      * @return {Observable<Node>} Observable emitting a single item,
38497      * the graph, when it has been reset.
38498      */
38499     GraphService.prototype.reset$ = function (keepKeys) {
38500         this._abortSubjects(this._firstGraphSubjects$);
38501         this._resetSubscriptions(this._initializeCacheSubscriptions);
38502         this._resetSubscriptions(this._sequenceSubscriptions);
38503         this._resetSubscriptions(this._spatialSubscriptions);
38504         return this._graph$.pipe(operators_1.first(), operators_1.tap(function (graph) {
38505             graph.reset(keepKeys);
38506         }), operators_1.map(function (graph) {
38507             return undefined;
38508         }));
38509     };
38510     /**
38511      * Uncache the graph.
38512      *
38513      * @description Uncaches the graph by removing tiles, nodes and
38514      * sequences. Keeps the nodes of the supplied keys and the tiles
38515      * related to those nodes.
38516      *
38517      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
38518      * @param {string} keepSequenceKey - Optional key of sequence
38519      * for which the belonging nodes should not be disposed or
38520      * removed from the graph. These nodes may still be uncached if
38521      * not specified in keep keys param.
38522      * @return {Observable<Graph>} Observable emitting a single item,
38523      * the graph, when the graph has been uncached.
38524      */
38525     GraphService.prototype.uncache$ = function (keepKeys, keepSequenceKey) {
38526         return this._graph$.pipe(operators_1.first(), operators_1.tap(function (graph) {
38527             graph.uncache(keepKeys, keepSequenceKey);
38528         }), operators_1.map(function (graph) {
38529             return undefined;
38530         }));
38531     };
38532     GraphService.prototype._abortSubjects = function (subjects) {
38533         for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
38534             var subject = _a[_i];
38535             this._removeFromArray(subject, subjects);
38536             subject.error(new Error("Cache node request was aborted."));
38537         }
38538     };
38539     GraphService.prototype._removeFromArray = function (object, objects) {
38540         var index = objects.indexOf(object);
38541         if (index !== -1) {
38542             objects.splice(index, 1);
38543         }
38544     };
38545     GraphService.prototype._resetSubscriptions = function (subscriptions) {
38546         for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
38547             var subscription = _a[_i];
38548             this._removeFromArray(subscription, subscriptions);
38549             if (!subscription.closed) {
38550                 subscription.unsubscribe();
38551             }
38552         }
38553     };
38554     return GraphService;
38555 }());
38556 exports.GraphService = GraphService;
38557 exports.default = GraphService;
38558
38559 },{"../Graph":278,"rxjs":26,"rxjs/operators":224}],393:[function(require,module,exports){
38560 "use strict";
38561 Object.defineProperty(exports, "__esModule", { value: true });
38562 var operators_1 = require("rxjs/operators");
38563 var rxjs_1 = require("rxjs");
38564 var ImageLoadingService = /** @class */ (function () {
38565     function ImageLoadingService() {
38566         this._loadnode$ = new rxjs_1.Subject();
38567         this._loadstatus$ = this._loadnode$.pipe(operators_1.scan(function (_a, node) {
38568             var nodes = _a[0];
38569             var changed = false;
38570             if (node.loadStatus.total === 0 || node.loadStatus.loaded === node.loadStatus.total) {
38571                 if (node.key in nodes) {
38572                     delete nodes[node.key];
38573                     changed = true;
38574                 }
38575             }
38576             else {
38577                 nodes[node.key] = node.loadStatus;
38578                 changed = true;
38579             }
38580             return [nodes, changed];
38581         }, [{}, false]), operators_1.filter(function (_a) {
38582             var nodes = _a[0], changed = _a[1];
38583             return changed;
38584         }), operators_1.map(function (_a) {
38585             var nodes = _a[0];
38586             return nodes;
38587         }), operators_1.publishReplay(1), operators_1.refCount());
38588         this._loadstatus$.subscribe(function () { });
38589     }
38590     Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
38591         get: function () {
38592             return this._loadnode$;
38593         },
38594         enumerable: true,
38595         configurable: true
38596     });
38597     Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
38598         get: function () {
38599             return this._loadstatus$;
38600         },
38601         enumerable: true,
38602         configurable: true
38603     });
38604     return ImageLoadingService;
38605 }());
38606 exports.ImageLoadingService = ImageLoadingService;
38607
38608 },{"rxjs":26,"rxjs/operators":224}],394:[function(require,module,exports){
38609 "use strict";
38610 Object.defineProperty(exports, "__esModule", { value: true });
38611 var Pbf = require("pbf");
38612 var MeshReader = /** @class */ (function () {
38613     function MeshReader() {
38614     }
38615     MeshReader.read = function (buffer) {
38616         var pbf = new Pbf(buffer);
38617         return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
38618     };
38619     MeshReader._readMeshField = function (tag, mesh, pbf) {
38620         if (tag === 1) {
38621             mesh.vertices.push(pbf.readFloat());
38622         }
38623         else if (tag === 2) {
38624             mesh.faces.push(pbf.readVarint());
38625         }
38626     };
38627     return MeshReader;
38628 }());
38629 exports.MeshReader = MeshReader;
38630
38631 },{"pbf":23}],395:[function(require,module,exports){
38632 "use strict";
38633 Object.defineProperty(exports, "__esModule", { value: true });
38634 var operators_1 = require("rxjs/operators");
38635 /**
38636  * @class Node
38637  *
38638  * @classdesc Represents a node in the navigation graph.
38639  *
38640  * Explanation of position and bearing properties:
38641  *
38642  * When images are uploaded they will have GPS information in the EXIF, this is what
38643  * is called `originalLatLon` {@link Node.originalLatLon}.
38644  *
38645  * When Structure from Motions has been run for a node a `computedLatLon` that
38646  * differs from the `originalLatLon` will be created. It is different because
38647  * GPS positions are not very exact and SfM aligns the camera positions according
38648  * to the 3D reconstruction {@link Node.computedLatLon}.
38649  *
38650  * At last there exist a `latLon` property which evaluates to
38651  * the `computedLatLon` from SfM if it exists but falls back
38652  * to the `originalLatLon` from the EXIF GPS otherwise {@link Node.latLon}.
38653  *
38654  * Everything that is done in in the Viewer is based on the SfM positions,
38655  * i.e. `computedLatLon`. That is why the smooth transitions go in the right
38656  * direction (nd not in strange directions because of bad GPS).
38657  *
38658  * E.g. when placing a marker in the Viewer it is relative to the SfM
38659  * position i.e. the `computedLatLon`.
38660  *
38661  * The same concept as above also applies to the compass angle (or bearing) properties
38662  * `originalCa`, `computedCa` and `ca`.
38663  */
38664 var Node = /** @class */ (function () {
38665     /**
38666      * Create a new node instance.
38667      *
38668      * @description Nodes are always created internally by the library.
38669      * Nodes can not be added to the library through any API method.
38670      *
38671      * @param {ICoreNode} coreNode - Raw core node data.
38672      * @ignore
38673      */
38674     function Node(core) {
38675         this._cache = null;
38676         this._core = core;
38677         this._fill = null;
38678     }
38679     Object.defineProperty(Node.prototype, "assetsCached", {
38680         /**
38681          * Get assets cached.
38682          *
38683          * @description The assets that need to be cached for this property
38684          * to report true are the following: fill properties, image and mesh.
38685          * The library ensures that the current node will always have the
38686          * assets cached.
38687          *
38688          * @returns {boolean} Value indicating whether all assets have been
38689          * cached.
38690          *
38691          * @ignore
38692          */
38693         get: function () {
38694             return this._core != null &&
38695                 this._fill != null &&
38696                 this._cache != null &&
38697                 this._cache.image != null &&
38698                 this._cache.mesh != null;
38699         },
38700         enumerable: true,
38701         configurable: true
38702     });
38703     Object.defineProperty(Node.prototype, "alt", {
38704         /**
38705          * Get alt.
38706          *
38707          * @description If SfM has not been run the computed altitude is
38708          * set to a default value of two meters.
38709          *
38710          * @returns {number} Altitude, in meters.
38711          */
38712         get: function () {
38713             return this._fill.calt;
38714         },
38715         enumerable: true,
38716         configurable: true
38717     });
38718     Object.defineProperty(Node.prototype, "ca", {
38719         /**
38720          * Get ca.
38721          *
38722          * @description If the SfM computed compass angle exists it will
38723          * be returned, otherwise the original EXIF compass angle.
38724          *
38725          * @returns {number} Compass angle, measured in degrees
38726          * clockwise with respect to north.
38727          */
38728         get: function () {
38729             return this._fill.cca != null ? this._fill.cca : this._fill.ca;
38730         },
38731         enumerable: true,
38732         configurable: true
38733     });
38734     Object.defineProperty(Node.prototype, "capturedAt", {
38735         /**
38736          * Get capturedAt.
38737          *
38738          * @returns {number} Timestamp when the image was captured.
38739          */
38740         get: function () {
38741             return this._fill.captured_at;
38742         },
38743         enumerable: true,
38744         configurable: true
38745     });
38746     Object.defineProperty(Node.prototype, "cameraUuid", {
38747         /**
38748          * Get camera uuid.
38749          *
38750          * @description Will be undefined if the camera uuid was not
38751          * recorded in the image exif information.
38752          *
38753          * @returns {string} Universally unique id for camera used
38754          * when capturing image.
38755          */
38756         get: function () {
38757             return this._fill.captured_with_camera_uuid;
38758         },
38759         enumerable: true,
38760         configurable: true
38761     });
38762     Object.defineProperty(Node.prototype, "ck1", {
38763         /**
38764          * Get ck1.
38765          *
38766          * @description Will not be set if SfM has not been run.
38767          *
38768          * @returns {number} SfM computed radial distortion parameter
38769          * k1.
38770          */
38771         get: function () {
38772             return this._fill.ck1;
38773         },
38774         enumerable: true,
38775         configurable: true
38776     });
38777     Object.defineProperty(Node.prototype, "ck2", {
38778         /**
38779          * Get ck2.
38780          *
38781          * @description Will not be set if SfM has not been run.
38782          *
38783          * @returns {number} SfM computed radial distortion parameter
38784          * k2.
38785          */
38786         get: function () {
38787             return this._fill.ck2;
38788         },
38789         enumerable: true,
38790         configurable: true
38791     });
38792     Object.defineProperty(Node.prototype, "computedCA", {
38793         /**
38794          * Get computedCA.
38795          *
38796          * @description Will not be set if SfM has not been run.
38797          *
38798          * @returns {number} SfM computed compass angle, measured
38799          * in degrees clockwise with respect to north.
38800          */
38801         get: function () {
38802             return this._fill.cca;
38803         },
38804         enumerable: true,
38805         configurable: true
38806     });
38807     Object.defineProperty(Node.prototype, "computedLatLon", {
38808         /**
38809          * Get computedLatLon.
38810          *
38811          * @description Will not be set if SfM has not been run.
38812          *
38813          * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
38814          * measured in degrees.
38815          */
38816         get: function () {
38817             return this._core.cl;
38818         },
38819         enumerable: true,
38820         configurable: true
38821     });
38822     Object.defineProperty(Node.prototype, "focal", {
38823         /**
38824          * Get focal.
38825          *
38826          * @description Will not be set if SfM has not been run.
38827          *
38828          * @returns {number} SfM computed focal length.
38829          */
38830         get: function () {
38831             return this._fill.cfocal;
38832         },
38833         enumerable: true,
38834         configurable: true
38835     });
38836     Object.defineProperty(Node.prototype, "full", {
38837         /**
38838          * Get full.
38839          *
38840          * @description The library ensures that the current node will
38841          * always be full.
38842          *
38843          * @returns {boolean} Value indicating whether the node has all
38844          * properties filled.
38845          *
38846          * @ignore
38847          */
38848         get: function () {
38849             return this._fill != null;
38850         },
38851         enumerable: true,
38852         configurable: true
38853     });
38854     Object.defineProperty(Node.prototype, "fullPano", {
38855         /**
38856          * Get fullPano.
38857          *
38858          * @returns {boolean} Value indicating whether the node is a complete
38859          * 360 panorama.
38860          */
38861         get: function () {
38862             return this._fill.gpano != null &&
38863                 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
38864                 this._fill.gpano.CroppedAreaTopPixels === 0 &&
38865                 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
38866                 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
38867         },
38868         enumerable: true,
38869         configurable: true
38870     });
38871     Object.defineProperty(Node.prototype, "gpano", {
38872         /**
38873          * Get gpano.
38874          *
38875          * @description Will not be set for non panoramic images.
38876          *
38877          * @returns {IGPano} Panorama information for panorama images.
38878          */
38879         get: function () {
38880             return this._fill.gpano;
38881         },
38882         enumerable: true,
38883         configurable: true
38884     });
38885     Object.defineProperty(Node.prototype, "height", {
38886         /**
38887          * Get height.
38888          *
38889          * @returns {number} Height of original image, not adjusted
38890          * for orientation.
38891          */
38892         get: function () {
38893             return this._fill.height;
38894         },
38895         enumerable: true,
38896         configurable: true
38897     });
38898     Object.defineProperty(Node.prototype, "image", {
38899         /**
38900          * Get image.
38901          *
38902          * @description The image will always be set on the current node.
38903          *
38904          * @returns {HTMLImageElement} Cached image element of the node.
38905          */
38906         get: function () {
38907             return this._cache.image;
38908         },
38909         enumerable: true,
38910         configurable: true
38911     });
38912     Object.defineProperty(Node.prototype, "image$", {
38913         /**
38914          * Get image$.
38915          *
38916          * @returns {Observable<HTMLImageElement>} Observable emitting
38917          * the cached image when it is updated.
38918          *
38919          * @ignore
38920          */
38921         get: function () {
38922             return this._cache.image$;
38923         },
38924         enumerable: true,
38925         configurable: true
38926     });
38927     Object.defineProperty(Node.prototype, "key", {
38928         /**
38929          * Get key.
38930          *
38931          * @returns {string} Unique key of the node.
38932          */
38933         get: function () {
38934             return this._core.key;
38935         },
38936         enumerable: true,
38937         configurable: true
38938     });
38939     Object.defineProperty(Node.prototype, "latLon", {
38940         /**
38941          * Get latLon.
38942          *
38943          * @description If the SfM computed latitude longitude exist
38944          * it will be returned, otherwise the original EXIF latitude
38945          * longitude.
38946          *
38947          * @returns {ILatLon} Latitude longitude in WGS84 datum,
38948          * measured in degrees.
38949          */
38950         get: function () {
38951             return this._core.cl != null ? this._core.cl : this._core.l;
38952         },
38953         enumerable: true,
38954         configurable: true
38955     });
38956     Object.defineProperty(Node.prototype, "loadStatus", {
38957         /**
38958          * Get loadStatus.
38959          *
38960          * @returns {ILoadStatus} Value indicating the load status
38961          * of the mesh and image.
38962          */
38963         get: function () {
38964             return this._cache.loadStatus;
38965         },
38966         enumerable: true,
38967         configurable: true
38968     });
38969     Object.defineProperty(Node.prototype, "merged", {
38970         /**
38971          * Get merged.
38972          *
38973          * @returns {boolean} Value indicating whether SfM has been
38974          * run on the node and the node has been merged into a
38975          * connected component.
38976          */
38977         get: function () {
38978             return this._fill != null &&
38979                 this._fill.merge_version != null &&
38980                 this._fill.merge_version > 0;
38981         },
38982         enumerable: true,
38983         configurable: true
38984     });
38985     Object.defineProperty(Node.prototype, "mergeCC", {
38986         /**
38987          * Get mergeCC.
38988          *
38989          * @description Will not be set if SfM has not yet been run on
38990          * node.
38991          *
38992          * @returns {number} SfM connected component key to which
38993          * image belongs.
38994          */
38995         get: function () {
38996             return this._fill.merge_cc;
38997         },
38998         enumerable: true,
38999         configurable: true
39000     });
39001     Object.defineProperty(Node.prototype, "mergeVersion", {
39002         /**
39003          * Get mergeVersion.
39004          *
39005          * @returns {number} Version for which SfM was run and image was merged.
39006          */
39007         get: function () {
39008             return this._fill.merge_version;
39009         },
39010         enumerable: true,
39011         configurable: true
39012     });
39013     Object.defineProperty(Node.prototype, "mesh", {
39014         /**
39015          * Get mesh.
39016          *
39017          * @description The mesh will always be set on the current node.
39018          *
39019          * @returns {IMesh} SfM triangulated mesh of reconstructed
39020          * atomic 3D points.
39021          */
39022         get: function () {
39023             return this._cache.mesh;
39024         },
39025         enumerable: true,
39026         configurable: true
39027     });
39028     Object.defineProperty(Node.prototype, "organizationKey", {
39029         /**
39030          * Get organizationKey.
39031          *
39032          * @returns {string} Unique key of the organization to which
39033          * the node belongs. If the node does not belong to an
39034          * organization the organization key will be undefined.
39035          */
39036         get: function () {
39037             return this._fill.organization_key;
39038         },
39039         enumerable: true,
39040         configurable: true
39041     });
39042     Object.defineProperty(Node.prototype, "orientation", {
39043         /**
39044          * Get orientation.
39045          *
39046          * @returns {number} EXIF orientation of original image.
39047          */
39048         get: function () {
39049             return this._fill.orientation;
39050         },
39051         enumerable: true,
39052         configurable: true
39053     });
39054     Object.defineProperty(Node.prototype, "originalCA", {
39055         /**
39056          * Get originalCA.
39057          *
39058          * @returns {number} Original EXIF compass angle, measured in
39059          * degrees.
39060          */
39061         get: function () {
39062             return this._fill.ca;
39063         },
39064         enumerable: true,
39065         configurable: true
39066     });
39067     Object.defineProperty(Node.prototype, "originalLatLon", {
39068         /**
39069          * Get originalLatLon.
39070          *
39071          * @returns {ILatLon} Original EXIF latitude longitude in
39072          * WGS84 datum, measured in degrees.
39073          */
39074         get: function () {
39075             return this._core.l;
39076         },
39077         enumerable: true,
39078         configurable: true
39079     });
39080     Object.defineProperty(Node.prototype, "pano", {
39081         /**
39082          * Get pano.
39083          *
39084          * @returns {boolean} Value indicating whether the node is a panorama.
39085          * It could be a cropped or full panorama.
39086          */
39087         get: function () {
39088             return this._fill.gpano != null &&
39089                 this._fill.gpano.FullPanoWidthPixels != null;
39090         },
39091         enumerable: true,
39092         configurable: true
39093     });
39094     Object.defineProperty(Node.prototype, "private", {
39095         /**
39096          * Get private.
39097          *
39098          * @returns {boolean} Value specifying if image is accessible to
39099          * organization members only or to everyone.
39100          */
39101         get: function () {
39102             return this._fill.private;
39103         },
39104         enumerable: true,
39105         configurable: true
39106     });
39107     Object.defineProperty(Node.prototype, "projectKey", {
39108         /**
39109          * Get projectKey.
39110          *
39111          * @returns {string} Unique key of the project to which
39112          * the node belongs. If the node does not belong to a
39113          * project the project key will be undefined.
39114          *
39115          * @deprecated This property will be deprecated in favor
39116          * of the organization key and private properties.
39117          */
39118         get: function () {
39119             return this._fill.project != null ?
39120                 this._fill.project.key :
39121                 null;
39122         },
39123         enumerable: true,
39124         configurable: true
39125     });
39126     Object.defineProperty(Node.prototype, "rotation", {
39127         /**
39128          * Get rotation.
39129          *
39130          * @description Will not be set if SfM has not been run.
39131          *
39132          * @returns {Array<number>} Rotation vector in angle axis representation.
39133          */
39134         get: function () {
39135             return this._fill.c_rotation;
39136         },
39137         enumerable: true,
39138         configurable: true
39139     });
39140     Object.defineProperty(Node.prototype, "scale", {
39141         /**
39142          * Get scale.
39143          *
39144          * @description Will not be set if SfM has not been run.
39145          *
39146          * @returns {number} Scale of atomic reconstruction.
39147          */
39148         get: function () {
39149             return this._fill.atomic_scale;
39150         },
39151         enumerable: true,
39152         configurable: true
39153     });
39154     Object.defineProperty(Node.prototype, "sequenceKey", {
39155         /**
39156          * Get sequenceKey.
39157          *
39158          * @returns {string} Unique key of the sequence to which
39159          * the node belongs.
39160          */
39161         get: function () {
39162             return this._core.sequence_key;
39163         },
39164         enumerable: true,
39165         configurable: true
39166     });
39167     Object.defineProperty(Node.prototype, "sequenceEdges", {
39168         /**
39169          * Get sequenceEdges.
39170          *
39171          * @returns {IEdgeStatus} Value describing the status of the
39172          * sequence edges.
39173          */
39174         get: function () {
39175             return this._cache.sequenceEdges;
39176         },
39177         enumerable: true,
39178         configurable: true
39179     });
39180     Object.defineProperty(Node.prototype, "sequenceEdges$", {
39181         /**
39182          * Get sequenceEdges$.
39183          *
39184          * @description Internal observable, should not be used as an API.
39185          *
39186          * @returns {Observable<IEdgeStatus>} Observable emitting
39187          * values describing the status of the sequence edges.
39188          *
39189          * @ignore
39190          */
39191         get: function () {
39192             return this._cache.sequenceEdges$;
39193         },
39194         enumerable: true,
39195         configurable: true
39196     });
39197     Object.defineProperty(Node.prototype, "spatialEdges", {
39198         /**
39199          * Get spatialEdges.
39200          *
39201          * @returns {IEdgeStatus} Value describing the status of the
39202          * spatial edges.
39203          */
39204         get: function () {
39205             return this._cache.spatialEdges;
39206         },
39207         enumerable: true,
39208         configurable: true
39209     });
39210     Object.defineProperty(Node.prototype, "spatialEdges$", {
39211         /**
39212          * Get spatialEdges$.
39213          *
39214          * @description Internal observable, should not be used as an API.
39215          *
39216          * @returns {Observable<IEdgeStatus>} Observable emitting
39217          * values describing the status of the spatial edges.
39218          *
39219          * @ignore
39220          */
39221         get: function () {
39222             return this._cache.spatialEdges$;
39223         },
39224         enumerable: true,
39225         configurable: true
39226     });
39227     Object.defineProperty(Node.prototype, "userKey", {
39228         /**
39229          * Get userKey.
39230          *
39231          * @returns {string} Unique key of the user who uploaded
39232          * the image.
39233          */
39234         get: function () {
39235             return this._fill.user.key;
39236         },
39237         enumerable: true,
39238         configurable: true
39239     });
39240     Object.defineProperty(Node.prototype, "username", {
39241         /**
39242          * Get username.
39243          *
39244          * @returns {string} Username of the user who uploaded
39245          * the image.
39246          */
39247         get: function () {
39248             return this._fill.user.username;
39249         },
39250         enumerable: true,
39251         configurable: true
39252     });
39253     Object.defineProperty(Node.prototype, "width", {
39254         /**
39255          * Get width.
39256          *
39257          * @returns {number} Width of original image, not
39258          * adjusted for orientation.
39259          */
39260         get: function () {
39261             return this._fill.width;
39262         },
39263         enumerable: true,
39264         configurable: true
39265     });
39266     /**
39267      * Cache the image and mesh assets.
39268      *
39269      * @description The assets are always cached internally by the
39270      * library prior to setting a node as the current node.
39271      *
39272      * @returns {Observable<Node>} Observable emitting this node whenever the
39273      * load status has changed and when the mesh or image has been fully loaded.
39274      *
39275      * @ignore
39276      */
39277     Node.prototype.cacheAssets$ = function () {
39278         var _this = this;
39279         return this._cache.cacheAssets$(this.key, this.pano, this.merged).pipe(operators_1.map(function () {
39280             return _this;
39281         }));
39282     };
39283     /**
39284      * Cache the image asset.
39285      *
39286      * @description Use for caching a differently sized image than
39287      * the one currently held by the node.
39288      *
39289      * @returns {Observable<Node>} Observable emitting this node whenever the
39290      * load status has changed and when the mesh or image has been fully loaded.
39291      *
39292      * @ignore
39293      */
39294     Node.prototype.cacheImage$ = function (imageSize) {
39295         var _this = this;
39296         return this._cache.cacheImage$(this.key, imageSize).pipe(operators_1.map(function () {
39297             return _this;
39298         }));
39299     };
39300     /**
39301      * Cache the sequence edges.
39302      *
39303      * @description The sequence edges are cached asynchronously
39304      * internally by the library.
39305      *
39306      * @param {Array<IEdge>} edges - Sequence edges to cache.
39307      * @ignore
39308      */
39309     Node.prototype.cacheSequenceEdges = function (edges) {
39310         this._cache.cacheSequenceEdges(edges);
39311     };
39312     /**
39313      * Cache the spatial edges.
39314      *
39315      * @description The spatial edges are cached asynchronously
39316      * internally by the library.
39317      *
39318      * @param {Array<IEdge>} edges - Spatial edges to cache.
39319      * @ignore
39320      */
39321     Node.prototype.cacheSpatialEdges = function (edges) {
39322         this._cache.cacheSpatialEdges(edges);
39323     };
39324     /**
39325      * Dispose the node.
39326      *
39327      * @description Disposes all cached assets.
39328      * @ignore
39329      */
39330     Node.prototype.dispose = function () {
39331         if (this._cache != null) {
39332             this._cache.dispose();
39333             this._cache = null;
39334         }
39335         this._core = null;
39336         this._fill = null;
39337     };
39338     /**
39339      * Initialize the node cache.
39340      *
39341      * @description The node cache is initialized internally by
39342      * the library.
39343      *
39344      * @param {NodeCache} cache - The node cache to set as cache.
39345      * @ignore
39346      */
39347     Node.prototype.initializeCache = function (cache) {
39348         if (this._cache != null) {
39349             throw new Error("Node cache already initialized (" + this.key + ").");
39350         }
39351         this._cache = cache;
39352     };
39353     /**
39354      * Fill the node with all properties.
39355      *
39356      * @description The node is filled internally by
39357      * the library.
39358      *
39359      * @param {IFillNode} fill - The fill node struct.
39360      * @ignore
39361      */
39362     Node.prototype.makeFull = function (fill) {
39363         if (fill == null) {
39364             throw new Error("Fill can not be null.");
39365         }
39366         this._fill = fill;
39367     };
39368     /**
39369      * Reset the sequence edges.
39370      *
39371      * @ignore
39372      */
39373     Node.prototype.resetSequenceEdges = function () {
39374         this._cache.resetSequenceEdges();
39375     };
39376     /**
39377      * Reset the spatial edges.
39378      *
39379      * @ignore
39380      */
39381     Node.prototype.resetSpatialEdges = function () {
39382         this._cache.resetSpatialEdges();
39383     };
39384     /**
39385      * Clears the image and mesh assets, aborts
39386      * any outstanding requests and resets edges.
39387      *
39388      * @ignore
39389      */
39390     Node.prototype.uncache = function () {
39391         if (this._cache == null) {
39392             return;
39393         }
39394         this._cache.dispose();
39395         this._cache = null;
39396     };
39397     return Node;
39398 }());
39399 exports.Node = Node;
39400 exports.default = Node;
39401
39402 },{"rxjs/operators":224}],396:[function(require,module,exports){
39403 (function (Buffer){
39404 "use strict";
39405 Object.defineProperty(exports, "__esModule", { value: true });
39406 var rxjs_1 = require("rxjs");
39407 var operators_1 = require("rxjs/operators");
39408 var Graph_1 = require("../Graph");
39409 var Utils_1 = require("../Utils");
39410 /**
39411  * @class NodeCache
39412  *
39413  * @classdesc Represents the cached properties of a node.
39414  */
39415 var NodeCache = /** @class */ (function () {
39416     /**
39417      * Create a new node cache instance.
39418      */
39419     function NodeCache() {
39420         this._disposed = false;
39421         this._image = null;
39422         this._loadStatus = { loaded: 0, total: 0 };
39423         this._mesh = null;
39424         this._sequenceEdges = { cached: false, edges: [] };
39425         this._spatialEdges = { cached: false, edges: [] };
39426         this._imageChanged$ = new rxjs_1.Subject();
39427         this._image$ = this._imageChanged$.pipe(operators_1.startWith(null), operators_1.publishReplay(1), operators_1.refCount());
39428         this._iamgeSubscription = this._image$.subscribe();
39429         this._sequenceEdgesChanged$ = new rxjs_1.Subject();
39430         this._sequenceEdges$ = this._sequenceEdgesChanged$.pipe(operators_1.startWith(this._sequenceEdges), operators_1.publishReplay(1), operators_1.refCount());
39431         this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
39432         this._spatialEdgesChanged$ = new rxjs_1.Subject();
39433         this._spatialEdges$ = this._spatialEdgesChanged$.pipe(operators_1.startWith(this._spatialEdges), operators_1.publishReplay(1), operators_1.refCount());
39434         this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
39435         this._cachingAssets$ = null;
39436     }
39437     Object.defineProperty(NodeCache.prototype, "image", {
39438         /**
39439          * Get image.
39440          *
39441          * @description Will not be set when assets have not been cached
39442          * or when the object has been disposed.
39443          *
39444          * @returns {HTMLImageElement} Cached image element of the node.
39445          */
39446         get: function () {
39447             return this._image;
39448         },
39449         enumerable: true,
39450         configurable: true
39451     });
39452     Object.defineProperty(NodeCache.prototype, "image$", {
39453         /**
39454          * Get image$.
39455          *
39456          * @returns {Observable<HTMLImageElement>} Observable emitting
39457          * the cached image when it is updated.
39458          */
39459         get: function () {
39460             return this._image$;
39461         },
39462         enumerable: true,
39463         configurable: true
39464     });
39465     Object.defineProperty(NodeCache.prototype, "loadStatus", {
39466         /**
39467          * Get loadStatus.
39468          *
39469          * @returns {ILoadStatus} Value indicating the load status
39470          * of the mesh and image.
39471          */
39472         get: function () {
39473             return this._loadStatus;
39474         },
39475         enumerable: true,
39476         configurable: true
39477     });
39478     Object.defineProperty(NodeCache.prototype, "mesh", {
39479         /**
39480          * Get mesh.
39481          *
39482          * @description Will not be set when assets have not been cached
39483          * or when the object has been disposed.
39484          *
39485          * @returns {IMesh} SfM triangulated mesh of reconstructed
39486          * atomic 3D points.
39487          */
39488         get: function () {
39489             return this._mesh;
39490         },
39491         enumerable: true,
39492         configurable: true
39493     });
39494     Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
39495         /**
39496          * Get sequenceEdges.
39497          *
39498          * @returns {IEdgeStatus} Value describing the status of the
39499          * sequence edges.
39500          */
39501         get: function () {
39502             return this._sequenceEdges;
39503         },
39504         enumerable: true,
39505         configurable: true
39506     });
39507     Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
39508         /**
39509          * Get sequenceEdges$.
39510          *
39511          * @returns {Observable<IEdgeStatus>} Observable emitting
39512          * values describing the status of the sequence edges.
39513          */
39514         get: function () {
39515             return this._sequenceEdges$;
39516         },
39517         enumerable: true,
39518         configurable: true
39519     });
39520     Object.defineProperty(NodeCache.prototype, "spatialEdges", {
39521         /**
39522          * Get spatialEdges.
39523          *
39524          * @returns {IEdgeStatus} Value describing the status of the
39525          * spatial edges.
39526          */
39527         get: function () {
39528             return this._spatialEdges;
39529         },
39530         enumerable: true,
39531         configurable: true
39532     });
39533     Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
39534         /**
39535          * Get spatialEdges$.
39536          *
39537          * @returns {Observable<IEdgeStatus>} Observable emitting
39538          * values describing the status of the spatial edges.
39539          */
39540         get: function () {
39541             return this._spatialEdges$;
39542         },
39543         enumerable: true,
39544         configurable: true
39545     });
39546     /**
39547      * Cache the image and mesh assets.
39548      *
39549      * @param {string} key - Key of the node to cache.
39550      * @param {boolean} pano - Value indicating whether node is a panorama.
39551      * @param {boolean} merged - Value indicating whether node is merged.
39552      * @returns {Observable<NodeCache>} Observable emitting this node
39553      * cache whenever the load status has changed and when the mesh or image
39554      * has been fully loaded.
39555      */
39556     NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
39557         var _this = this;
39558         if (this._cachingAssets$ != null) {
39559             return this._cachingAssets$;
39560         }
39561         var imageSize = pano ?
39562             Utils_1.Settings.basePanoramaSize :
39563             Utils_1.Settings.baseImageSize;
39564         this._cachingAssets$ = rxjs_1.combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged)).pipe(operators_1.map(function (_a) {
39565             var imageStatus = _a[0], meshStatus = _a[1];
39566             _this._loadStatus.loaded = 0;
39567             _this._loadStatus.total = 0;
39568             if (meshStatus) {
39569                 _this._mesh = meshStatus.object;
39570                 _this._loadStatus.loaded += meshStatus.loaded.loaded;
39571                 _this._loadStatus.total += meshStatus.loaded.total;
39572             }
39573             if (imageStatus) {
39574                 _this._image = imageStatus.object;
39575                 _this._loadStatus.loaded += imageStatus.loaded.loaded;
39576                 _this._loadStatus.total += imageStatus.loaded.total;
39577             }
39578             return _this;
39579         }), operators_1.finalize(function () {
39580             _this._cachingAssets$ = null;
39581         }), operators_1.publishReplay(1), operators_1.refCount());
39582         this._cachingAssets$.pipe(operators_1.first(function (nodeCache) {
39583             return !!nodeCache._image;
39584         }))
39585             .subscribe(function (nodeCache) {
39586             _this._imageChanged$.next(_this._image);
39587         }, function (error) { });
39588         return this._cachingAssets$;
39589     };
39590     /**
39591      * Cache an image with a higher resolution than the current one.
39592      *
39593      * @param {string} key - Key of the node to cache.
39594      * @param {ImageSize} imageSize - The size to cache.
39595      * @returns {Observable<NodeCache>} Observable emitting a single item,
39596      * the node cache, when the image has been cached. If supplied image
39597      * size is not larger than the current image size the node cache is
39598      * returned immediately.
39599      */
39600     NodeCache.prototype.cacheImage$ = function (key, imageSize) {
39601         var _this = this;
39602         if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
39603             return rxjs_1.of(this);
39604         }
39605         var cacheImage$ = this._cacheImage$(key, imageSize).pipe(operators_1.first(function (status) {
39606             return status.object != null;
39607         }), operators_1.tap(function (status) {
39608             _this._disposeImage();
39609             _this._image = status.object;
39610         }), operators_1.map(function (imageStatus) {
39611             return _this;
39612         }), operators_1.publishReplay(1), operators_1.refCount());
39613         cacheImage$
39614             .subscribe(function (nodeCache) {
39615             _this._imageChanged$.next(_this._image);
39616         }, function (error) { });
39617         return cacheImage$;
39618     };
39619     /**
39620      * Cache the sequence edges.
39621      *
39622      * @param {Array<IEdge>} edges - Sequence edges to cache.
39623      */
39624     NodeCache.prototype.cacheSequenceEdges = function (edges) {
39625         this._sequenceEdges = { cached: true, edges: edges };
39626         this._sequenceEdgesChanged$.next(this._sequenceEdges);
39627     };
39628     /**
39629      * Cache the spatial edges.
39630      *
39631      * @param {Array<IEdge>} edges - Spatial edges to cache.
39632      */
39633     NodeCache.prototype.cacheSpatialEdges = function (edges) {
39634         this._spatialEdges = { cached: true, edges: edges };
39635         this._spatialEdgesChanged$.next(this._spatialEdges);
39636     };
39637     /**
39638      * Dispose the node cache.
39639      *
39640      * @description Disposes all cached assets and unsubscribes to
39641      * all streams.
39642      */
39643     NodeCache.prototype.dispose = function () {
39644         this._iamgeSubscription.unsubscribe();
39645         this._sequenceEdgesSubscription.unsubscribe();
39646         this._spatialEdgesSubscription.unsubscribe();
39647         this._disposeImage();
39648         this._mesh = null;
39649         this._loadStatus.loaded = 0;
39650         this._loadStatus.total = 0;
39651         this._sequenceEdges = { cached: false, edges: [] };
39652         this._spatialEdges = { cached: false, edges: [] };
39653         this._imageChanged$.next(null);
39654         this._sequenceEdgesChanged$.next(this._sequenceEdges);
39655         this._spatialEdgesChanged$.next(this._spatialEdges);
39656         this._disposed = true;
39657         if (this._imageRequest != null) {
39658             this._imageRequest.abort();
39659         }
39660         if (this._meshRequest != null) {
39661             this._meshRequest.abort();
39662         }
39663     };
39664     /**
39665      * Reset the sequence edges.
39666      */
39667     NodeCache.prototype.resetSequenceEdges = function () {
39668         this._sequenceEdges = { cached: false, edges: [] };
39669         this._sequenceEdgesChanged$.next(this._sequenceEdges);
39670     };
39671     /**
39672      * Reset the spatial edges.
39673      */
39674     NodeCache.prototype.resetSpatialEdges = function () {
39675         this._spatialEdges = { cached: false, edges: [] };
39676         this._spatialEdgesChanged$.next(this._spatialEdges);
39677     };
39678     /**
39679      * Cache the image.
39680      *
39681      * @param {string} key - Key of the node to cache.
39682      * @param {boolean} pano - Value indicating whether node is a panorama.
39683      * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
39684      * emitting a load status object every time the load status changes
39685      * and completes when the image is fully loaded.
39686      */
39687     NodeCache.prototype._cacheImage$ = function (key, imageSize) {
39688         var _this = this;
39689         return rxjs_1.Observable.create(function (subscriber) {
39690             var xmlHTTP = new XMLHttpRequest();
39691             xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize, Utils_1.Urls.origin), true);
39692             xmlHTTP.responseType = "arraybuffer";
39693             xmlHTTP.timeout = 15000;
39694             xmlHTTP.onload = function (pe) {
39695                 if (xmlHTTP.status !== 200) {
39696                     _this._imageRequest = null;
39697                     subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
39698                     return;
39699                 }
39700                 var image = new Image();
39701                 image.crossOrigin = "Anonymous";
39702                 image.onload = function (e) {
39703                     _this._imageRequest = null;
39704                     if (_this._disposed) {
39705                         window.URL.revokeObjectURL(image.src);
39706                         subscriber.error(new Error("Image load was aborted (" + key + ")"));
39707                         return;
39708                     }
39709                     subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
39710                     subscriber.complete();
39711                 };
39712                 image.onerror = function (error) {
39713                     _this._imageRequest = null;
39714                     subscriber.error(new Error("Failed to load image (" + key + ")"));
39715                 };
39716                 var blob = new Blob([xmlHTTP.response]);
39717                 image.src = window.URL.createObjectURL(blob);
39718             };
39719             xmlHTTP.onprogress = function (pe) {
39720                 if (_this._disposed) {
39721                     return;
39722                 }
39723                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
39724             };
39725             xmlHTTP.onerror = function (error) {
39726                 _this._imageRequest = null;
39727                 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
39728             };
39729             xmlHTTP.ontimeout = function (e) {
39730                 _this._imageRequest = null;
39731                 subscriber.error(new Error("Image request timed out (" + key + ")"));
39732             };
39733             xmlHTTP.onabort = function (event) {
39734                 _this._imageRequest = null;
39735                 subscriber.error(new Error("Image request was aborted (" + key + ")"));
39736             };
39737             _this._imageRequest = xmlHTTP;
39738             xmlHTTP.send(null);
39739         });
39740     };
39741     /**
39742      * Cache the mesh.
39743      *
39744      * @param {string} key - Key of the node to cache.
39745      * @param {boolean} merged - Value indicating whether node is merged.
39746      * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
39747      * a load status object every time the load status changes and completes
39748      * when the mesh is fully loaded.
39749      */
39750     NodeCache.prototype._cacheMesh$ = function (key, merged) {
39751         var _this = this;
39752         return rxjs_1.Observable.create(function (subscriber) {
39753             if (!merged) {
39754                 subscriber.next(_this._createEmptyMeshLoadStatus());
39755                 subscriber.complete();
39756                 return;
39757             }
39758             var xmlHTTP = new XMLHttpRequest();
39759             xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
39760             xmlHTTP.responseType = "arraybuffer";
39761             xmlHTTP.timeout = 15000;
39762             xmlHTTP.onload = function (pe) {
39763                 _this._meshRequest = null;
39764                 if (_this._disposed) {
39765                     return;
39766                 }
39767                 var mesh = xmlHTTP.status === 200 ?
39768                     Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
39769                     { faces: [], vertices: [] };
39770                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
39771                 subscriber.complete();
39772             };
39773             xmlHTTP.onprogress = function (pe) {
39774                 if (_this._disposed) {
39775                     return;
39776                 }
39777                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
39778             };
39779             xmlHTTP.onerror = function (e) {
39780                 _this._meshRequest = null;
39781                 console.error("Failed to cache mesh (" + key + ")");
39782                 subscriber.next(_this._createEmptyMeshLoadStatus());
39783                 subscriber.complete();
39784             };
39785             xmlHTTP.ontimeout = function (e) {
39786                 _this._meshRequest = null;
39787                 console.error("Mesh request timed out (" + key + ")");
39788                 subscriber.next(_this._createEmptyMeshLoadStatus());
39789                 subscriber.complete();
39790             };
39791             xmlHTTP.onabort = function (e) {
39792                 _this._meshRequest = null;
39793                 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
39794             };
39795             _this._meshRequest = xmlHTTP;
39796             xmlHTTP.send(null);
39797         });
39798     };
39799     /**
39800      * Create a load status object with an empty mesh.
39801      *
39802      * @returns {ILoadStatusObject<IMesh>} Load status object
39803      * with empty mesh.
39804      */
39805     NodeCache.prototype._createEmptyMeshLoadStatus = function () {
39806         return {
39807             loaded: { loaded: 0, total: 0 },
39808             object: { faces: [], vertices: [] },
39809         };
39810     };
39811     NodeCache.prototype._disposeImage = function () {
39812         if (this._image != null) {
39813             window.URL.revokeObjectURL(this._image.src);
39814         }
39815         this._image = null;
39816     };
39817     return NodeCache;
39818 }());
39819 exports.NodeCache = NodeCache;
39820 exports.default = NodeCache;
39821
39822 }).call(this,require("buffer").Buffer)
39823
39824 },{"../Graph":278,"../Utils":284,"buffer":7,"rxjs":26,"rxjs/operators":224}],397:[function(require,module,exports){
39825 "use strict";
39826 Object.defineProperty(exports, "__esModule", { value: true });
39827 /**
39828  * @class Sequence
39829  *
39830  * @classdesc Represents a sequence of ordered nodes.
39831  */
39832 var Sequence = /** @class */ (function () {
39833     /**
39834      * Create a new sequene instance.
39835      *
39836      * @param {ISequence} sequence - Raw sequence data.
39837      */
39838     function Sequence(sequence) {
39839         this._key = sequence.key;
39840         this._keys = sequence.keys;
39841     }
39842     Object.defineProperty(Sequence.prototype, "key", {
39843         /**
39844          * Get key.
39845          *
39846          * @returns {string} Unique sequence key.
39847          */
39848         get: function () {
39849             return this._key;
39850         },
39851         enumerable: true,
39852         configurable: true
39853     });
39854     Object.defineProperty(Sequence.prototype, "keys", {
39855         /**
39856          * Get keys.
39857          *
39858          * @returns {Array<string>} Array of ordered node keys in the sequence.
39859          */
39860         get: function () {
39861             return this._keys;
39862         },
39863         enumerable: true,
39864         configurable: true
39865     });
39866     /**
39867      * Dispose the sequence.
39868      *
39869      * @description Disposes all cached assets.
39870      */
39871     Sequence.prototype.dispose = function () {
39872         this._key = null;
39873         this._keys = null;
39874     };
39875     /**
39876      * Find the next node key in the sequence with respect to
39877      * the provided node key.
39878      *
39879      * @param {string} key - Reference node key.
39880      * @returns {string} Next key in sequence if it exists, null otherwise.
39881      */
39882     Sequence.prototype.findNextKey = function (key) {
39883         var i = this._keys.indexOf(key);
39884         if ((i + 1) >= this._keys.length || i === -1) {
39885             return null;
39886         }
39887         else {
39888             return this._keys[i + 1];
39889         }
39890     };
39891     /**
39892      * Find the previous node key in the sequence with respect to
39893      * the provided node key.
39894      *
39895      * @param {string} key - Reference node key.
39896      * @returns {string} Previous key in sequence if it exists, null otherwise.
39897      */
39898     Sequence.prototype.findPrevKey = function (key) {
39899         var i = this._keys.indexOf(key);
39900         if (i === 0 || i === -1) {
39901             return null;
39902         }
39903         else {
39904             return this._keys[i - 1];
39905         }
39906     };
39907     return Sequence;
39908 }());
39909 exports.Sequence = Sequence;
39910 exports.default = Sequence;
39911
39912 },{}],398:[function(require,module,exports){
39913 "use strict";
39914 Object.defineProperty(exports, "__esModule", { value: true });
39915 var THREE = require("three");
39916 var Edge_1 = require("../../Edge");
39917 var Error_1 = require("../../Error");
39918 var Geo_1 = require("../../Geo");
39919 /**
39920  * @class EdgeCalculator
39921  *
39922  * @classdesc Represents a class for calculating node edges.
39923  */
39924 var EdgeCalculator = /** @class */ (function () {
39925     /**
39926      * Create a new edge calculator instance.
39927      *
39928      * @param {EdgeCalculatorSettings} settings - Settings struct.
39929      * @param {EdgeCalculatorDirections} directions - Directions struct.
39930      * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
39931      */
39932     function EdgeCalculator(settings, directions, coefficients) {
39933         this._spatial = new Geo_1.Spatial();
39934         this._geoCoords = new Geo_1.GeoCoords();
39935         this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
39936         this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
39937         this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
39938     }
39939     /**
39940      * Returns the potential edges to destination nodes for a set
39941      * of nodes with respect to a source node.
39942      *
39943      * @param {Node} node - Source node.
39944      * @param {Array<Node>} nodes - Potential destination nodes.
39945      * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
39946      * be returned even if they do not meet the criteria for a potential edge.
39947      * @throws {ArgumentMapillaryError} If node is not full.
39948      */
39949     EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
39950         if (!node.full) {
39951             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
39952         }
39953         if (!node.merged) {
39954             return [];
39955         }
39956         var currentDirection = this._spatial.viewingDirection(node.rotation);
39957         var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
39958         var potentialEdges = [];
39959         for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
39960             var potential = potentialNodes_1[_i];
39961             if (!potential.merged ||
39962                 potential.key === node.key) {
39963                 continue;
39964             }
39965             var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
39966             var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
39967             var distance = motion.length();
39968             if (distance > this._settings.maxDistance &&
39969                 fallbackKeys.indexOf(potential.key) < 0) {
39970                 continue;
39971             }
39972             var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
39973             var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
39974             var direction = this._spatial.viewingDirection(potential.rotation);
39975             var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
39976             var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
39977             var verticalDirectionChange = verticalDirection - currentVerticalDirection;
39978             var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
39979             var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
39980             var sameSequence = potential.sequenceKey != null &&
39981                 node.sequenceKey != null &&
39982                 potential.sequenceKey === node.sequenceKey;
39983             var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
39984                 potential.mergeCC === node.mergeCC;
39985             var sameUser = potential.userKey === node.userKey;
39986             var potentialEdge = {
39987                 capturedAt: potential.capturedAt,
39988                 croppedPano: potential.pano && !potential.fullPano,
39989                 directionChange: directionChange,
39990                 distance: distance,
39991                 fullPano: potential.fullPano,
39992                 key: potential.key,
39993                 motionChange: motionChange,
39994                 rotation: rotation,
39995                 sameMergeCC: sameMergeCC,
39996                 sameSequence: sameSequence,
39997                 sameUser: sameUser,
39998                 sequenceKey: potential.sequenceKey,
39999                 verticalDirectionChange: verticalDirectionChange,
40000                 verticalMotion: verticalMotion,
40001                 worldMotionAzimuth: worldMotionAzimuth,
40002             };
40003             potentialEdges.push(potentialEdge);
40004         }
40005         return potentialEdges;
40006     };
40007     /**
40008      * Computes the sequence edges for a node.
40009      *
40010      * @param {Node} node - Source node.
40011      * @throws {ArgumentMapillaryError} If node is not full.
40012      */
40013     EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
40014         if (!node.full) {
40015             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40016         }
40017         if (node.sequenceKey !== sequence.key) {
40018             throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
40019         }
40020         var edges = [];
40021         var nextKey = sequence.findNextKey(node.key);
40022         if (nextKey != null) {
40023             edges.push({
40024                 data: {
40025                     direction: Edge_1.EdgeDirection.Next,
40026                     worldMotionAzimuth: Number.NaN,
40027                 },
40028                 from: node.key,
40029                 to: nextKey,
40030             });
40031         }
40032         var prevKey = sequence.findPrevKey(node.key);
40033         if (prevKey != null) {
40034             edges.push({
40035                 data: {
40036                     direction: Edge_1.EdgeDirection.Prev,
40037                     worldMotionAzimuth: Number.NaN,
40038                 },
40039                 from: node.key,
40040                 to: prevKey,
40041             });
40042         }
40043         return edges;
40044     };
40045     /**
40046      * Computes the similar edges for a node.
40047      *
40048      * @description Similar edges for perspective images and cropped panoramas
40049      * look roughly in the same direction and are positioned closed to the node.
40050      * Similar edges for full panoramas only target other full panoramas.
40051      *
40052      * @param {Node} node - Source node.
40053      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40054      * @throws {ArgumentMapillaryError} If node is not full.
40055      */
40056     EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
40057         var _this = this;
40058         if (!node.full) {
40059             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40060         }
40061         var nodeFullPano = node.fullPano;
40062         var sequenceGroups = {};
40063         for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
40064             var potentialEdge = potentialEdges_1[_i];
40065             if (potentialEdge.sequenceKey == null) {
40066                 continue;
40067             }
40068             if (potentialEdge.sameSequence) {
40069                 continue;
40070             }
40071             if (nodeFullPano) {
40072                 if (!potentialEdge.fullPano) {
40073                     continue;
40074                 }
40075             }
40076             else {
40077                 if (!potentialEdge.fullPano &&
40078                     Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
40079                     continue;
40080                 }
40081             }
40082             if (potentialEdge.distance > this._settings.similarMaxDistance) {
40083                 continue;
40084             }
40085             if (potentialEdge.sameUser &&
40086                 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
40087                     this._settings.similarMinTimeDifference) {
40088                 continue;
40089             }
40090             if (sequenceGroups[potentialEdge.sequenceKey] == null) {
40091                 sequenceGroups[potentialEdge.sequenceKey] = [];
40092             }
40093             sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
40094         }
40095         var similarEdges = [];
40096         var calculateScore = node.fullPano ?
40097             function (potentialEdge) {
40098                 return potentialEdge.distance;
40099             } :
40100             function (potentialEdge) {
40101                 return _this._coefficients.similarDistance * potentialEdge.distance +
40102                     _this._coefficients.similarRotation * potentialEdge.rotation;
40103             };
40104         for (var sequenceKey in sequenceGroups) {
40105             if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
40106                 continue;
40107             }
40108             var lowestScore = Number.MAX_VALUE;
40109             var similarEdge = null;
40110             for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
40111                 var potentialEdge = _b[_a];
40112                 var score = calculateScore(potentialEdge);
40113                 if (score < lowestScore) {
40114                     lowestScore = score;
40115                     similarEdge = potentialEdge;
40116                 }
40117             }
40118             if (similarEdge == null) {
40119                 continue;
40120             }
40121             similarEdges.push(similarEdge);
40122         }
40123         return similarEdges
40124             .map(function (potentialEdge) {
40125             return {
40126                 data: {
40127                     direction: Edge_1.EdgeDirection.Similar,
40128                     worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
40129                 },
40130                 from: node.key,
40131                 to: potentialEdge.key,
40132             };
40133         });
40134     };
40135     /**
40136      * Computes the step edges for a perspective node.
40137      *
40138      * @description Step edge targets can only be other perspective nodes.
40139      * Returns an empty array for cropped and full panoramas.
40140      *
40141      * @param {Node} node - Source node.
40142      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40143      * @param {string} prevKey - Key of previous node in sequence.
40144      * @param {string} prevKey - Key of next node in sequence.
40145      * @throws {ArgumentMapillaryError} If node is not full.
40146      */
40147     EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
40148         if (!node.full) {
40149             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40150         }
40151         var edges = [];
40152         if (node.pano) {
40153             return edges;
40154         }
40155         for (var k in this._directions.steps) {
40156             if (!this._directions.steps.hasOwnProperty(k)) {
40157                 continue;
40158             }
40159             var step = this._directions.steps[k];
40160             var lowestScore = Number.MAX_VALUE;
40161             var edge = null;
40162             var fallback = null;
40163             for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
40164                 var potential = potentialEdges_2[_i];
40165                 if (potential.croppedPano || potential.fullPano) {
40166                     continue;
40167                 }
40168                 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
40169                     continue;
40170                 }
40171                 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
40172                 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
40173                 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
40174                 if (Math.abs(drift) > this._settings.stepMaxDrift) {
40175                     continue;
40176                 }
40177                 var potentialKey = potential.key;
40178                 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
40179                     fallback = potential;
40180                 }
40181                 if (potential.distance > this._settings.stepMaxDistance) {
40182                     continue;
40183                 }
40184                 motionDifference = Math.sqrt(motionDifference * motionDifference +
40185                     potential.verticalMotion * potential.verticalMotion);
40186                 var score = this._coefficients.stepPreferredDistance *
40187                     Math.abs(potential.distance - this._settings.stepPreferredDistance) /
40188                     this._settings.stepMaxDistance +
40189                     this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
40190                     this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
40191                     this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
40192                     this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
40193                 if (score < lowestScore) {
40194                     lowestScore = score;
40195                     edge = potential;
40196                 }
40197             }
40198             edge = edge == null ? fallback : edge;
40199             if (edge != null) {
40200                 edges.push({
40201                     data: {
40202                         direction: step.direction,
40203                         worldMotionAzimuth: edge.worldMotionAzimuth,
40204                     },
40205                     from: node.key,
40206                     to: edge.key,
40207                 });
40208             }
40209         }
40210         return edges;
40211     };
40212     /**
40213      * Computes the turn edges for a perspective node.
40214      *
40215      * @description Turn edge targets can only be other perspective images.
40216      * Returns an empty array for cropped and full panoramas.
40217      *
40218      * @param {Node} node - Source node.
40219      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40220      * @throws {ArgumentMapillaryError} If node is not full.
40221      */
40222     EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
40223         if (!node.full) {
40224             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40225         }
40226         var edges = [];
40227         if (node.pano) {
40228             return edges;
40229         }
40230         for (var k in this._directions.turns) {
40231             if (!this._directions.turns.hasOwnProperty(k)) {
40232                 continue;
40233             }
40234             var turn = this._directions.turns[k];
40235             var lowestScore = Number.MAX_VALUE;
40236             var edge = null;
40237             for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
40238                 var potential = potentialEdges_3[_i];
40239                 if (potential.croppedPano || potential.fullPano) {
40240                     continue;
40241                 }
40242                 if (potential.distance > this._settings.turnMaxDistance) {
40243                     continue;
40244                 }
40245                 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
40246                     potential.distance < this._settings.turnMaxRigDistance &&
40247                     Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
40248                 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
40249                 var score = void 0;
40250                 if (rig &&
40251                     potential.directionChange * turn.directionChange > 0 &&
40252                     Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
40253                     score = -Math.PI / 2 + Math.abs(potential.directionChange);
40254                 }
40255                 else {
40256                     if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
40257                         continue;
40258                     }
40259                     var motionDifference = turn.motionChange ?
40260                         this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
40261                     motionDifference = Math.sqrt(motionDifference * motionDifference +
40262                         potential.verticalMotion * potential.verticalMotion);
40263                     score =
40264                         this._coefficients.turnDistance * potential.distance /
40265                             this._settings.turnMaxDistance +
40266                             this._coefficients.turnMotion * motionDifference / Math.PI +
40267                             this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
40268                             this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
40269                 }
40270                 if (score < lowestScore) {
40271                     lowestScore = score;
40272                     edge = potential;
40273                 }
40274             }
40275             if (edge != null) {
40276                 edges.push({
40277                     data: {
40278                         direction: turn.direction,
40279                         worldMotionAzimuth: edge.worldMotionAzimuth,
40280                     },
40281                     from: node.key,
40282                     to: edge.key,
40283                 });
40284             }
40285         }
40286         return edges;
40287     };
40288     /**
40289      * Computes the pano edges for a perspective node.
40290      *
40291      * @description Perspective to pano edge targets can only be
40292      * full pano nodes. Returns an empty array for cropped and full panoramas.
40293      *
40294      * @param {Node} node - Source node.
40295      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40296      * @throws {ArgumentMapillaryError} If node is not full.
40297      */
40298     EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
40299         if (!node.full) {
40300             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40301         }
40302         if (node.pano) {
40303             return [];
40304         }
40305         var lowestScore = Number.MAX_VALUE;
40306         var edge = null;
40307         for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
40308             var potential = potentialEdges_4[_i];
40309             if (!potential.fullPano) {
40310                 continue;
40311             }
40312             var score = this._coefficients.panoPreferredDistance *
40313                 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
40314                 this._settings.panoMaxDistance +
40315                 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
40316                 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
40317             if (score < lowestScore) {
40318                 lowestScore = score;
40319                 edge = potential;
40320             }
40321         }
40322         if (edge == null) {
40323             return [];
40324         }
40325         return [
40326             {
40327                 data: {
40328                     direction: Edge_1.EdgeDirection.Pano,
40329                     worldMotionAzimuth: edge.worldMotionAzimuth,
40330                 },
40331                 from: node.key,
40332                 to: edge.key,
40333             },
40334         ];
40335     };
40336     /**
40337      * Computes the full pano and step edges for a full pano node.
40338      *
40339      * @description Pano to pano edge targets can only be
40340      * full pano nodes. Pano to step edge targets can only be perspective
40341      * nodes.
40342      * Returns an empty array for cropped panoramas and perspective nodes.
40343      *
40344      * @param {Node} node - Source node.
40345      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40346      * @throws {ArgumentMapillaryError} If node is not full.
40347      */
40348     EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
40349         if (!node.full) {
40350             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40351         }
40352         if (!node.fullPano) {
40353             return [];
40354         }
40355         var panoEdges = [];
40356         var potentialPanos = [];
40357         var potentialSteps = [];
40358         for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
40359             var potential = potentialEdges_5[_i];
40360             if (potential.distance > this._settings.panoMaxDistance) {
40361                 continue;
40362             }
40363             if (potential.fullPano) {
40364                 if (potential.distance < this._settings.panoMinDistance) {
40365                     continue;
40366                 }
40367                 potentialPanos.push(potential);
40368             }
40369             else {
40370                 if (potential.croppedPano) {
40371                     continue;
40372                 }
40373                 for (var k in this._directions.panos) {
40374                     if (!this._directions.panos.hasOwnProperty(k)) {
40375                         continue;
40376                     }
40377                     var pano = this._directions.panos[k];
40378                     var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
40379                     var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
40380                     if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
40381                         continue;
40382                     }
40383                     potentialSteps.push([pano.direction, potential]);
40384                     // break if step direction found
40385                     break;
40386                 }
40387             }
40388         }
40389         var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
40390         var occupiedAngles = [];
40391         var stepAngles = [];
40392         for (var index = 0; index < this._settings.panoMaxItems; index++) {
40393             var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
40394             var lowestScore = Number.MAX_VALUE;
40395             var edge = null;
40396             for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
40397                 var potential = potentialPanos_1[_a];
40398                 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
40399                 if (Math.abs(motionDifference) > maxRotationDifference) {
40400                     continue;
40401                 }
40402                 var occupiedDifference = Number.MAX_VALUE;
40403                 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
40404                     var occupiedAngle = occupiedAngles_1[_b];
40405                     var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
40406                     if (difference < occupiedDifference) {
40407                         occupiedDifference = difference;
40408                     }
40409                 }
40410                 if (occupiedDifference <= maxRotationDifference) {
40411                     continue;
40412                 }
40413                 var score = this._coefficients.panoPreferredDistance *
40414                     Math.abs(potential.distance - this._settings.panoPreferredDistance) /
40415                     this._settings.panoMaxDistance +
40416                     this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
40417                     this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
40418                     this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
40419                 if (score < lowestScore) {
40420                     lowestScore = score;
40421                     edge = potential;
40422                 }
40423             }
40424             if (edge != null) {
40425                 occupiedAngles.push(edge.motionChange);
40426                 panoEdges.push({
40427                     data: {
40428                         direction: Edge_1.EdgeDirection.Pano,
40429                         worldMotionAzimuth: edge.worldMotionAzimuth,
40430                     },
40431                     from: node.key,
40432                     to: edge.key,
40433                 });
40434             }
40435             else {
40436                 stepAngles.push(rotation);
40437             }
40438         }
40439         var occupiedStepAngles = {};
40440         occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
40441         occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
40442         occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
40443         occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
40444         occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
40445         for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
40446             var stepAngle = stepAngles_1[_c];
40447             var occupations = [];
40448             for (var k in this._directions.panos) {
40449                 if (!this._directions.panos.hasOwnProperty(k)) {
40450                     continue;
40451                 }
40452                 var pano = this._directions.panos[k];
40453                 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
40454                     .concat(occupiedStepAngles[pano.direction])
40455                     .concat(occupiedStepAngles[pano.prev])
40456                     .concat(occupiedStepAngles[pano.next]);
40457                 var lowestScore = Number.MAX_VALUE;
40458                 var edge = null;
40459                 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
40460                     var potential = potentialSteps_1[_d];
40461                     if (potential[0] !== pano.direction) {
40462                         continue;
40463                     }
40464                     var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
40465                     if (Math.abs(motionChange) > maxRotationDifference) {
40466                         continue;
40467                     }
40468                     var minOccupiedDifference = Number.MAX_VALUE;
40469                     for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
40470                         var occupiedAngle = allOccupiedAngles_1[_e];
40471                         var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
40472                         if (occupiedDifference < minOccupiedDifference) {
40473                             minOccupiedDifference = occupiedDifference;
40474                         }
40475                     }
40476                     if (minOccupiedDifference <= maxRotationDifference) {
40477                         continue;
40478                     }
40479                     var score = this._coefficients.panoPreferredDistance *
40480                         Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
40481                         this._settings.panoMaxDistance +
40482                         this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
40483                         this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
40484                     if (score < lowestScore) {
40485                         lowestScore = score;
40486                         edge = potential;
40487                     }
40488                 }
40489                 if (edge != null) {
40490                     occupations.push(edge);
40491                     panoEdges.push({
40492                         data: {
40493                             direction: edge[0],
40494                             worldMotionAzimuth: edge[1].worldMotionAzimuth,
40495                         },
40496                         from: node.key,
40497                         to: edge[1].key,
40498                     });
40499                 }
40500             }
40501             for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
40502                 var occupation = occupations_1[_f];
40503                 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
40504             }
40505         }
40506         return panoEdges;
40507     };
40508     return EdgeCalculator;
40509 }());
40510 exports.EdgeCalculator = EdgeCalculator;
40511 exports.default = EdgeCalculator;
40512
40513 },{"../../Edge":275,"../../Error":276,"../../Geo":277,"three":225}],399:[function(require,module,exports){
40514 "use strict";
40515 Object.defineProperty(exports, "__esModule", { value: true });
40516 var EdgeCalculatorCoefficients = /** @class */ (function () {
40517     function EdgeCalculatorCoefficients() {
40518         this.panoPreferredDistance = 2;
40519         this.panoMotion = 2;
40520         this.panoSequencePenalty = 1;
40521         this.panoMergeCCPenalty = 4;
40522         this.stepPreferredDistance = 4;
40523         this.stepMotion = 3;
40524         this.stepRotation = 4;
40525         this.stepSequencePenalty = 2;
40526         this.stepMergeCCPenalty = 6;
40527         this.similarDistance = 2;
40528         this.similarRotation = 3;
40529         this.turnDistance = 4;
40530         this.turnMotion = 2;
40531         this.turnSequencePenalty = 1;
40532         this.turnMergeCCPenalty = 4;
40533     }
40534     return EdgeCalculatorCoefficients;
40535 }());
40536 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
40537 exports.default = EdgeCalculatorCoefficients;
40538
40539 },{}],400:[function(require,module,exports){
40540 "use strict";
40541 Object.defineProperty(exports, "__esModule", { value: true });
40542 var Edge_1 = require("../../Edge");
40543 var EdgeCalculatorDirections = /** @class */ (function () {
40544     function EdgeCalculatorDirections() {
40545         this.steps = {};
40546         this.turns = {};
40547         this.panos = {};
40548         this.steps[Edge_1.EdgeDirection.StepForward] = {
40549             direction: Edge_1.EdgeDirection.StepForward,
40550             motionChange: 0,
40551             useFallback: true,
40552         };
40553         this.steps[Edge_1.EdgeDirection.StepBackward] = {
40554             direction: Edge_1.EdgeDirection.StepBackward,
40555             motionChange: Math.PI,
40556             useFallback: true,
40557         };
40558         this.steps[Edge_1.EdgeDirection.StepLeft] = {
40559             direction: Edge_1.EdgeDirection.StepLeft,
40560             motionChange: Math.PI / 2,
40561             useFallback: false,
40562         };
40563         this.steps[Edge_1.EdgeDirection.StepRight] = {
40564             direction: Edge_1.EdgeDirection.StepRight,
40565             motionChange: -Math.PI / 2,
40566             useFallback: false,
40567         };
40568         this.turns[Edge_1.EdgeDirection.TurnLeft] = {
40569             direction: Edge_1.EdgeDirection.TurnLeft,
40570             directionChange: Math.PI / 2,
40571             motionChange: Math.PI / 4,
40572         };
40573         this.turns[Edge_1.EdgeDirection.TurnRight] = {
40574             direction: Edge_1.EdgeDirection.TurnRight,
40575             directionChange: -Math.PI / 2,
40576             motionChange: -Math.PI / 4,
40577         };
40578         this.turns[Edge_1.EdgeDirection.TurnU] = {
40579             direction: Edge_1.EdgeDirection.TurnU,
40580             directionChange: Math.PI,
40581             motionChange: null,
40582         };
40583         this.panos[Edge_1.EdgeDirection.StepForward] = {
40584             direction: Edge_1.EdgeDirection.StepForward,
40585             directionChange: 0,
40586             next: Edge_1.EdgeDirection.StepLeft,
40587             prev: Edge_1.EdgeDirection.StepRight,
40588         };
40589         this.panos[Edge_1.EdgeDirection.StepBackward] = {
40590             direction: Edge_1.EdgeDirection.StepBackward,
40591             directionChange: Math.PI,
40592             next: Edge_1.EdgeDirection.StepRight,
40593             prev: Edge_1.EdgeDirection.StepLeft,
40594         };
40595         this.panos[Edge_1.EdgeDirection.StepLeft] = {
40596             direction: Edge_1.EdgeDirection.StepLeft,
40597             directionChange: Math.PI / 2,
40598             next: Edge_1.EdgeDirection.StepBackward,
40599             prev: Edge_1.EdgeDirection.StepForward,
40600         };
40601         this.panos[Edge_1.EdgeDirection.StepRight] = {
40602             direction: Edge_1.EdgeDirection.StepRight,
40603             directionChange: -Math.PI / 2,
40604             next: Edge_1.EdgeDirection.StepForward,
40605             prev: Edge_1.EdgeDirection.StepBackward,
40606         };
40607     }
40608     return EdgeCalculatorDirections;
40609 }());
40610 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
40611
40612 },{"../../Edge":275}],401:[function(require,module,exports){
40613 "use strict";
40614 Object.defineProperty(exports, "__esModule", { value: true });
40615 var EdgeCalculatorSettings = /** @class */ (function () {
40616     function EdgeCalculatorSettings() {
40617         this.panoMinDistance = 0.1;
40618         this.panoMaxDistance = 20;
40619         this.panoPreferredDistance = 5;
40620         this.panoMaxItems = 4;
40621         this.panoMaxStepTurnChange = Math.PI / 8;
40622         this.rotationMaxDistance = this.turnMaxRigDistance;
40623         this.rotationMaxDirectionChange = Math.PI / 6;
40624         this.rotationMaxVerticalDirectionChange = Math.PI / 8;
40625         this.similarMaxDirectionChange = Math.PI / 8;
40626         this.similarMaxDistance = 12;
40627         this.similarMinTimeDifference = 12 * 3600 * 1000;
40628         this.stepMaxDistance = 20;
40629         this.stepMaxDirectionChange = Math.PI / 6;
40630         this.stepMaxDrift = Math.PI / 6;
40631         this.stepPreferredDistance = 4;
40632         this.turnMaxDistance = 15;
40633         this.turnMaxDirectionChange = 2 * Math.PI / 9;
40634         this.turnMaxRigDistance = 0.65;
40635         this.turnMinRigDirectionChange = Math.PI / 6;
40636     }
40637     Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
40638         get: function () {
40639             return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
40640         },
40641         enumerable: true,
40642         configurable: true
40643     });
40644     return EdgeCalculatorSettings;
40645 }());
40646 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
40647 exports.default = EdgeCalculatorSettings;
40648
40649 },{}],402:[function(require,module,exports){
40650 "use strict";
40651 Object.defineProperty(exports, "__esModule", { value: true });
40652 /**
40653  * Enumeration for edge directions
40654  * @enum {number}
40655  * @readonly
40656  * @description Directions for edges in node graph describing
40657  * sequence, spatial and node type relations between nodes.
40658  */
40659 var EdgeDirection;
40660 (function (EdgeDirection) {
40661     /**
40662      * Next node in the sequence.
40663      */
40664     EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
40665     /**
40666      * Previous node in the sequence.
40667      */
40668     EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
40669     /**
40670      * Step to the left keeping viewing direction.
40671      */
40672     EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
40673     /**
40674      * Step to the right keeping viewing direction.
40675      */
40676     EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
40677     /**
40678      * Step forward keeping viewing direction.
40679      */
40680     EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
40681     /**
40682      * Step backward keeping viewing direction.
40683      */
40684     EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
40685     /**
40686      * Turn 90 degrees counter clockwise.
40687      */
40688     EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
40689     /**
40690      * Turn 90 degrees clockwise.
40691      */
40692     EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
40693     /**
40694      * Turn 180 degrees.
40695      */
40696     EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
40697     /**
40698      * Panorama in general direction.
40699      */
40700     EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
40701     /**
40702      * Looking in roughly the same direction at rougly the same position.
40703      */
40704     EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
40705 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
40706
40707 },{}],403:[function(require,module,exports){
40708 "use strict";
40709 Object.defineProperty(exports, "__esModule", { value: true });
40710 var rxjs_1 = require("rxjs");
40711 var operators_1 = require("rxjs/operators");
40712 var vd = require("virtual-dom");
40713 var rxjs_2 = require("rxjs");
40714 var Render_1 = require("../Render");
40715 var DOMRenderer = /** @class */ (function () {
40716     function DOMRenderer(element, renderService, currentFrame$) {
40717         this._adaptiveOperation$ = new rxjs_2.Subject();
40718         this._render$ = new rxjs_2.Subject();
40719         this._renderAdaptive$ = new rxjs_2.Subject();
40720         this._renderService = renderService;
40721         this._currentFrame$ = currentFrame$;
40722         var rootNode = vd.create(vd.h("div.domRenderer", []));
40723         element.appendChild(rootNode);
40724         this._offset$ = this._adaptiveOperation$.pipe(operators_1.scan(function (adaptive, operation) {
40725             return operation(adaptive);
40726         }, {
40727             elementHeight: element.offsetHeight,
40728             elementWidth: element.offsetWidth,
40729             imageAspect: 0,
40730             renderMode: Render_1.RenderMode.Fill,
40731         }), operators_1.filter(function (adaptive) {
40732             return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
40733         }), operators_1.map(function (adaptive) {
40734             var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
40735             var ratio = adaptive.imageAspect / elementAspect;
40736             var verticalOffset = 0;
40737             var horizontalOffset = 0;
40738             if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
40739                 if (adaptive.imageAspect > elementAspect) {
40740                     verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
40741                 }
40742                 else {
40743                     horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
40744                 }
40745             }
40746             else {
40747                 if (adaptive.imageAspect > elementAspect) {
40748                     horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
40749                 }
40750                 else {
40751                     verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
40752                 }
40753             }
40754             return {
40755                 bottom: verticalOffset,
40756                 left: horizontalOffset,
40757                 right: horizontalOffset,
40758                 top: verticalOffset,
40759             };
40760         }));
40761         this._currentFrame$.pipe(operators_1.filter(function (frame) {
40762             return frame.state.currentNode != null;
40763         }), operators_1.distinctUntilChanged(function (k1, k2) {
40764             return k1 === k2;
40765         }, function (frame) {
40766             return frame.state.currentNode.key;
40767         }), operators_1.map(function (frame) {
40768             return frame.state.currentTransform.basicAspect;
40769         }), operators_1.map(function (aspect) {
40770             return function (adaptive) {
40771                 adaptive.imageAspect = aspect;
40772                 return adaptive;
40773             };
40774         }))
40775             .subscribe(this._adaptiveOperation$);
40776         rxjs_1.combineLatest(this._renderAdaptive$.pipe(operators_1.scan(function (vNodeHashes, vNodeHash) {
40777             if (vNodeHash.vnode == null) {
40778                 delete vNodeHashes[vNodeHash.name];
40779             }
40780             else {
40781                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
40782             }
40783             return vNodeHashes;
40784         }, {})), this._offset$).pipe(operators_1.map(function (vo) {
40785             var vNodes = [];
40786             var hashes = vo[0];
40787             for (var name_1 in hashes) {
40788                 if (!hashes.hasOwnProperty(name_1)) {
40789                     continue;
40790                 }
40791                 vNodes.push(hashes[name_1]);
40792             }
40793             var offset = vo[1];
40794             var properties = {
40795                 style: {
40796                     bottom: offset.bottom + "px",
40797                     left: offset.left + "px",
40798                     "pointer-events": "none",
40799                     position: "absolute",
40800                     right: offset.right + "px",
40801                     top: offset.top + "px",
40802                 },
40803             };
40804             return {
40805                 name: "adaptiveDomRenderer",
40806                 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
40807             };
40808         }))
40809             .subscribe(this._render$);
40810         this._vNode$ = this._render$.pipe(operators_1.scan(function (vNodeHashes, vNodeHash) {
40811             if (vNodeHash.vnode == null) {
40812                 delete vNodeHashes[vNodeHash.name];
40813             }
40814             else {
40815                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
40816             }
40817             return vNodeHashes;
40818         }, {}), operators_1.map(function (hashes) {
40819             var vNodes = [];
40820             for (var name_2 in hashes) {
40821                 if (!hashes.hasOwnProperty(name_2)) {
40822                     continue;
40823                 }
40824                 vNodes.push(hashes[name_2]);
40825             }
40826             return vd.h("div.domRenderer", vNodes);
40827         }));
40828         this._vPatch$ = this._vNode$.pipe(operators_1.scan(function (nodePatch, vNode) {
40829             nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
40830             nodePatch.vnode = vNode;
40831             return nodePatch;
40832         }, { vnode: vd.h("div.domRenderer", []), vpatch: null }), operators_1.pluck("vpatch"));
40833         this._element$ = this._vPatch$.pipe(operators_1.scan(function (oldElement, vPatch) {
40834             return vd.patch(oldElement, vPatch);
40835         }, rootNode), operators_1.publishReplay(1), operators_1.refCount());
40836         this._element$.subscribe(function () { });
40837         this._renderService.size$.pipe(operators_1.map(function (size) {
40838             return function (adaptive) {
40839                 adaptive.elementWidth = size.width;
40840                 adaptive.elementHeight = size.height;
40841                 return adaptive;
40842             };
40843         }))
40844             .subscribe(this._adaptiveOperation$);
40845         this._renderService.renderMode$.pipe(operators_1.map(function (renderMode) {
40846             return function (adaptive) {
40847                 adaptive.renderMode = renderMode;
40848                 return adaptive;
40849             };
40850         }))
40851             .subscribe(this._adaptiveOperation$);
40852     }
40853     Object.defineProperty(DOMRenderer.prototype, "element$", {
40854         get: function () {
40855             return this._element$;
40856         },
40857         enumerable: true,
40858         configurable: true
40859     });
40860     Object.defineProperty(DOMRenderer.prototype, "render$", {
40861         get: function () {
40862             return this._render$;
40863         },
40864         enumerable: true,
40865         configurable: true
40866     });
40867     Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
40868         get: function () {
40869             return this._renderAdaptive$;
40870         },
40871         enumerable: true,
40872         configurable: true
40873     });
40874     DOMRenderer.prototype.clear = function (name) {
40875         this._renderAdaptive$.next({ name: name, vnode: null });
40876         this._render$.next({ name: name, vnode: null });
40877     };
40878     return DOMRenderer;
40879 }());
40880 exports.DOMRenderer = DOMRenderer;
40881 exports.default = DOMRenderer;
40882
40883
40884 },{"../Render":280,"rxjs":26,"rxjs/operators":224,"virtual-dom":230}],404:[function(require,module,exports){
40885 "use strict";
40886 Object.defineProperty(exports, "__esModule", { value: true });
40887 var GLRenderStage;
40888 (function (GLRenderStage) {
40889     GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
40890     GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
40891 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
40892 exports.default = GLRenderStage;
40893
40894 },{}],405:[function(require,module,exports){
40895 "use strict";
40896 Object.defineProperty(exports, "__esModule", { value: true });
40897 var rxjs_1 = require("rxjs");
40898 var operators_1 = require("rxjs/operators");
40899 var THREE = require("three");
40900 var Render_1 = require("../Render");
40901 var Utils_1 = require("../Utils");
40902 var GLRenderer = /** @class */ (function () {
40903     function GLRenderer(canvasContainer, renderService, dom) {
40904         var _this = this;
40905         this._renderFrame$ = new rxjs_1.Subject();
40906         this._renderCameraOperation$ = new rxjs_1.Subject();
40907         this._render$ = new rxjs_1.Subject();
40908         this._clear$ = new rxjs_1.Subject();
40909         this._renderOperation$ = new rxjs_1.Subject();
40910         this._rendererOperation$ = new rxjs_1.Subject();
40911         this._eraserOperation$ = new rxjs_1.Subject();
40912         this._renderService = renderService;
40913         this._dom = !!dom ? dom : new Utils_1.DOM();
40914         this._renderer$ = this._rendererOperation$.pipe(operators_1.scan(function (renderer, operation) {
40915             return operation(renderer);
40916         }, { needsRender: false, renderer: null }), operators_1.filter(function (renderer) {
40917             return !!renderer.renderer;
40918         }));
40919         this._renderCollection$ = this._renderOperation$.pipe(operators_1.scan(function (hashes, operation) {
40920             return operation(hashes);
40921         }, {}), operators_1.share());
40922         this._renderCamera$ = this._renderCameraOperation$.pipe(operators_1.scan(function (rc, operation) {
40923             return operation(rc);
40924         }, { frameId: -1, needsRender: false, perspective: null }));
40925         this._eraser$ = this._eraserOperation$.pipe(operators_1.startWith(function (eraser) {
40926             return eraser;
40927         }), operators_1.scan(function (eraser, operation) {
40928             return operation(eraser);
40929         }, { needsRender: false }));
40930         rxjs_1.combineLatest(this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$).pipe(operators_1.map(function (_a) {
40931             var renderer = _a[0], hashes = _a[1], rc = _a[2], eraser = _a[3];
40932             var renders = Object.keys(hashes)
40933                 .map(function (key) {
40934                 return hashes[key];
40935             });
40936             return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
40937         }), operators_1.filter(function (co) {
40938             var needsRender = co.renderer.needsRender ||
40939                 co.camera.needsRender ||
40940                 co.eraser.needsRender;
40941             var frameId = co.camera.frameId;
40942             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
40943                 var render = _a[_i];
40944                 if (render.frameId !== frameId) {
40945                     return false;
40946                 }
40947                 needsRender = needsRender || render.needsRender;
40948             }
40949             return needsRender;
40950         }), operators_1.distinctUntilChanged(function (n1, n2) {
40951             return n1 === n2;
40952         }, function (co) {
40953             return co.eraser.needsRender ? -1 : co.camera.frameId;
40954         }))
40955             .subscribe(function (co) {
40956             co.renderer.needsRender = false;
40957             co.camera.needsRender = false;
40958             co.eraser.needsRender = false;
40959             var perspectiveCamera = co.camera.perspective;
40960             var backgroundRenders = [];
40961             var foregroundRenders = [];
40962             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
40963                 var render = _a[_i];
40964                 if (render.stage === Render_1.GLRenderStage.Background) {
40965                     backgroundRenders.push(render.render);
40966                 }
40967                 else if (render.stage === Render_1.GLRenderStage.Foreground) {
40968                     foregroundRenders.push(render.render);
40969                 }
40970             }
40971             var renderer = co.renderer.renderer;
40972             renderer.clear();
40973             for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
40974                 var render = backgroundRenders_1[_b];
40975                 render(perspectiveCamera, renderer);
40976             }
40977             renderer.clearDepth();
40978             for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
40979                 var render = foregroundRenders_1[_c];
40980                 render(perspectiveCamera, renderer);
40981             }
40982         });
40983         this._renderFrame$.pipe(operators_1.map(function (rc) {
40984             return function (irc) {
40985                 irc.frameId = rc.frameId;
40986                 irc.perspective = rc.perspective;
40987                 if (rc.changed === true) {
40988                     irc.needsRender = true;
40989                 }
40990                 return irc;
40991             };
40992         }))
40993             .subscribe(this._renderCameraOperation$);
40994         this._renderFrameSubscribe();
40995         var renderHash$ = this._render$.pipe(operators_1.map(function (hash) {
40996             return function (hashes) {
40997                 hashes[hash.name] = hash.render;
40998                 return hashes;
40999             };
41000         }));
41001         var clearHash$ = this._clear$.pipe(operators_1.map(function (name) {
41002             return function (hashes) {
41003                 delete hashes[name];
41004                 return hashes;
41005             };
41006         }));
41007         rxjs_1.merge(renderHash$, clearHash$)
41008             .subscribe(this._renderOperation$);
41009         this._webGLRenderer$ = this._render$.pipe(operators_1.first(), operators_1.map(function (hash) {
41010             var canvas = _this._dom.createElement("canvas", "mapillary-js-canvas");
41011             canvas.style.position = "absolute";
41012             canvas.setAttribute("tabindex", "0");
41013             canvasContainer.appendChild(canvas);
41014             var element = renderService.element;
41015             var webGLRenderer = new THREE.WebGLRenderer({ canvas: canvas });
41016             webGLRenderer.setPixelRatio(window.devicePixelRatio);
41017             webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
41018             webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
41019             webGLRenderer.autoClear = false;
41020             return webGLRenderer;
41021         }), operators_1.publishReplay(1), operators_1.refCount());
41022         this._webGLRenderer$.subscribe(function () { });
41023         var createRenderer$ = this._webGLRenderer$.pipe(operators_1.first(), operators_1.map(function (webGLRenderer) {
41024             return function (renderer) {
41025                 renderer.needsRender = true;
41026                 renderer.renderer = webGLRenderer;
41027                 return renderer;
41028             };
41029         }));
41030         var resizeRenderer$ = this._renderService.size$.pipe(operators_1.map(function (size) {
41031             return function (renderer) {
41032                 if (renderer.renderer == null) {
41033                     return renderer;
41034                 }
41035                 renderer.renderer.setSize(size.width, size.height);
41036                 renderer.needsRender = true;
41037                 return renderer;
41038             };
41039         }));
41040         var clearRenderer$ = this._clear$.pipe(operators_1.map(function (name) {
41041             return function (renderer) {
41042                 if (renderer.renderer == null) {
41043                     return renderer;
41044                 }
41045                 renderer.needsRender = true;
41046                 return renderer;
41047             };
41048         }));
41049         rxjs_1.merge(createRenderer$, resizeRenderer$, clearRenderer$)
41050             .subscribe(this._rendererOperation$);
41051         var renderCollectionEmpty$ = this._renderCollection$.pipe(operators_1.filter(function (hashes) {
41052             return Object.keys(hashes).length === 0;
41053         }), operators_1.share());
41054         renderCollectionEmpty$
41055             .subscribe(function (hashes) {
41056             if (_this._renderFrameSubscription == null) {
41057                 return;
41058             }
41059             _this._renderFrameSubscription.unsubscribe();
41060             _this._renderFrameSubscription = null;
41061             _this._renderFrameSubscribe();
41062         });
41063         renderCollectionEmpty$.pipe(operators_1.map(function (hashes) {
41064             return function (eraser) {
41065                 eraser.needsRender = true;
41066                 return eraser;
41067             };
41068         }))
41069             .subscribe(this._eraserOperation$);
41070     }
41071     Object.defineProperty(GLRenderer.prototype, "render$", {
41072         get: function () {
41073             return this._render$;
41074         },
41075         enumerable: true,
41076         configurable: true
41077     });
41078     Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
41079         get: function () {
41080             return this._webGLRenderer$;
41081         },
41082         enumerable: true,
41083         configurable: true
41084     });
41085     GLRenderer.prototype.clear = function (name) {
41086         this._clear$.next(name);
41087     };
41088     GLRenderer.prototype._renderFrameSubscribe = function () {
41089         var _this = this;
41090         this._render$.pipe(operators_1.first(), operators_1.map(function (renderHash) {
41091             return function (irc) {
41092                 irc.needsRender = true;
41093                 return irc;
41094             };
41095         }))
41096             .subscribe(function (operation) {
41097             _this._renderCameraOperation$.next(operation);
41098         });
41099         this._renderFrameSubscription = this._render$.pipe(operators_1.first(), operators_1.mergeMap(function (hash) {
41100             return _this._renderService.renderCameraFrame$;
41101         }))
41102             .subscribe(this._renderFrame$);
41103     };
41104     return GLRenderer;
41105 }());
41106 exports.GLRenderer = GLRenderer;
41107 exports.default = GLRenderer;
41108
41109
41110 },{"../Render":280,"../Utils":284,"rxjs":26,"rxjs/operators":224,"three":225}],406:[function(require,module,exports){
41111 "use strict";
41112 Object.defineProperty(exports, "__esModule", { value: true });
41113 var THREE = require("three");
41114 var Geo_1 = require("../Geo");
41115 var Render_1 = require("../Render");
41116 var State_1 = require("../State");
41117 var RenderCamera = /** @class */ (function () {
41118     function RenderCamera(elementWidth, elementHeight, renderMode) {
41119         this._spatial = new Geo_1.Spatial();
41120         this._viewportCoords = new Geo_1.ViewportCoords();
41121         this._initialFov = 50;
41122         this._alpha = -1;
41123         this._renderMode = renderMode;
41124         this._zoom = 0;
41125         this._frameId = -1;
41126         this._changed = false;
41127         this._changedForFrame = -1;
41128         this._currentNodeId = null;
41129         this._previousNodeId = null;
41130         this._currentPano = false;
41131         this._previousPano = false;
41132         this._state = null;
41133         this._currentProjectedPoints = [];
41134         this._previousProjectedPoints = [];
41135         this._currentFov = this._initialFov;
41136         this._previousFov = this._initialFov;
41137         this._camera = new Geo_1.Camera();
41138         this._perspective = new THREE.PerspectiveCamera(this._initialFov, this._computeAspect(elementWidth, elementHeight), 0.16, 10000);
41139         this._perspective.matrixAutoUpdate = false;
41140         this._rotation = { phi: 0, theta: 0 };
41141     }
41142     Object.defineProperty(RenderCamera.prototype, "alpha", {
41143         get: function () {
41144             return this._alpha;
41145         },
41146         enumerable: true,
41147         configurable: true
41148     });
41149     Object.defineProperty(RenderCamera.prototype, "camera", {
41150         get: function () {
41151             return this._camera;
41152         },
41153         enumerable: true,
41154         configurable: true
41155     });
41156     Object.defineProperty(RenderCamera.prototype, "changed", {
41157         get: function () {
41158             return this._frameId === this._changedForFrame;
41159         },
41160         enumerable: true,
41161         configurable: true
41162     });
41163     Object.defineProperty(RenderCamera.prototype, "frameId", {
41164         get: function () {
41165             return this._frameId;
41166         },
41167         enumerable: true,
41168         configurable: true
41169     });
41170     Object.defineProperty(RenderCamera.prototype, "perspective", {
41171         get: function () {
41172             return this._perspective;
41173         },
41174         enumerable: true,
41175         configurable: true
41176     });
41177     Object.defineProperty(RenderCamera.prototype, "renderMode", {
41178         get: function () {
41179             return this._renderMode;
41180         },
41181         enumerable: true,
41182         configurable: true
41183     });
41184     Object.defineProperty(RenderCamera.prototype, "rotation", {
41185         get: function () {
41186             return this._rotation;
41187         },
41188         enumerable: true,
41189         configurable: true
41190     });
41191     Object.defineProperty(RenderCamera.prototype, "zoom", {
41192         get: function () {
41193             return this._zoom;
41194         },
41195         enumerable: true,
41196         configurable: true
41197     });
41198     RenderCamera.prototype.setFrame = function (frame) {
41199         var state = frame.state;
41200         if (state.state !== this._state) {
41201             this._state = state.state;
41202             this._changed = true;
41203         }
41204         var currentNodeId = state.currentNode.key;
41205         var previousNodeId = !!state.previousNode ? state.previousNode.key : null;
41206         if (currentNodeId !== this._currentNodeId) {
41207             this._currentNodeId = currentNodeId;
41208             this._currentPano = !!state.currentTransform.gpano;
41209             this._currentProjectedPoints = this._computeProjectedPoints(state.currentTransform);
41210             this._changed = true;
41211         }
41212         if (previousNodeId !== this._previousNodeId) {
41213             this._previousNodeId = previousNodeId;
41214             this._previousPano = !!state.previousTransform.gpano;
41215             this._previousProjectedPoints = this._computeProjectedPoints(state.previousTransform);
41216             this._changed = true;
41217         }
41218         var zoom = state.zoom;
41219         if (zoom !== this._zoom) {
41220             this._zoom = zoom;
41221             this._changed = true;
41222         }
41223         if (this._changed) {
41224             this._currentFov = this._computeCurrentFov();
41225             this._previousFov = this._computePreviousFov();
41226         }
41227         var alpha = state.alpha;
41228         if (this._changed || alpha !== this._alpha) {
41229             this._alpha = alpha;
41230             this._perspective.fov = this._state === State_1.State.Earth ?
41231                 60 :
41232                 this._interpolateFov(this._currentFov, this._previousFov, this._alpha);
41233             this._changed = true;
41234         }
41235         var camera = state.camera;
41236         if (this._camera.diff(camera) > 1e-9) {
41237             this._camera.copy(camera);
41238             this._rotation = this._computeRotation(camera);
41239             this._perspective.up.copy(camera.up);
41240             this._perspective.position.copy(camera.position);
41241             this._perspective.lookAt(camera.lookat);
41242             this._perspective.updateMatrix();
41243             this._perspective.updateMatrixWorld(false);
41244             this._changed = true;
41245         }
41246         if (this._changed) {
41247             this._perspective.updateProjectionMatrix();
41248         }
41249         this._setFrameId(frame.id);
41250     };
41251     RenderCamera.prototype.setRenderMode = function (renderMode) {
41252         this._renderMode = renderMode;
41253         this._perspective.fov = this._computeFov();
41254         this._perspective.updateProjectionMatrix();
41255         this._changed = true;
41256     };
41257     RenderCamera.prototype.setSize = function (size) {
41258         this._perspective.aspect = this._computeAspect(size.width, size.height);
41259         this._perspective.fov = this._computeFov();
41260         this._perspective.updateProjectionMatrix();
41261         this._changed = true;
41262     };
41263     RenderCamera.prototype._computeAspect = function (elementWidth, elementHeight) {
41264         return elementWidth === 0 ? 0 : elementWidth / elementHeight;
41265     };
41266     RenderCamera.prototype._computeCurrentFov = function () {
41267         if (!this._currentNodeId) {
41268             return this._initialFov;
41269         }
41270         return this._currentPano ?
41271             this._yToFov(1, this._zoom) :
41272             this._computeVerticalFov(this._currentProjectedPoints, this._renderMode, this._zoom, this.perspective.aspect);
41273     };
41274     RenderCamera.prototype._computeFov = function () {
41275         this._currentFov = this._computeCurrentFov();
41276         this._previousFov = this._computePreviousFov();
41277         return this._interpolateFov(this._currentFov, this._previousFov, this._alpha);
41278     };
41279     RenderCamera.prototype._computePreviousFov = function () {
41280         if (!this._currentNodeId) {
41281             return this._initialFov;
41282         }
41283         return !this._previousNodeId ?
41284             this._currentFov :
41285             this._previousPano ?
41286                 this._yToFov(1, this._zoom) :
41287                 this._computeVerticalFov(this._previousProjectedPoints, this._renderMode, this._zoom, this.perspective.aspect);
41288     };
41289     RenderCamera.prototype._computeProjectedPoints = function (transform) {
41290         var _this = this;
41291         var os = [[0.5, 0], [1, 0]];
41292         var ds = [[0.5, 0], [0, 0.5]];
41293         var pointsPerSide = 100;
41294         var basicPoints = [];
41295         for (var side = 0; side < os.length; ++side) {
41296             var o = os[side];
41297             var d = ds[side];
41298             for (var i = 0; i <= pointsPerSide; ++i) {
41299                 basicPoints.push([o[0] + d[0] * i / pointsPerSide,
41300                     o[1] + d[1] * i / pointsPerSide]);
41301             }
41302         }
41303         var camera = new THREE.Camera();
41304         camera.up.copy(transform.upVector());
41305         camera.position.copy(new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0)));
41306         camera.lookAt(new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10)));
41307         camera.updateMatrix();
41308         camera.updateMatrixWorld(true);
41309         var projectedPoints = basicPoints
41310             .map(function (basicPoint) {
41311             var worldPoint = transform.unprojectBasic(basicPoint, 10000);
41312             var cameraPoint = _this._viewportCoords.worldToCamera(worldPoint, camera);
41313             return [
41314                 Math.abs(cameraPoint[0] / cameraPoint[2]),
41315                 Math.abs(cameraPoint[1] / cameraPoint[2]),
41316             ];
41317         });
41318         return projectedPoints;
41319     };
41320     RenderCamera.prototype._computeRequiredVerticalFov = function (projectedPoint, zoom, aspect) {
41321         var maxY = Math.max(projectedPoint[0] / aspect, projectedPoint[1]);
41322         return this._yToFov(maxY, zoom);
41323     };
41324     RenderCamera.prototype._computeRotation = function (camera) {
41325         var direction = camera.lookat.clone().sub(camera.position);
41326         var up = camera.up.clone();
41327         var upProjection = direction.clone().dot(up);
41328         var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
41329         var phi = Math.atan2(planeProjection.y, planeProjection.x);
41330         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
41331         return { phi: phi, theta: theta };
41332     };
41333     RenderCamera.prototype._computeVerticalFov = function (projectedPoints, renderMode, zoom, aspect) {
41334         var _this = this;
41335         var fovs = projectedPoints
41336             .map(function (projectedPoint) {
41337             return _this._computeRequiredVerticalFov(projectedPoint, zoom, aspect);
41338         });
41339         var fov = renderMode === Render_1.RenderMode.Fill ?
41340             Math.min.apply(Math, fovs) * 0.995 : Math.max.apply(Math, fovs);
41341         return fov;
41342     };
41343     RenderCamera.prototype._yToFov = function (y, zoom) {
41344         return 2 * Math.atan(y / Math.pow(2, zoom)) * 180 / Math.PI;
41345     };
41346     RenderCamera.prototype._interpolateFov = function (v1, v2, alpha) {
41347         return alpha * v1 + (1 - alpha) * v2;
41348     };
41349     RenderCamera.prototype._setFrameId = function (frameId) {
41350         this._frameId = frameId;
41351         if (this._changed) {
41352             this._changed = false;
41353             this._changedForFrame = frameId;
41354         }
41355     };
41356     return RenderCamera;
41357 }());
41358 exports.RenderCamera = RenderCamera;
41359 exports.default = RenderCamera;
41360
41361 },{"../Geo":277,"../Render":280,"../State":281,"three":225}],407:[function(require,module,exports){
41362 "use strict";
41363 Object.defineProperty(exports, "__esModule", { value: true });
41364 /**
41365  * Enumeration for render mode
41366  * @enum {number}
41367  * @readonly
41368  * @description Modes for specifying how rendering is done
41369  * in the viewer. All modes preserves the original aspect
41370  * ratio of the images.
41371  */
41372 var RenderMode;
41373 (function (RenderMode) {
41374     /**
41375      * Displays all content within the viewer.
41376      *
41377      * @description Black bars shown on both
41378      * sides of the content. Bars are shown
41379      * either below and above or to the left
41380      * and right of the content depending on
41381      * the aspect ratio relation between the
41382      * image and the viewer.
41383      */
41384     RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
41385     /**
41386      * Fills the viewer by cropping content.
41387      *
41388      * @description Cropping is done either
41389      * in horizontal or vertical direction
41390      * depending on the aspect ratio relation
41391      * between the image and the viewer.
41392      */
41393     RenderMode[RenderMode["Fill"] = 1] = "Fill";
41394 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
41395 exports.default = RenderMode;
41396
41397 },{}],408:[function(require,module,exports){
41398 "use strict";
41399 Object.defineProperty(exports, "__esModule", { value: true });
41400 var operators_1 = require("rxjs/operators");
41401 var rxjs_1 = require("rxjs");
41402 var Geo_1 = require("../Geo");
41403 var Render_1 = require("../Render");
41404 var RenderService = /** @class */ (function () {
41405     function RenderService(element, currentFrame$, renderMode, renderCamera) {
41406         var _this = this;
41407         this._element = element;
41408         this._currentFrame$ = currentFrame$;
41409         this._spatial = new Geo_1.Spatial();
41410         renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
41411         this._resize$ = new rxjs_1.Subject();
41412         this._renderCameraOperation$ = new rxjs_1.Subject();
41413         this._size$ =
41414             new rxjs_1.BehaviorSubject({
41415                 height: this._element.offsetHeight,
41416                 width: this._element.offsetWidth,
41417             });
41418         this._resize$.pipe(operators_1.map(function () {
41419             return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
41420         }))
41421             .subscribe(this._size$);
41422         this._renderMode$ = new rxjs_1.BehaviorSubject(renderMode);
41423         this._renderCameraHolder$ = this._renderCameraOperation$.pipe(operators_1.startWith(function (rc) {
41424             return rc;
41425         }), operators_1.scan(function (rc, operation) {
41426             return operation(rc);
41427         }, !!renderCamera ? renderCamera : new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode)), operators_1.publishReplay(1), operators_1.refCount());
41428         this._renderCameraFrame$ = this._currentFrame$.pipe(operators_1.withLatestFrom(this._renderCameraHolder$), operators_1.tap(function (_a) {
41429             var frame = _a[0], rc = _a[1];
41430             rc.setFrame(frame);
41431         }), operators_1.map(function (args) {
41432             return args[1];
41433         }), operators_1.publishReplay(1), operators_1.refCount());
41434         this._renderCamera$ = this._renderCameraFrame$.pipe(operators_1.filter(function (rc) {
41435             return rc.changed;
41436         }), operators_1.publishReplay(1), operators_1.refCount());
41437         this._bearing$ = this._renderCamera$.pipe(operators_1.map(function (rc) {
41438             var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(rc.rotation.phi));
41439             return _this._spatial.wrap(bearing, 0, 360);
41440         }), operators_1.publishReplay(1), operators_1.refCount());
41441         this._size$.pipe(operators_1.skip(1), operators_1.map(function (size) {
41442             return function (rc) {
41443                 rc.setSize(size);
41444                 return rc;
41445             };
41446         }))
41447             .subscribe(this._renderCameraOperation$);
41448         this._renderMode$.pipe(operators_1.skip(1), operators_1.map(function (rm) {
41449             return function (rc) {
41450                 rc.setRenderMode(rm);
41451                 return rc;
41452             };
41453         }))
41454             .subscribe(this._renderCameraOperation$);
41455         this._bearing$.subscribe(function () { });
41456         this._renderCameraHolder$.subscribe(function () { });
41457         this._size$.subscribe(function () { });
41458         this._renderMode$.subscribe(function () { });
41459         this._renderCamera$.subscribe(function () { });
41460         this._renderCameraFrame$.subscribe(function () { });
41461     }
41462     Object.defineProperty(RenderService.prototype, "bearing$", {
41463         get: function () {
41464             return this._bearing$;
41465         },
41466         enumerable: true,
41467         configurable: true
41468     });
41469     Object.defineProperty(RenderService.prototype, "element", {
41470         get: function () {
41471             return this._element;
41472         },
41473         enumerable: true,
41474         configurable: true
41475     });
41476     Object.defineProperty(RenderService.prototype, "resize$", {
41477         get: function () {
41478             return this._resize$;
41479         },
41480         enumerable: true,
41481         configurable: true
41482     });
41483     Object.defineProperty(RenderService.prototype, "size$", {
41484         get: function () {
41485             return this._size$;
41486         },
41487         enumerable: true,
41488         configurable: true
41489     });
41490     Object.defineProperty(RenderService.prototype, "renderMode$", {
41491         get: function () {
41492             return this._renderMode$;
41493         },
41494         enumerable: true,
41495         configurable: true
41496     });
41497     Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
41498         get: function () {
41499             return this._renderCameraFrame$;
41500         },
41501         enumerable: true,
41502         configurable: true
41503     });
41504     Object.defineProperty(RenderService.prototype, "renderCamera$", {
41505         get: function () {
41506             return this._renderCamera$;
41507         },
41508         enumerable: true,
41509         configurable: true
41510     });
41511     return RenderService;
41512 }());
41513 exports.RenderService = RenderService;
41514 exports.default = RenderService;
41515
41516
41517 },{"../Geo":277,"../Render":280,"rxjs":26,"rxjs/operators":224}],409:[function(require,module,exports){
41518 "use strict";
41519 Object.defineProperty(exports, "__esModule", { value: true });
41520 var FrameGenerator = /** @class */ (function () {
41521     function FrameGenerator(root) {
41522         if (root.requestAnimationFrame) {
41523             this._cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
41524             this._requestAnimationFrame = root.requestAnimationFrame.bind(root);
41525         }
41526         else if (root.mozRequestAnimationFrame) {
41527             this._cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
41528             this._requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
41529         }
41530         else if (root.webkitRequestAnimationFrame) {
41531             this._cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
41532             this._requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
41533         }
41534         else if (root.msRequestAnimationFrame) {
41535             this._cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
41536             this._requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
41537         }
41538         else if (root.oRequestAnimationFrame) {
41539             this._cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
41540             this._requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
41541         }
41542         else {
41543             this._cancelAnimationFrame = root.clearTimeout.bind(root);
41544             this._requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
41545         }
41546     }
41547     Object.defineProperty(FrameGenerator.prototype, "cancelAnimationFrame", {
41548         get: function () {
41549             return this._cancelAnimationFrame;
41550         },
41551         enumerable: true,
41552         configurable: true
41553     });
41554     Object.defineProperty(FrameGenerator.prototype, "requestAnimationFrame", {
41555         get: function () {
41556             return this._requestAnimationFrame;
41557         },
41558         enumerable: true,
41559         configurable: true
41560     });
41561     return FrameGenerator;
41562 }());
41563 exports.FrameGenerator = FrameGenerator;
41564 exports.default = FrameGenerator;
41565
41566 },{}],410:[function(require,module,exports){
41567 "use strict";
41568 Object.defineProperty(exports, "__esModule", { value: true });
41569 var RotationDelta = /** @class */ (function () {
41570     function RotationDelta(phi, theta) {
41571         this._phi = phi;
41572         this._theta = theta;
41573     }
41574     Object.defineProperty(RotationDelta.prototype, "phi", {
41575         get: function () {
41576             return this._phi;
41577         },
41578         set: function (value) {
41579             this._phi = value;
41580         },
41581         enumerable: true,
41582         configurable: true
41583     });
41584     Object.defineProperty(RotationDelta.prototype, "theta", {
41585         get: function () {
41586             return this._theta;
41587         },
41588         set: function (value) {
41589             this._theta = value;
41590         },
41591         enumerable: true,
41592         configurable: true
41593     });
41594     Object.defineProperty(RotationDelta.prototype, "isZero", {
41595         get: function () {
41596             return this._phi === 0 && this._theta === 0;
41597         },
41598         enumerable: true,
41599         configurable: true
41600     });
41601     RotationDelta.prototype.copy = function (delta) {
41602         this._phi = delta.phi;
41603         this._theta = delta.theta;
41604     };
41605     RotationDelta.prototype.lerp = function (other, alpha) {
41606         this._phi = (1 - alpha) * this._phi + alpha * other.phi;
41607         this._theta = (1 - alpha) * this._theta + alpha * other.theta;
41608     };
41609     RotationDelta.prototype.multiply = function (value) {
41610         this._phi *= value;
41611         this._theta *= value;
41612     };
41613     RotationDelta.prototype.threshold = function (value) {
41614         this._phi = Math.abs(this._phi) > value ? this._phi : 0;
41615         this._theta = Math.abs(this._theta) > value ? this._theta : 0;
41616     };
41617     RotationDelta.prototype.lengthSquared = function () {
41618         return this._phi * this._phi + this._theta * this._theta;
41619     };
41620     RotationDelta.prototype.reset = function () {
41621         this._phi = 0;
41622         this._theta = 0;
41623     };
41624     return RotationDelta;
41625 }());
41626 exports.RotationDelta = RotationDelta;
41627 exports.default = RotationDelta;
41628
41629 },{}],411:[function(require,module,exports){
41630 "use strict";
41631 Object.defineProperty(exports, "__esModule", { value: true });
41632 var State;
41633 (function (State) {
41634     State[State["Earth"] = 0] = "Earth";
41635     State[State["Traversing"] = 1] = "Traversing";
41636     State[State["Waiting"] = 2] = "Waiting";
41637     State[State["WaitingInteractively"] = 3] = "WaitingInteractively";
41638 })(State = exports.State || (exports.State = {}));
41639 exports.default = State;
41640
41641 },{}],412:[function(require,module,exports){
41642 "use strict";
41643 Object.defineProperty(exports, "__esModule", { value: true });
41644 var State_1 = require("../State");
41645 var Geo_1 = require("../Geo");
41646 var StateContext = /** @class */ (function () {
41647     function StateContext(transitionMode) {
41648         this._state = new State_1.TraversingState({
41649             alpha: 1,
41650             camera: new Geo_1.Camera(),
41651             currentIndex: -1,
41652             reference: { alt: 0, lat: 0, lon: 0 },
41653             trajectory: [],
41654             transitionMode: transitionMode == null ? State_1.TransitionMode.Default : transitionMode,
41655             zoom: 0,
41656         });
41657     }
41658     StateContext.prototype.earth = function () {
41659         this._state = this._state.earth();
41660     };
41661     StateContext.prototype.traverse = function () {
41662         this._state = this._state.traverse();
41663     };
41664     StateContext.prototype.wait = function () {
41665         this._state = this._state.wait();
41666     };
41667     StateContext.prototype.waitInteractively = function () {
41668         this._state = this._state.waitInteractively();
41669     };
41670     Object.defineProperty(StateContext.prototype, "state", {
41671         get: function () {
41672             if (this._state instanceof State_1.EarthState) {
41673                 return State_1.State.Earth;
41674             }
41675             else if (this._state instanceof State_1.TraversingState) {
41676                 return State_1.State.Traversing;
41677             }
41678             else if (this._state instanceof State_1.WaitingState) {
41679                 return State_1.State.Waiting;
41680             }
41681             else if (this._state instanceof State_1.InteractiveWaitingState) {
41682                 return State_1.State.WaitingInteractively;
41683             }
41684             throw new Error("Invalid state");
41685         },
41686         enumerable: true,
41687         configurable: true
41688     });
41689     Object.defineProperty(StateContext.prototype, "reference", {
41690         get: function () {
41691             return this._state.reference;
41692         },
41693         enumerable: true,
41694         configurable: true
41695     });
41696     Object.defineProperty(StateContext.prototype, "alpha", {
41697         get: function () {
41698             return this._state.alpha;
41699         },
41700         enumerable: true,
41701         configurable: true
41702     });
41703     Object.defineProperty(StateContext.prototype, "camera", {
41704         get: function () {
41705             return this._state.camera;
41706         },
41707         enumerable: true,
41708         configurable: true
41709     });
41710     Object.defineProperty(StateContext.prototype, "zoom", {
41711         get: function () {
41712             return this._state.zoom;
41713         },
41714         enumerable: true,
41715         configurable: true
41716     });
41717     Object.defineProperty(StateContext.prototype, "currentNode", {
41718         get: function () {
41719             return this._state.currentNode;
41720         },
41721         enumerable: true,
41722         configurable: true
41723     });
41724     Object.defineProperty(StateContext.prototype, "previousNode", {
41725         get: function () {
41726             return this._state.previousNode;
41727         },
41728         enumerable: true,
41729         configurable: true
41730     });
41731     Object.defineProperty(StateContext.prototype, "currentCamera", {
41732         get: function () {
41733             return this._state.currentCamera;
41734         },
41735         enumerable: true,
41736         configurable: true
41737     });
41738     Object.defineProperty(StateContext.prototype, "currentTransform", {
41739         get: function () {
41740             return this._state.currentTransform;
41741         },
41742         enumerable: true,
41743         configurable: true
41744     });
41745     Object.defineProperty(StateContext.prototype, "previousTransform", {
41746         get: function () {
41747             return this._state.previousTransform;
41748         },
41749         enumerable: true,
41750         configurable: true
41751     });
41752     Object.defineProperty(StateContext.prototype, "trajectory", {
41753         get: function () {
41754             return this._state.trajectory;
41755         },
41756         enumerable: true,
41757         configurable: true
41758     });
41759     Object.defineProperty(StateContext.prototype, "currentIndex", {
41760         get: function () {
41761             return this._state.currentIndex;
41762         },
41763         enumerable: true,
41764         configurable: true
41765     });
41766     Object.defineProperty(StateContext.prototype, "lastNode", {
41767         get: function () {
41768             return this._state.trajectory[this._state.trajectory.length - 1];
41769         },
41770         enumerable: true,
41771         configurable: true
41772     });
41773     Object.defineProperty(StateContext.prototype, "nodesAhead", {
41774         get: function () {
41775             return this._state.trajectory.length - 1 - this._state.currentIndex;
41776         },
41777         enumerable: true,
41778         configurable: true
41779     });
41780     Object.defineProperty(StateContext.prototype, "motionless", {
41781         get: function () {
41782             return this._state.motionless;
41783         },
41784         enumerable: true,
41785         configurable: true
41786     });
41787     StateContext.prototype.getCenter = function () {
41788         return this._state.getCenter();
41789     };
41790     StateContext.prototype.setCenter = function (center) {
41791         this._state.setCenter(center);
41792     };
41793     StateContext.prototype.setZoom = function (zoom) {
41794         this._state.setZoom(zoom);
41795     };
41796     StateContext.prototype.update = function (fps) {
41797         this._state.update(fps);
41798     };
41799     StateContext.prototype.append = function (nodes) {
41800         this._state.append(nodes);
41801     };
41802     StateContext.prototype.prepend = function (nodes) {
41803         this._state.prepend(nodes);
41804     };
41805     StateContext.prototype.remove = function (n) {
41806         this._state.remove(n);
41807     };
41808     StateContext.prototype.clear = function () {
41809         this._state.clear();
41810     };
41811     StateContext.prototype.clearPrior = function () {
41812         this._state.clearPrior();
41813     };
41814     StateContext.prototype.cut = function () {
41815         this._state.cut();
41816     };
41817     StateContext.prototype.set = function (nodes) {
41818         this._state.set(nodes);
41819     };
41820     StateContext.prototype.rotate = function (delta) {
41821         this._state.rotate(delta);
41822     };
41823     StateContext.prototype.rotateUnbounded = function (delta) {
41824         this._state.rotateUnbounded(delta);
41825     };
41826     StateContext.prototype.rotateWithoutInertia = function (delta) {
41827         this._state.rotateWithoutInertia(delta);
41828     };
41829     StateContext.prototype.rotateBasic = function (basicRotation) {
41830         this._state.rotateBasic(basicRotation);
41831     };
41832     StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
41833         this._state.rotateBasicUnbounded(basicRotation);
41834     };
41835     StateContext.prototype.rotateBasicWithoutInertia = function (basicRotation) {
41836         this._state.rotateBasicWithoutInertia(basicRotation);
41837     };
41838     StateContext.prototype.rotateToBasic = function (basic) {
41839         this._state.rotateToBasic(basic);
41840     };
41841     StateContext.prototype.move = function (delta) {
41842         this._state.move(delta);
41843     };
41844     StateContext.prototype.moveTo = function (delta) {
41845         this._state.moveTo(delta);
41846     };
41847     StateContext.prototype.zoomIn = function (delta, reference) {
41848         this._state.zoomIn(delta, reference);
41849     };
41850     StateContext.prototype.setSpeed = function (speed) {
41851         this._state.setSpeed(speed);
41852     };
41853     StateContext.prototype.setTransitionMode = function (mode) {
41854         this._state.setTransitionMode(mode);
41855     };
41856     StateContext.prototype.dolly = function (delta) {
41857         this._state.dolly(delta);
41858     };
41859     StateContext.prototype.orbit = function (rotation) {
41860         this._state.orbit(rotation);
41861     };
41862     StateContext.prototype.truck = function (direction) {
41863         this._state.truck(direction);
41864     };
41865     return StateContext;
41866 }());
41867 exports.StateContext = StateContext;
41868
41869 },{"../Geo":277,"../State":281}],413:[function(require,module,exports){
41870 "use strict";
41871 Object.defineProperty(exports, "__esModule", { value: true });
41872 var rxjs_1 = require("rxjs");
41873 var operators_1 = require("rxjs/operators");
41874 var State_1 = require("../State");
41875 var StateService = /** @class */ (function () {
41876     function StateService(transitionMode) {
41877         var _this = this;
41878         this._appendNode$ = new rxjs_1.Subject();
41879         this._start$ = new rxjs_1.Subject();
41880         this._frame$ = new rxjs_1.Subject();
41881         this._fpsSampleRate = 30;
41882         this._contextOperation$ = new rxjs_1.BehaviorSubject(function (context) {
41883             return context;
41884         });
41885         this._context$ = this._contextOperation$.pipe(operators_1.scan(function (context, operation) {
41886             return operation(context);
41887         }, new State_1.StateContext(transitionMode)), operators_1.publishReplay(1), operators_1.refCount());
41888         this._state$ = this._context$.pipe(operators_1.map(function (context) {
41889             return context.state;
41890         }), operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
41891         this._fps$ = this._start$.pipe(operators_1.switchMap(function () {
41892             return _this._frame$.pipe(operators_1.bufferCount(1, _this._fpsSampleRate), operators_1.map(function (frameIds) {
41893                 return new Date().getTime();
41894             }), operators_1.pairwise(), operators_1.map(function (times) {
41895                 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
41896             }), operators_1.startWith(60));
41897         }), operators_1.share());
41898         this._currentState$ = this._frame$.pipe(operators_1.withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
41899             return [frameId, fps, context];
41900         }), operators_1.filter(function (fc) {
41901             return fc[2].currentNode != null;
41902         }), operators_1.tap(function (fc) {
41903             fc[2].update(fc[1]);
41904         }), operators_1.map(function (fc) {
41905             return { fps: fc[1], id: fc[0], state: fc[2] };
41906         }), operators_1.share());
41907         this._lastState$ = this._currentState$.pipe(operators_1.publishReplay(1), operators_1.refCount());
41908         var nodeChanged$ = this._currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (f) {
41909             return f.state.currentNode.key;
41910         }), operators_1.publishReplay(1), operators_1.refCount());
41911         var nodeChangedSubject$ = new rxjs_1.Subject();
41912         nodeChanged$
41913             .subscribe(nodeChangedSubject$);
41914         this._currentKey$ = new rxjs_1.BehaviorSubject(null);
41915         nodeChangedSubject$.pipe(operators_1.map(function (f) {
41916             return f.state.currentNode.key;
41917         }))
41918             .subscribe(this._currentKey$);
41919         this._currentNode$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
41920             return f.state.currentNode;
41921         }), operators_1.publishReplay(1), operators_1.refCount());
41922         this._currentCamera$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
41923             return f.state.currentCamera;
41924         }), operators_1.publishReplay(1), operators_1.refCount());
41925         this._currentTransform$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
41926             return f.state.currentTransform;
41927         }), operators_1.publishReplay(1), operators_1.refCount());
41928         this._reference$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
41929             return f.state.reference;
41930         }), operators_1.distinctUntilChanged(function (r1, r2) {
41931             return r1.lat === r2.lat && r1.lon === r2.lon;
41932         }, function (reference) {
41933             return { lat: reference.lat, lon: reference.lon };
41934         }), operators_1.publishReplay(1), operators_1.refCount());
41935         this._currentNodeExternal$ = nodeChanged$.pipe(operators_1.map(function (f) {
41936             return f.state.currentNode;
41937         }), operators_1.publishReplay(1), operators_1.refCount());
41938         this._appendNode$.pipe(operators_1.map(function (node) {
41939             return function (context) {
41940                 context.append([node]);
41941                 return context;
41942             };
41943         }))
41944             .subscribe(this._contextOperation$);
41945         this._inMotionOperation$ = new rxjs_1.Subject();
41946         nodeChanged$.pipe(operators_1.map(function (frame) {
41947             return true;
41948         }))
41949             .subscribe(this._inMotionOperation$);
41950         this._inMotionOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.filter(function (moving) {
41951             return moving;
41952         }), operators_1.switchMap(function (moving) {
41953             return _this._currentState$.pipe(operators_1.filter(function (frame) {
41954                 return frame.state.nodesAhead === 0;
41955             }), operators_1.map(function (frame) {
41956                 return [frame.state.camera.clone(), frame.state.zoom];
41957             }), operators_1.pairwise(), operators_1.map(function (pair) {
41958                 var c1 = pair[0][0];
41959                 var c2 = pair[1][0];
41960                 var z1 = pair[0][1];
41961                 var z2 = pair[1][1];
41962                 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
41963             }), operators_1.first(function (changed) {
41964                 return !changed;
41965             }));
41966         }))
41967             .subscribe(this._inMotionOperation$);
41968         this._inMotion$ = this._inMotionOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
41969         this._inTranslationOperation$ = new rxjs_1.Subject();
41970         nodeChanged$.pipe(operators_1.map(function (frame) {
41971             return true;
41972         }))
41973             .subscribe(this._inTranslationOperation$);
41974         this._inTranslationOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.filter(function (inTranslation) {
41975             return inTranslation;
41976         }), operators_1.switchMap(function (inTranslation) {
41977             return _this._currentState$.pipe(operators_1.filter(function (frame) {
41978                 return frame.state.nodesAhead === 0;
41979             }), operators_1.map(function (frame) {
41980                 return frame.state.camera.position.clone();
41981             }), operators_1.pairwise(), operators_1.map(function (pair) {
41982                 return pair[0].distanceToSquared(pair[1]) !== 0;
41983             }), operators_1.first(function (changed) {
41984                 return !changed;
41985             }));
41986         }))
41987             .subscribe(this._inTranslationOperation$);
41988         this._inTranslation$ = this._inTranslationOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
41989         this._state$.subscribe(function () { });
41990         this._currentNode$.subscribe(function () { });
41991         this._currentCamera$.subscribe(function () { });
41992         this._currentTransform$.subscribe(function () { });
41993         this._reference$.subscribe(function () { });
41994         this._currentNodeExternal$.subscribe(function () { });
41995         this._lastState$.subscribe(function () { });
41996         this._inMotion$.subscribe(function () { });
41997         this._inTranslation$.subscribe(function () { });
41998         this._frameId = null;
41999         this._frameGenerator = new State_1.FrameGenerator(window);
42000     }
42001     Object.defineProperty(StateService.prototype, "currentState$", {
42002         get: function () {
42003             return this._currentState$;
42004         },
42005         enumerable: true,
42006         configurable: true
42007     });
42008     Object.defineProperty(StateService.prototype, "currentNode$", {
42009         get: function () {
42010             return this._currentNode$;
42011         },
42012         enumerable: true,
42013         configurable: true
42014     });
42015     Object.defineProperty(StateService.prototype, "currentKey$", {
42016         get: function () {
42017             return this._currentKey$;
42018         },
42019         enumerable: true,
42020         configurable: true
42021     });
42022     Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
42023         get: function () {
42024             return this._currentNodeExternal$;
42025         },
42026         enumerable: true,
42027         configurable: true
42028     });
42029     Object.defineProperty(StateService.prototype, "currentCamera$", {
42030         get: function () {
42031             return this._currentCamera$;
42032         },
42033         enumerable: true,
42034         configurable: true
42035     });
42036     Object.defineProperty(StateService.prototype, "currentTransform$", {
42037         get: function () {
42038             return this._currentTransform$;
42039         },
42040         enumerable: true,
42041         configurable: true
42042     });
42043     Object.defineProperty(StateService.prototype, "state$", {
42044         get: function () {
42045             return this._state$;
42046         },
42047         enumerable: true,
42048         configurable: true
42049     });
42050     Object.defineProperty(StateService.prototype, "reference$", {
42051         get: function () {
42052             return this._reference$;
42053         },
42054         enumerable: true,
42055         configurable: true
42056     });
42057     Object.defineProperty(StateService.prototype, "inMotion$", {
42058         get: function () {
42059             return this._inMotion$;
42060         },
42061         enumerable: true,
42062         configurable: true
42063     });
42064     Object.defineProperty(StateService.prototype, "inTranslation$", {
42065         get: function () {
42066             return this._inTranslation$;
42067         },
42068         enumerable: true,
42069         configurable: true
42070     });
42071     Object.defineProperty(StateService.prototype, "appendNode$", {
42072         get: function () {
42073             return this._appendNode$;
42074         },
42075         enumerable: true,
42076         configurable: true
42077     });
42078     StateService.prototype.earth = function () {
42079         this._inMotionOperation$.next(true);
42080         this._invokeContextOperation(function (context) { context.earth(); });
42081     };
42082     StateService.prototype.traverse = function () {
42083         this._inMotionOperation$.next(true);
42084         this._invokeContextOperation(function (context) { context.traverse(); });
42085     };
42086     StateService.prototype.wait = function () {
42087         this._invokeContextOperation(function (context) { context.wait(); });
42088     };
42089     StateService.prototype.waitInteractively = function () {
42090         this._invokeContextOperation(function (context) { context.waitInteractively(); });
42091     };
42092     StateService.prototype.appendNodes = function (nodes) {
42093         this._invokeContextOperation(function (context) { context.append(nodes); });
42094     };
42095     StateService.prototype.prependNodes = function (nodes) {
42096         this._invokeContextOperation(function (context) { context.prepend(nodes); });
42097     };
42098     StateService.prototype.removeNodes = function (n) {
42099         this._invokeContextOperation(function (context) { context.remove(n); });
42100     };
42101     StateService.prototype.clearNodes = function () {
42102         this._invokeContextOperation(function (context) { context.clear(); });
42103     };
42104     StateService.prototype.clearPriorNodes = function () {
42105         this._invokeContextOperation(function (context) { context.clearPrior(); });
42106     };
42107     StateService.prototype.cutNodes = function () {
42108         this._invokeContextOperation(function (context) { context.cut(); });
42109     };
42110     StateService.prototype.setNodes = function (nodes) {
42111         this._invokeContextOperation(function (context) { context.set(nodes); });
42112     };
42113     StateService.prototype.rotate = function (delta) {
42114         this._inMotionOperation$.next(true);
42115         this._invokeContextOperation(function (context) { context.rotate(delta); });
42116     };
42117     StateService.prototype.rotateUnbounded = function (delta) {
42118         this._inMotionOperation$.next(true);
42119         this._invokeContextOperation(function (context) { context.rotateUnbounded(delta); });
42120     };
42121     StateService.prototype.rotateWithoutInertia = function (delta) {
42122         this._inMotionOperation$.next(true);
42123         this._invokeContextOperation(function (context) { context.rotateWithoutInertia(delta); });
42124     };
42125     StateService.prototype.rotateBasic = function (basicRotation) {
42126         this._inMotionOperation$.next(true);
42127         this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
42128     };
42129     StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
42130         this._inMotionOperation$.next(true);
42131         this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
42132     };
42133     StateService.prototype.rotateBasicWithoutInertia = function (basicRotation) {
42134         this._inMotionOperation$.next(true);
42135         this._invokeContextOperation(function (context) { context.rotateBasicWithoutInertia(basicRotation); });
42136     };
42137     StateService.prototype.rotateToBasic = function (basic) {
42138         this._inMotionOperation$.next(true);
42139         this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
42140     };
42141     StateService.prototype.move = function (delta) {
42142         this._inMotionOperation$.next(true);
42143         this._invokeContextOperation(function (context) { context.move(delta); });
42144     };
42145     StateService.prototype.moveTo = function (position) {
42146         this._inMotionOperation$.next(true);
42147         this._invokeContextOperation(function (context) { context.moveTo(position); });
42148     };
42149     StateService.prototype.dolly = function (delta) {
42150         this._inMotionOperation$.next(true);
42151         this._invokeContextOperation(function (context) { context.dolly(delta); });
42152     };
42153     StateService.prototype.orbit = function (rotation) {
42154         this._inMotionOperation$.next(true);
42155         this._invokeContextOperation(function (context) { context.orbit(rotation); });
42156     };
42157     StateService.prototype.truck = function (direction) {
42158         this._inMotionOperation$.next(true);
42159         this._invokeContextOperation(function (context) { context.truck(direction); });
42160     };
42161     /**
42162      * Change zoom level while keeping the reference point position approximately static.
42163      *
42164      * @parameter {number} delta - Change in zoom level.
42165      * @parameter {Array<number>} reference - Reference point in basic coordinates.
42166      */
42167     StateService.prototype.zoomIn = function (delta, reference) {
42168         this._inMotionOperation$.next(true);
42169         this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
42170     };
42171     StateService.prototype.getCenter = function () {
42172         return this._lastState$.pipe(operators_1.first(), operators_1.map(function (frame) {
42173             return frame.state.getCenter();
42174         }));
42175     };
42176     StateService.prototype.getZoom = function () {
42177         return this._lastState$.pipe(operators_1.first(), operators_1.map(function (frame) {
42178             return frame.state.zoom;
42179         }));
42180     };
42181     StateService.prototype.setCenter = function (center) {
42182         this._inMotionOperation$.next(true);
42183         this._invokeContextOperation(function (context) { context.setCenter(center); });
42184     };
42185     StateService.prototype.setSpeed = function (speed) {
42186         this._invokeContextOperation(function (context) { context.setSpeed(speed); });
42187     };
42188     StateService.prototype.setTransitionMode = function (mode) {
42189         this._invokeContextOperation(function (context) { context.setTransitionMode(mode); });
42190     };
42191     StateService.prototype.setZoom = function (zoom) {
42192         this._inMotionOperation$.next(true);
42193         this._invokeContextOperation(function (context) { context.setZoom(zoom); });
42194     };
42195     StateService.prototype.start = function () {
42196         if (this._frameId == null) {
42197             this._start$.next(null);
42198             this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
42199             this._frame$.next(this._frameId);
42200         }
42201     };
42202     StateService.prototype.stop = function () {
42203         if (this._frameId != null) {
42204             this._frameGenerator.cancelAnimationFrame(this._frameId);
42205             this._frameId = null;
42206         }
42207     };
42208     StateService.prototype._invokeContextOperation = function (action) {
42209         this._contextOperation$
42210             .next(function (context) {
42211             action(context);
42212             return context;
42213         });
42214     };
42215     StateService.prototype._frame = function (time) {
42216         this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
42217         this._frame$.next(this._frameId);
42218     };
42219     return StateService;
42220 }());
42221 exports.StateService = StateService;
42222
42223 },{"../State":281,"rxjs":26,"rxjs/operators":224}],414:[function(require,module,exports){
42224 "use strict";
42225 Object.defineProperty(exports, "__esModule", { value: true });
42226 /**
42227  * Enumeration for transition mode
42228  * @enum {number}
42229  * @readonly
42230  * @description Modes for specifying how transitions
42231  * between nodes are performed.
42232  */
42233 var TransitionMode;
42234 (function (TransitionMode) {
42235     /**
42236      * Default transitions.
42237      *
42238      * @description The viewer dynamically determines
42239      * whether transitions should be performed with or
42240      * without motion and blending for each transition
42241      * based on the underlying data.
42242      */
42243     TransitionMode[TransitionMode["Default"] = 0] = "Default";
42244     /**
42245      * Instantaneous transitions.
42246      *
42247      * @description All transitions are performed
42248      * without motion or blending.
42249      */
42250     TransitionMode[TransitionMode["Instantaneous"] = 1] = "Instantaneous";
42251 })(TransitionMode = exports.TransitionMode || (exports.TransitionMode = {}));
42252 exports.default = TransitionMode;
42253
42254 },{}],415:[function(require,module,exports){
42255 "use strict";
42256 var __extends = (this && this.__extends) || (function () {
42257     var extendStatics = function (d, b) {
42258         extendStatics = Object.setPrototypeOf ||
42259             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42260             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42261         return extendStatics(d, b);
42262     }
42263     return function (d, b) {
42264         extendStatics(d, b);
42265         function __() { this.constructor = d; }
42266         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42267     };
42268 })();
42269 Object.defineProperty(exports, "__esModule", { value: true });
42270 var THREE = require("three");
42271 var State_1 = require("../../State");
42272 var EarthState = /** @class */ (function (_super) {
42273     __extends(EarthState, _super);
42274     function EarthState(state) {
42275         var _this = _super.call(this, state) || this;
42276         var viewingDirection = _this._camera.lookat
42277             .clone()
42278             .sub(_this._camera.position)
42279             .normalize();
42280         _this._camera.lookat.copy(_this._camera.position);
42281         _this._camera.position.z = state.camera.position.z + 20;
42282         _this._camera.position.x = state.camera.position.x - 16 * viewingDirection.x;
42283         _this._camera.position.y = state.camera.position.y - 16 * viewingDirection.y;
42284         _this._camera.up.set(0, 0, 1);
42285         return _this;
42286     }
42287     EarthState.prototype.traverse = function () {
42288         return new State_1.TraversingState(this);
42289     };
42290     EarthState.prototype.wait = function () {
42291         return new State_1.WaitingState(this);
42292     };
42293     EarthState.prototype.waitInteractively = function () {
42294         return new State_1.InteractiveWaitingState(this);
42295     };
42296     EarthState.prototype.dolly = function (delta) {
42297         var camera = this._camera;
42298         var offset = new THREE.Vector3()
42299             .copy(camera.position)
42300             .sub(camera.lookat);
42301         var length = offset.length();
42302         var scaled = length * Math.pow(2, -delta);
42303         var clipped = Math.max(1, Math.min(scaled, 1000));
42304         offset.normalize();
42305         offset.multiplyScalar(clipped);
42306         camera.position.copy(camera.lookat).add(offset);
42307     };
42308     EarthState.prototype.orbit = function (rotation) {
42309         var camera = this._camera;
42310         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
42311         var qInverse = q.clone().inverse();
42312         var offset = new THREE.Vector3();
42313         offset.copy(camera.position).sub(camera.lookat);
42314         offset.applyQuaternion(q);
42315         var length = offset.length();
42316         var phi = Math.atan2(offset.y, offset.x);
42317         phi += rotation.phi;
42318         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
42319         theta += rotation.theta;
42320         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
42321         offset.x = Math.sin(theta) * Math.cos(phi);
42322         offset.y = Math.sin(theta) * Math.sin(phi);
42323         offset.z = Math.cos(theta);
42324         offset.applyQuaternion(qInverse);
42325         camera.position.copy(camera.lookat).add(offset.multiplyScalar(length));
42326     };
42327     EarthState.prototype.truck = function (direction) {
42328         this._camera.position.add(new THREE.Vector3().fromArray(direction));
42329         this._camera.lookat.add(new THREE.Vector3().fromArray(direction));
42330     };
42331     EarthState.prototype.update = function () { };
42332     return EarthState;
42333 }(State_1.StateBase));
42334 exports.EarthState = EarthState;
42335 exports.default = EarthState;
42336
42337
42338 },{"../../State":281,"three":225}],416:[function(require,module,exports){
42339 "use strict";
42340 var __extends = (this && this.__extends) || (function () {
42341     var extendStatics = function (d, b) {
42342         extendStatics = Object.setPrototypeOf ||
42343             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42344             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42345         return extendStatics(d, b);
42346     }
42347     return function (d, b) {
42348         extendStatics(d, b);
42349         function __() { this.constructor = d; }
42350         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42351     };
42352 })();
42353 Object.defineProperty(exports, "__esModule", { value: true });
42354 var THREE = require("three");
42355 var State_1 = require("../../State");
42356 var InteractiveStateBase = /** @class */ (function (_super) {
42357     __extends(InteractiveStateBase, _super);
42358     function InteractiveStateBase(state) {
42359         var _this = _super.call(this, state) || this;
42360         _this._animationSpeed = 1 / 40;
42361         _this._rotationDelta = new State_1.RotationDelta(0, 0);
42362         _this._requestedRotationDelta = null;
42363         _this._basicRotation = [0, 0];
42364         _this._requestedBasicRotation = null;
42365         _this._requestedBasicRotationUnbounded = null;
42366         _this._rotationAcceleration = 0.86;
42367         _this._rotationIncreaseAlpha = 0.97;
42368         _this._rotationDecreaseAlpha = 0.9;
42369         _this._rotationThreshold = 1e-3;
42370         _this._unboundedRotationAlpha = 0.8;
42371         _this._desiredZoom = state.zoom;
42372         _this._minZoom = 0;
42373         _this._maxZoom = 3;
42374         _this._lookatDepth = 10;
42375         _this._desiredLookat = null;
42376         _this._desiredCenter = null;
42377         return _this;
42378     }
42379     InteractiveStateBase.prototype.rotate = function (rotationDelta) {
42380         if (this._currentNode == null) {
42381             return;
42382         }
42383         this._desiredZoom = this._zoom;
42384         this._desiredLookat = null;
42385         this._requestedBasicRotation = null;
42386         if (this._requestedRotationDelta != null) {
42387             this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
42388             this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
42389         }
42390         else {
42391             this._requestedRotationDelta = new State_1.RotationDelta(rotationDelta.phi, rotationDelta.theta);
42392         }
42393     };
42394     InteractiveStateBase.prototype.rotateUnbounded = function (delta) {
42395         if (this._currentNode == null) {
42396             return;
42397         }
42398         this._requestedBasicRotation = null;
42399         this._requestedRotationDelta = null;
42400         this._applyRotation(delta, this._currentCamera);
42401         this._applyRotation(delta, this._previousCamera);
42402         if (!this._desiredLookat) {
42403             return;
42404         }
42405         var q = new THREE.Quaternion().setFromUnitVectors(this._currentCamera.up, new THREE.Vector3(0, 0, 1));
42406         var qInverse = q.clone().inverse();
42407         var offset = new THREE.Vector3()
42408             .copy(this._desiredLookat)
42409             .sub(this._camera.position)
42410             .applyQuaternion(q);
42411         var length = offset.length();
42412         var phi = Math.atan2(offset.y, offset.x);
42413         phi += delta.phi;
42414         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
42415         theta += delta.theta;
42416         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
42417         offset.x = Math.sin(theta) * Math.cos(phi);
42418         offset.y = Math.sin(theta) * Math.sin(phi);
42419         offset.z = Math.cos(theta);
42420         offset.applyQuaternion(qInverse);
42421         this._desiredLookat
42422             .copy(this._camera.position)
42423             .add(offset.multiplyScalar(length));
42424     };
42425     InteractiveStateBase.prototype.rotateWithoutInertia = function (rotationDelta) {
42426         if (this._currentNode == null) {
42427             return;
42428         }
42429         this._desiredZoom = this._zoom;
42430         this._desiredLookat = null;
42431         this._requestedBasicRotation = null;
42432         this._requestedRotationDelta = null;
42433         var threshold = Math.PI / (10 * Math.pow(2, this._zoom));
42434         var delta = {
42435             phi: this._spatial.clamp(rotationDelta.phi, -threshold, threshold),
42436             theta: this._spatial.clamp(rotationDelta.theta, -threshold, threshold),
42437         };
42438         this._applyRotation(delta, this._currentCamera);
42439         this._applyRotation(delta, this._previousCamera);
42440     };
42441     InteractiveStateBase.prototype.rotateBasic = function (basicRotation) {
42442         if (this._currentNode == null) {
42443             return;
42444         }
42445         this._desiredZoom = this._zoom;
42446         this._desiredLookat = null;
42447         this._requestedRotationDelta = null;
42448         if (this._requestedBasicRotation != null) {
42449             this._requestedBasicRotation[0] += basicRotation[0];
42450             this._requestedBasicRotation[1] += basicRotation[1];
42451             var threshold = 0.05 / Math.pow(2, this._zoom);
42452             this._requestedBasicRotation[0] =
42453                 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
42454             this._requestedBasicRotation[1] =
42455                 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
42456         }
42457         else {
42458             this._requestedBasicRotation = basicRotation.slice();
42459         }
42460     };
42461     InteractiveStateBase.prototype.rotateBasicUnbounded = function (basicRotation) {
42462         if (this._currentNode == null) {
42463             return;
42464         }
42465         if (this._requestedBasicRotationUnbounded != null) {
42466             this._requestedBasicRotationUnbounded[0] += basicRotation[0];
42467             this._requestedBasicRotationUnbounded[1] += basicRotation[1];
42468         }
42469         else {
42470             this._requestedBasicRotationUnbounded = basicRotation.slice();
42471         }
42472     };
42473     InteractiveStateBase.prototype.rotateBasicWithoutInertia = function (basic) {
42474         if (this._currentNode == null) {
42475             return;
42476         }
42477         this._desiredZoom = this._zoom;
42478         this._desiredLookat = null;
42479         this._requestedRotationDelta = null;
42480         this._requestedBasicRotation = null;
42481         var threshold = 0.05 / Math.pow(2, this._zoom);
42482         var basicRotation = basic.slice();
42483         basicRotation[0] = this._spatial.clamp(basicRotation[0], -threshold, threshold);
42484         basicRotation[1] = this._spatial.clamp(basicRotation[1], -threshold, threshold);
42485         this._applyRotationBasic(basicRotation);
42486     };
42487     InteractiveStateBase.prototype.rotateToBasic = function (basic) {
42488         if (this._currentNode == null) {
42489             return;
42490         }
42491         this._desiredZoom = this._zoom;
42492         this._desiredLookat = null;
42493         basic[0] = this._spatial.clamp(basic[0], 0, 1);
42494         basic[1] = this._spatial.clamp(basic[1], 0, 1);
42495         var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
42496         this._currentCamera.lookat.fromArray(lookat);
42497     };
42498     InteractiveStateBase.prototype.zoomIn = function (delta, reference) {
42499         if (this._currentNode == null) {
42500             return;
42501         }
42502         this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
42503         var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
42504         var currentCenterX = currentCenter[0];
42505         var currentCenterY = currentCenter[1];
42506         var zoom0 = Math.pow(2, this._zoom);
42507         var zoom1 = Math.pow(2, this._desiredZoom);
42508         var refX = reference[0];
42509         var refY = reference[1];
42510         if (this.currentTransform.gpano != null &&
42511             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
42512             if (refX - currentCenterX > 0.5) {
42513                 refX = refX - 1;
42514             }
42515             else if (currentCenterX - refX > 0.5) {
42516                 refX = 1 + refX;
42517             }
42518         }
42519         var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
42520         var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
42521         var gpano = this.currentTransform.gpano;
42522         if (this._currentNode.fullPano) {
42523             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
42524             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
42525         }
42526         else if (gpano != null &&
42527             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
42528             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
42529             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
42530         }
42531         else {
42532             newCenterX = this._spatial.clamp(newCenterX, 0, 1);
42533             newCenterY = this._spatial.clamp(newCenterY, 0, 1);
42534         }
42535         this._desiredLookat = new THREE.Vector3()
42536             .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
42537     };
42538     InteractiveStateBase.prototype.setCenter = function (center) {
42539         this._desiredLookat = null;
42540         this._requestedRotationDelta = null;
42541         this._requestedBasicRotation = null;
42542         this._desiredZoom = this._zoom;
42543         var clamped = [
42544             this._spatial.clamp(center[0], 0, 1),
42545             this._spatial.clamp(center[1], 0, 1),
42546         ];
42547         if (this._currentNode == null) {
42548             this._desiredCenter = clamped;
42549             return;
42550         }
42551         this._desiredCenter = null;
42552         var currentLookat = new THREE.Vector3()
42553             .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
42554         var previousTransform = this.previousTransform != null ?
42555             this.previousTransform :
42556             this.currentTransform;
42557         var previousLookat = new THREE.Vector3()
42558             .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
42559         this._currentCamera.lookat.copy(currentLookat);
42560         this._previousCamera.lookat.copy(previousLookat);
42561     };
42562     InteractiveStateBase.prototype.setZoom = function (zoom) {
42563         this._desiredLookat = null;
42564         this._requestedRotationDelta = null;
42565         this._requestedBasicRotation = null;
42566         this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
42567         this._desiredZoom = this._zoom;
42568     };
42569     InteractiveStateBase.prototype._applyRotation = function (delta, camera) {
42570         if (camera == null) {
42571             return;
42572         }
42573         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
42574         var qInverse = q.clone().inverse();
42575         var offset = new THREE.Vector3();
42576         offset.copy(camera.lookat).sub(camera.position);
42577         offset.applyQuaternion(q);
42578         var length = offset.length();
42579         var phi = Math.atan2(offset.y, offset.x);
42580         phi += delta.phi;
42581         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
42582         theta += delta.theta;
42583         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
42584         offset.x = Math.sin(theta) * Math.cos(phi);
42585         offset.y = Math.sin(theta) * Math.sin(phi);
42586         offset.z = Math.cos(theta);
42587         offset.applyQuaternion(qInverse);
42588         camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
42589     };
42590     InteractiveStateBase.prototype._applyRotationBasic = function (basicRotation) {
42591         var currentNode = this._currentNode;
42592         var previousNode = this._previousNode != null ?
42593             this.previousNode :
42594             this.currentNode;
42595         var currentCamera = this._currentCamera;
42596         var previousCamera = this._previousCamera;
42597         var currentTransform = this.currentTransform;
42598         var previousTransform = this.previousTransform != null ?
42599             this.previousTransform :
42600             this.currentTransform;
42601         var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
42602         var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
42603         var currentGPano = currentTransform.gpano;
42604         var previousGPano = previousTransform.gpano;
42605         if (currentNode.fullPano) {
42606             currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
42607             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0.05, 0.95);
42608         }
42609         else if (currentGPano != null &&
42610             currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
42611             currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
42612             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
42613         }
42614         else {
42615             currentBasic[0] = this._spatial.clamp(currentBasic[0] + basicRotation[0], 0, 1);
42616             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
42617         }
42618         if (previousNode.fullPano) {
42619             previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
42620             previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0.05, 0.95);
42621         }
42622         else if (previousGPano != null &&
42623             previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
42624             previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
42625             previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0, 1);
42626         }
42627         else {
42628             previousBasic[0] = this._spatial.clamp(previousBasic[0] + basicRotation[0], 0, 1);
42629             previousBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
42630         }
42631         var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
42632         currentCamera.lookat.fromArray(currentLookat);
42633         var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
42634         previousCamera.lookat.fromArray(previousLookat);
42635     };
42636     InteractiveStateBase.prototype._updateZoom = function (animationSpeed) {
42637         var diff = this._desiredZoom - this._zoom;
42638         var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
42639         if (diff === 0) {
42640             return;
42641         }
42642         else if (Math.abs(diff) < 2e-3) {
42643             this._zoom = this._desiredZoom;
42644             if (this._desiredLookat != null) {
42645                 this._desiredLookat = null;
42646             }
42647         }
42648         else {
42649             this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
42650         }
42651     };
42652     InteractiveStateBase.prototype._updateLookat = function (animationSpeed) {
42653         if (this._desiredLookat === null) {
42654             return;
42655         }
42656         var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
42657         if (Math.abs(diff) < 1e-6) {
42658             this._currentCamera.lookat.copy(this._desiredLookat);
42659             this._desiredLookat = null;
42660         }
42661         else {
42662             this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
42663         }
42664     };
42665     InteractiveStateBase.prototype._updateRotation = function () {
42666         if (this._requestedRotationDelta != null) {
42667             var length_1 = this._rotationDelta.lengthSquared();
42668             var requestedLength = this._requestedRotationDelta.lengthSquared();
42669             if (requestedLength > length_1) {
42670                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
42671             }
42672             else {
42673                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
42674             }
42675             this._requestedRotationDelta = null;
42676             return;
42677         }
42678         if (this._rotationDelta.isZero) {
42679             return;
42680         }
42681         this._rotationDelta.multiply(this._rotationAcceleration);
42682         this._rotationDelta.threshold(this._rotationThreshold);
42683     };
42684     InteractiveStateBase.prototype._updateRotationBasic = function () {
42685         if (this._requestedBasicRotation != null) {
42686             var x = this._basicRotation[0];
42687             var y = this._basicRotation[1];
42688             var reqX = this._requestedBasicRotation[0];
42689             var reqY = this._requestedBasicRotation[1];
42690             if (Math.abs(reqX) > Math.abs(x)) {
42691                 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
42692             }
42693             else {
42694                 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
42695             }
42696             if (Math.abs(reqY) > Math.abs(y)) {
42697                 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
42698             }
42699             else {
42700                 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
42701             }
42702             this._requestedBasicRotation = null;
42703             return;
42704         }
42705         if (this._requestedBasicRotationUnbounded != null) {
42706             var reqX = this._requestedBasicRotationUnbounded[0];
42707             var reqY = this._requestedBasicRotationUnbounded[1];
42708             if (Math.abs(reqX) > 0) {
42709                 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
42710             }
42711             if (Math.abs(reqY) > 0) {
42712                 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
42713             }
42714             if (this._desiredLookat != null) {
42715                 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
42716                 desiredBasicLookat[0] += reqX;
42717                 desiredBasicLookat[1] += reqY;
42718                 this._desiredLookat = new THREE.Vector3()
42719                     .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
42720             }
42721             this._requestedBasicRotationUnbounded = null;
42722         }
42723         if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
42724             return;
42725         }
42726         this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
42727         this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
42728         if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
42729             Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
42730             this._basicRotation = [0, 0];
42731         }
42732     };
42733     InteractiveStateBase.prototype._clearRotation = function () {
42734         if (this._currentNode.fullPano) {
42735             return;
42736         }
42737         if (this._requestedRotationDelta != null) {
42738             this._requestedRotationDelta = null;
42739         }
42740         if (!this._rotationDelta.isZero) {
42741             this._rotationDelta.reset();
42742         }
42743         if (this._requestedBasicRotation != null) {
42744             this._requestedBasicRotation = null;
42745         }
42746         if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
42747             this._basicRotation = [0, 0];
42748         }
42749     };
42750     InteractiveStateBase.prototype._setDesiredCenter = function () {
42751         if (this._desiredCenter == null) {
42752             return;
42753         }
42754         var lookatDirection = new THREE.Vector3()
42755             .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
42756             .sub(this._currentCamera.position);
42757         this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
42758         this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
42759         this._desiredCenter = null;
42760     };
42761     InteractiveStateBase.prototype._setDesiredZoom = function () {
42762         this._desiredZoom =
42763             this._currentNode.fullPano || this._previousNode == null ?
42764                 this._zoom : 0;
42765     };
42766     return InteractiveStateBase;
42767 }(State_1.StateBase));
42768 exports.InteractiveStateBase = InteractiveStateBase;
42769 exports.default = InteractiveStateBase;
42770
42771
42772 },{"../../State":281,"three":225}],417:[function(require,module,exports){
42773 "use strict";
42774 var __extends = (this && this.__extends) || (function () {
42775     var extendStatics = function (d, b) {
42776         extendStatics = Object.setPrototypeOf ||
42777             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42778             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42779         return extendStatics(d, b);
42780     }
42781     return function (d, b) {
42782         extendStatics(d, b);
42783         function __() { this.constructor = d; }
42784         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42785     };
42786 })();
42787 Object.defineProperty(exports, "__esModule", { value: true });
42788 var State_1 = require("../../State");
42789 var InteractiveWaitingState = /** @class */ (function (_super) {
42790     __extends(InteractiveWaitingState, _super);
42791     function InteractiveWaitingState(state) {
42792         var _this = _super.call(this, state) || this;
42793         _this._adjustCameras();
42794         _this._motionless = _this._motionlessTransition();
42795         return _this;
42796     }
42797     InteractiveWaitingState.prototype.traverse = function () {
42798         return new State_1.TraversingState(this);
42799     };
42800     InteractiveWaitingState.prototype.wait = function () {
42801         return new State_1.WaitingState(this);
42802     };
42803     InteractiveWaitingState.prototype.prepend = function (nodes) {
42804         _super.prototype.prepend.call(this, nodes);
42805         this._motionless = this._motionlessTransition();
42806     };
42807     InteractiveWaitingState.prototype.set = function (nodes) {
42808         _super.prototype.set.call(this, nodes);
42809         this._motionless = this._motionlessTransition();
42810     };
42811     InteractiveWaitingState.prototype.move = function (delta) {
42812         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
42813     };
42814     InteractiveWaitingState.prototype.moveTo = function (position) {
42815         this._alpha = Math.max(0, Math.min(1, position));
42816     };
42817     InteractiveWaitingState.prototype.update = function (fps) {
42818         this._updateRotation();
42819         if (!this._rotationDelta.isZero) {
42820             this._applyRotation(this._rotationDelta, this._previousCamera);
42821             this._applyRotation(this._rotationDelta, this._currentCamera);
42822         }
42823         this._updateRotationBasic();
42824         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
42825             this._applyRotationBasic(this._basicRotation);
42826         }
42827         var animationSpeed = this._animationSpeed * (60 / fps);
42828         this._updateZoom(animationSpeed);
42829         this._updateLookat(animationSpeed);
42830         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
42831     };
42832     InteractiveWaitingState.prototype._getAlpha = function () {
42833         return this._motionless ? Math.round(this._alpha) : this._alpha;
42834     };
42835     InteractiveWaitingState.prototype._setCurrentCamera = function () {
42836         _super.prototype._setCurrentCamera.call(this);
42837         this._adjustCameras();
42838     };
42839     InteractiveWaitingState.prototype._adjustCameras = function () {
42840         if (this._previousNode == null) {
42841             return;
42842         }
42843         if (this._currentNode.fullPano) {
42844             var lookat = this._camera.lookat.clone().sub(this._camera.position);
42845             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
42846         }
42847         if (this._previousNode.fullPano) {
42848             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
42849             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
42850         }
42851     };
42852     return InteractiveWaitingState;
42853 }(State_1.InteractiveStateBase));
42854 exports.InteractiveWaitingState = InteractiveWaitingState;
42855 exports.default = InteractiveWaitingState;
42856
42857 },{"../../State":281}],418:[function(require,module,exports){
42858 "use strict";
42859 Object.defineProperty(exports, "__esModule", { value: true });
42860 var Error_1 = require("../../Error");
42861 var Geo_1 = require("../../Geo");
42862 var State_1 = require("../../State");
42863 var StateBase = /** @class */ (function () {
42864     function StateBase(state) {
42865         this._spatial = new Geo_1.Spatial();
42866         this._geoCoords = new Geo_1.GeoCoords();
42867         this._referenceThreshold = 0.01;
42868         this._transitionMode = state.transitionMode;
42869         this._reference = state.reference;
42870         this._alpha = state.alpha;
42871         this._camera = state.camera.clone();
42872         this._zoom = state.zoom;
42873         this._currentIndex = state.currentIndex;
42874         this._trajectory = state.trajectory.slice();
42875         this._trajectoryTransforms = [];
42876         this._trajectoryCameras = [];
42877         for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
42878             var node = _a[_i];
42879             var translation = this._nodeToTranslation(node, this._reference);
42880             var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image, undefined, node.ck1, node.ck2);
42881             this._trajectoryTransforms.push(transform);
42882             this._trajectoryCameras.push(new Geo_1.Camera(transform));
42883         }
42884         this._currentNode = this._trajectory.length > 0 ?
42885             this._trajectory[this._currentIndex] :
42886             null;
42887         this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
42888             this._trajectory[this._currentIndex - 1] :
42889             null;
42890         this._currentCamera = this._trajectoryCameras.length > 0 ?
42891             this._trajectoryCameras[this._currentIndex].clone() :
42892             new Geo_1.Camera();
42893         this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
42894             this._trajectoryCameras[this._currentIndex - 1].clone() :
42895             this._currentCamera.clone();
42896     }
42897     Object.defineProperty(StateBase.prototype, "reference", {
42898         get: function () {
42899             return this._reference;
42900         },
42901         enumerable: true,
42902         configurable: true
42903     });
42904     Object.defineProperty(StateBase.prototype, "alpha", {
42905         get: function () {
42906             return this._getAlpha();
42907         },
42908         enumerable: true,
42909         configurable: true
42910     });
42911     Object.defineProperty(StateBase.prototype, "camera", {
42912         get: function () {
42913             return this._camera;
42914         },
42915         enumerable: true,
42916         configurable: true
42917     });
42918     Object.defineProperty(StateBase.prototype, "zoom", {
42919         get: function () {
42920             return this._zoom;
42921         },
42922         enumerable: true,
42923         configurable: true
42924     });
42925     Object.defineProperty(StateBase.prototype, "trajectory", {
42926         get: function () {
42927             return this._trajectory;
42928         },
42929         enumerable: true,
42930         configurable: true
42931     });
42932     Object.defineProperty(StateBase.prototype, "currentIndex", {
42933         get: function () {
42934             return this._currentIndex;
42935         },
42936         enumerable: true,
42937         configurable: true
42938     });
42939     Object.defineProperty(StateBase.prototype, "currentNode", {
42940         get: function () {
42941             return this._currentNode;
42942         },
42943         enumerable: true,
42944         configurable: true
42945     });
42946     Object.defineProperty(StateBase.prototype, "previousNode", {
42947         get: function () {
42948             return this._previousNode;
42949         },
42950         enumerable: true,
42951         configurable: true
42952     });
42953     Object.defineProperty(StateBase.prototype, "currentCamera", {
42954         get: function () {
42955             return this._currentCamera;
42956         },
42957         enumerable: true,
42958         configurable: true
42959     });
42960     Object.defineProperty(StateBase.prototype, "currentTransform", {
42961         get: function () {
42962             return this._trajectoryTransforms.length > 0 ?
42963                 this._trajectoryTransforms[this.currentIndex] : null;
42964         },
42965         enumerable: true,
42966         configurable: true
42967     });
42968     Object.defineProperty(StateBase.prototype, "previousTransform", {
42969         get: function () {
42970             return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
42971                 this._trajectoryTransforms[this.currentIndex - 1] : null;
42972         },
42973         enumerable: true,
42974         configurable: true
42975     });
42976     Object.defineProperty(StateBase.prototype, "motionless", {
42977         get: function () {
42978             return this._motionless;
42979         },
42980         enumerable: true,
42981         configurable: true
42982     });
42983     Object.defineProperty(StateBase.prototype, "transitionMode", {
42984         get: function () {
42985             return this._transitionMode;
42986         },
42987         enumerable: true,
42988         configurable: true
42989     });
42990     StateBase.prototype.earth = function () { throw new Error("Not implemented"); };
42991     StateBase.prototype.traverse = function () { throw new Error("Not implemented"); };
42992     StateBase.prototype.wait = function () { throw new Error("Not implemented"); };
42993     StateBase.prototype.waitInteractively = function () { throw new Error("Not implemented"); };
42994     StateBase.prototype.move = function (delta) { };
42995     StateBase.prototype.moveTo = function (position) { };
42996     StateBase.prototype.rotate = function (delta) { };
42997     StateBase.prototype.rotateUnbounded = function (delta) { };
42998     StateBase.prototype.rotateWithoutInertia = function (delta) { };
42999     StateBase.prototype.rotateBasic = function (basicRotation) { };
43000     StateBase.prototype.rotateBasicUnbounded = function (basicRotation) { };
43001     StateBase.prototype.rotateBasicWithoutInertia = function (basicRotation) { };
43002     StateBase.prototype.rotateToBasic = function (basic) { };
43003     StateBase.prototype.setSpeed = function (speed) { };
43004     StateBase.prototype.zoomIn = function (delta, reference) { };
43005     StateBase.prototype.update = function (fps) { };
43006     StateBase.prototype.setCenter = function (center) { };
43007     StateBase.prototype.setZoom = function (zoom) { };
43008     StateBase.prototype.dolly = function (delta) { };
43009     StateBase.prototype.orbit = function (rotation) { };
43010     StateBase.prototype.truck = function (direction) { };
43011     StateBase.prototype.append = function (nodes) {
43012         if (nodes.length < 1) {
43013             throw Error("Trajectory can not be empty");
43014         }
43015         if (this._currentIndex < 0) {
43016             this.set(nodes);
43017         }
43018         else {
43019             this._trajectory = this._trajectory.concat(nodes);
43020             this._appendToTrajectories(nodes);
43021         }
43022     };
43023     StateBase.prototype.prepend = function (nodes) {
43024         if (nodes.length < 1) {
43025             throw Error("Trajectory can not be empty");
43026         }
43027         this._trajectory = nodes.slice().concat(this._trajectory);
43028         this._currentIndex += nodes.length;
43029         this._setCurrentNode();
43030         var referenceReset = this._setReference(this._currentNode);
43031         if (referenceReset) {
43032             this._setTrajectories();
43033         }
43034         else {
43035             this._prependToTrajectories(nodes);
43036         }
43037         this._setCurrentCamera();
43038     };
43039     StateBase.prototype.remove = function (n) {
43040         if (n < 0) {
43041             throw Error("n must be a positive integer");
43042         }
43043         if (this._currentIndex - 1 < n) {
43044             throw Error("Current and previous nodes can not be removed");
43045         }
43046         for (var i = 0; i < n; i++) {
43047             this._trajectory.shift();
43048             this._trajectoryTransforms.shift();
43049             this._trajectoryCameras.shift();
43050             this._currentIndex--;
43051         }
43052         this._setCurrentNode();
43053     };
43054     StateBase.prototype.clearPrior = function () {
43055         if (this._currentIndex > 0) {
43056             this.remove(this._currentIndex - 1);
43057         }
43058     };
43059     StateBase.prototype.clear = function () {
43060         this.cut();
43061         if (this._currentIndex > 0) {
43062             this.remove(this._currentIndex - 1);
43063         }
43064     };
43065     StateBase.prototype.cut = function () {
43066         while (this._trajectory.length - 1 > this._currentIndex) {
43067             this._trajectory.pop();
43068             this._trajectoryTransforms.pop();
43069             this._trajectoryCameras.pop();
43070         }
43071     };
43072     StateBase.prototype.set = function (nodes) {
43073         this._setTrajectory(nodes);
43074         this._setCurrentNode();
43075         this._setReference(this._currentNode);
43076         this._setTrajectories();
43077         this._setCurrentCamera();
43078     };
43079     StateBase.prototype.getCenter = function () {
43080         return this._currentNode != null ?
43081             this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
43082             [0.5, 0.5];
43083     };
43084     StateBase.prototype.setTransitionMode = function (mode) {
43085         this._transitionMode = mode;
43086     };
43087     StateBase.prototype._getAlpha = function () { return 1; };
43088     StateBase.prototype._setCurrent = function () {
43089         this._setCurrentNode();
43090         var referenceReset = this._setReference(this._currentNode);
43091         if (referenceReset) {
43092             this._setTrajectories();
43093         }
43094         this._setCurrentCamera();
43095     };
43096     StateBase.prototype._setCurrentCamera = function () {
43097         this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
43098         this._previousCamera = this._currentIndex > 0 ?
43099             this._trajectoryCameras[this._currentIndex - 1].clone() :
43100             this._currentCamera.clone();
43101     };
43102     StateBase.prototype._motionlessTransition = function () {
43103         var nodesSet = this._currentNode != null && this._previousNode != null;
43104         return nodesSet && (this._transitionMode === State_1.TransitionMode.Instantaneous || !(this._currentNode.merged &&
43105             this._previousNode.merged &&
43106             this._withinOriginalDistance() &&
43107             this._sameConnectedComponent()));
43108     };
43109     StateBase.prototype._setReference = function (node) {
43110         // do not reset reference if node is within threshold distance
43111         if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
43112             Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
43113             return false;
43114         }
43115         // do not reset reference if previous node exist and transition is with motion
43116         if (this._previousNode != null && !this._motionlessTransition()) {
43117             return false;
43118         }
43119         this._reference.lat = node.latLon.lat;
43120         this._reference.lon = node.latLon.lon;
43121         this._reference.alt = node.alt;
43122         return true;
43123     };
43124     StateBase.prototype._setCurrentNode = function () {
43125         this._currentNode = this._trajectory.length > 0 ?
43126             this._trajectory[this._currentIndex] :
43127             null;
43128         this._previousNode = this._currentIndex > 0 ?
43129             this._trajectory[this._currentIndex - 1] :
43130             null;
43131     };
43132     StateBase.prototype._setTrajectory = function (nodes) {
43133         if (nodes.length < 1) {
43134             throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
43135         }
43136         if (this._currentNode != null) {
43137             this._trajectory = [this._currentNode].concat(nodes);
43138             this._currentIndex = 1;
43139         }
43140         else {
43141             this._trajectory = nodes.slice();
43142             this._currentIndex = 0;
43143         }
43144     };
43145     StateBase.prototype._setTrajectories = function () {
43146         this._trajectoryTransforms.length = 0;
43147         this._trajectoryCameras.length = 0;
43148         this._appendToTrajectories(this._trajectory);
43149     };
43150     StateBase.prototype._appendToTrajectories = function (nodes) {
43151         for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
43152             var node = nodes_1[_i];
43153             if (!node.assetsCached) {
43154                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
43155             }
43156             var translation = this._nodeToTranslation(node, this.reference);
43157             var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image, undefined, node.ck1, node.ck2);
43158             this._trajectoryTransforms.push(transform);
43159             this._trajectoryCameras.push(new Geo_1.Camera(transform));
43160         }
43161     };
43162     StateBase.prototype._prependToTrajectories = function (nodes) {
43163         for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
43164             var node = _a[_i];
43165             if (!node.assetsCached) {
43166                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
43167             }
43168             var translation = this._nodeToTranslation(node, this.reference);
43169             var transform = new Geo_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.image, undefined, node.ck1, node.ck2);
43170             this._trajectoryTransforms.unshift(transform);
43171             this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
43172         }
43173     };
43174     StateBase.prototype._nodeToTranslation = function (node, reference) {
43175         return Geo_1.Geo.computeTranslation({ alt: node.alt, lat: node.latLon.lat, lon: node.latLon.lon }, node.rotation, reference);
43176     };
43177     StateBase.prototype._sameConnectedComponent = function () {
43178         var current = this._currentNode;
43179         var previous = this._previousNode;
43180         return !!current && !!previous &&
43181             current.mergeCC === previous.mergeCC;
43182     };
43183     StateBase.prototype._withinOriginalDistance = function () {
43184         var current = this._currentNode;
43185         var previous = this._previousNode;
43186         if (!current || !previous) {
43187             return true;
43188         }
43189         // 50 km/h moves 28m in 2s
43190         var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
43191         return distance < 25;
43192     };
43193     return StateBase;
43194 }());
43195 exports.StateBase = StateBase;
43196
43197 },{"../../Error":276,"../../Geo":277,"../../State":281}],419:[function(require,module,exports){
43198 "use strict";
43199 var __extends = (this && this.__extends) || (function () {
43200     var extendStatics = function (d, b) {
43201         extendStatics = Object.setPrototypeOf ||
43202             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43203             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
43204         return extendStatics(d, b);
43205     }
43206     return function (d, b) {
43207         extendStatics(d, b);
43208         function __() { this.constructor = d; }
43209         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43210     };
43211 })();
43212 Object.defineProperty(exports, "__esModule", { value: true });
43213 var UnitBezier = require("@mapbox/unitbezier");
43214 var State_1 = require("../../State");
43215 var TraversingState = /** @class */ (function (_super) {
43216     __extends(TraversingState, _super);
43217     function TraversingState(state) {
43218         var _this = _super.call(this, state) || this;
43219         _this._adjustCameras();
43220         _this._motionless = _this._motionlessTransition();
43221         _this._baseAlpha = _this._alpha;
43222         _this._speedCoefficient = 1;
43223         _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
43224         _this._useBezier = false;
43225         return _this;
43226     }
43227     TraversingState.prototype.earth = function () {
43228         return new State_1.EarthState(this);
43229     };
43230     TraversingState.prototype.wait = function () {
43231         return new State_1.WaitingState(this);
43232     };
43233     TraversingState.prototype.waitInteractively = function () {
43234         return new State_1.InteractiveWaitingState(this);
43235     };
43236     TraversingState.prototype.append = function (nodes) {
43237         var emptyTrajectory = this._trajectory.length === 0;
43238         if (emptyTrajectory) {
43239             this._resetTransition();
43240         }
43241         _super.prototype.append.call(this, nodes);
43242         if (emptyTrajectory) {
43243             this._setDesiredCenter();
43244             this._setDesiredZoom();
43245         }
43246     };
43247     TraversingState.prototype.prepend = function (nodes) {
43248         var emptyTrajectory = this._trajectory.length === 0;
43249         if (emptyTrajectory) {
43250             this._resetTransition();
43251         }
43252         _super.prototype.prepend.call(this, nodes);
43253         if (emptyTrajectory) {
43254             this._setDesiredCenter();
43255             this._setDesiredZoom();
43256         }
43257     };
43258     TraversingState.prototype.set = function (nodes) {
43259         _super.prototype.set.call(this, nodes);
43260         this._desiredLookat = null;
43261         this._resetTransition();
43262         this._clearRotation();
43263         this._setDesiredCenter();
43264         this._setDesiredZoom();
43265         if (this._trajectory.length < 3) {
43266             this._useBezier = true;
43267         }
43268     };
43269     TraversingState.prototype.setSpeed = function (speed) {
43270         this._speedCoefficient = this._spatial.clamp(speed, 0, 10);
43271     };
43272     TraversingState.prototype.update = function (fps) {
43273         if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
43274             this._currentIndex += 1;
43275             this._useBezier = this._trajectory.length < 3 &&
43276                 this._currentIndex + 1 === this._trajectory.length;
43277             this._setCurrent();
43278             this._resetTransition();
43279             this._clearRotation();
43280             this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
43281             this._desiredLookat = null;
43282         }
43283         var animationSpeed = this._animationSpeed * (60 / fps);
43284         this._baseAlpha = Math.min(1, this._baseAlpha + this._speedCoefficient * animationSpeed);
43285         if (this._useBezier) {
43286             this._alpha = this._unitBezier.solve(this._baseAlpha);
43287         }
43288         else {
43289             this._alpha = this._baseAlpha;
43290         }
43291         this._updateRotation();
43292         if (!this._rotationDelta.isZero) {
43293             this._applyRotation(this._rotationDelta, this._previousCamera);
43294             this._applyRotation(this._rotationDelta, this._currentCamera);
43295         }
43296         this._updateRotationBasic();
43297         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
43298             this._applyRotationBasic(this._basicRotation);
43299         }
43300         this._updateZoom(animationSpeed);
43301         this._updateLookat(animationSpeed);
43302         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
43303     };
43304     TraversingState.prototype._getAlpha = function () {
43305         return this._motionless ? Math.ceil(this._alpha) : this._alpha;
43306     };
43307     TraversingState.prototype._setCurrentCamera = function () {
43308         _super.prototype._setCurrentCamera.call(this);
43309         this._adjustCameras();
43310     };
43311     TraversingState.prototype._adjustCameras = function () {
43312         if (this._previousNode == null) {
43313             return;
43314         }
43315         var lookat = this._camera.lookat.clone().sub(this._camera.position);
43316         this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
43317         if (this._currentNode.fullPano) {
43318             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
43319         }
43320     };
43321     TraversingState.prototype._resetTransition = function () {
43322         this._alpha = 0;
43323         this._baseAlpha = 0;
43324         this._motionless = this._motionlessTransition();
43325     };
43326     return TraversingState;
43327 }(State_1.InteractiveStateBase));
43328 exports.TraversingState = TraversingState;
43329 exports.default = TraversingState;
43330
43331 },{"../../State":281,"@mapbox/unitbezier":2}],420:[function(require,module,exports){
43332 "use strict";
43333 var __extends = (this && this.__extends) || (function () {
43334     var extendStatics = function (d, b) {
43335         extendStatics = Object.setPrototypeOf ||
43336             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43337             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
43338         return extendStatics(d, b);
43339     }
43340     return function (d, b) {
43341         extendStatics(d, b);
43342         function __() { this.constructor = d; }
43343         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43344     };
43345 })();
43346 Object.defineProperty(exports, "__esModule", { value: true });
43347 var State_1 = require("../../State");
43348 var WaitingState = /** @class */ (function (_super) {
43349     __extends(WaitingState, _super);
43350     function WaitingState(state) {
43351         var _this = _super.call(this, state) || this;
43352         _this._zoom = 0;
43353         _this._adjustCameras();
43354         _this._motionless = _this._motionlessTransition();
43355         return _this;
43356     }
43357     WaitingState.prototype.traverse = function () {
43358         return new State_1.TraversingState(this);
43359     };
43360     WaitingState.prototype.waitInteractively = function () {
43361         return new State_1.InteractiveWaitingState(this);
43362     };
43363     WaitingState.prototype.prepend = function (nodes) {
43364         _super.prototype.prepend.call(this, nodes);
43365         this._motionless = this._motionlessTransition();
43366     };
43367     WaitingState.prototype.set = function (nodes) {
43368         _super.prototype.set.call(this, nodes);
43369         this._motionless = this._motionlessTransition();
43370     };
43371     WaitingState.prototype.move = function (delta) {
43372         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
43373     };
43374     WaitingState.prototype.moveTo = function (position) {
43375         this._alpha = Math.max(0, Math.min(1, position));
43376     };
43377     WaitingState.prototype.update = function (fps) {
43378         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
43379     };
43380     WaitingState.prototype._getAlpha = function () {
43381         return this._motionless ? Math.round(this._alpha) : this._alpha;
43382     };
43383     WaitingState.prototype._setCurrentCamera = function () {
43384         _super.prototype._setCurrentCamera.call(this);
43385         this._adjustCameras();
43386     };
43387     WaitingState.prototype._adjustCameras = function () {
43388         if (this._previousNode == null) {
43389             return;
43390         }
43391         if (this._currentNode.fullPano) {
43392             var lookat = this._camera.lookat.clone().sub(this._camera.position);
43393             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
43394         }
43395         if (this._previousNode.fullPano) {
43396             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
43397             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
43398         }
43399     };
43400     return WaitingState;
43401 }(State_1.StateBase));
43402 exports.WaitingState = WaitingState;
43403 exports.default = WaitingState;
43404
43405 },{"../../State":281}],421:[function(require,module,exports){
43406 "use strict";
43407 Object.defineProperty(exports, "__esModule", { value: true });
43408 var rxjs_1 = require("rxjs");
43409 /**
43410  * @class ImageTileLoader
43411  *
43412  * @classdesc Represents a loader of image tiles.
43413  */
43414 var ImageTileLoader = /** @class */ (function () {
43415     /**
43416      * Create a new node image tile loader instance.
43417      *
43418      * @param {string} scheme - The URI scheme.
43419      * @param {string} host - The URI host.
43420      * @param {string} [origin] - The origin query param.
43421      */
43422     function ImageTileLoader(scheme, host, origin) {
43423         this._scheme = scheme;
43424         this._host = host;
43425         this._origin = origin != null ? "?origin=" + origin : "";
43426     }
43427     /**
43428      * Retrieve an image tile.
43429      *
43430      * @description Retrieve an image tile by specifying the area
43431      * as well as the scaled size.
43432      *
43433      * @param {string} identifier - The identifier of the image.
43434      * @param {number} x - The top left x pixel coordinate for the tile
43435      * in the original image.
43436      * @param {number} y - The top left y pixel coordinate for the tile
43437      * in the original image.
43438      * @param {number} w - The pixel width of the tile in the original image.
43439      * @param {number} h - The pixel height of the tile in the original image.
43440      * @param {number} scaledW - The scaled width of the returned tile.
43441      * @param {number} scaledH - The scaled height of the returned tile.
43442      */
43443     ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
43444         var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
43445         var url = this._scheme +
43446             "://" +
43447             this._host +
43448             characteristics +
43449             this._origin;
43450         var xmlHTTP = null;
43451         return [rxjs_1.Observable.create(function (subscriber) {
43452                 xmlHTTP = new XMLHttpRequest();
43453                 xmlHTTP.open("GET", url, true);
43454                 xmlHTTP.responseType = "arraybuffer";
43455                 xmlHTTP.timeout = 15000;
43456                 xmlHTTP.onload = function (event) {
43457                     if (xmlHTTP.status !== 200) {
43458                         subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
43459                             ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
43460                         return;
43461                     }
43462                     var image = new Image();
43463                     image.crossOrigin = "Anonymous";
43464                     image.onload = function (e) {
43465                         subscriber.next(image);
43466                         subscriber.complete();
43467                     };
43468                     image.onerror = function (error) {
43469                         subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
43470                     };
43471                     var blob = new Blob([xmlHTTP.response]);
43472                     image.src = window.URL.createObjectURL(blob);
43473                 };
43474                 xmlHTTP.onerror = function (error) {
43475                     subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
43476                 };
43477                 xmlHTTP.ontimeout = function (error) {
43478                     subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
43479                 };
43480                 xmlHTTP.onabort = function (event) {
43481                     subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
43482                 };
43483                 xmlHTTP.send(null);
43484             }),
43485             function () {
43486                 if (xmlHTTP != null) {
43487                     xmlHTTP.abort();
43488                 }
43489             },
43490         ];
43491     };
43492     return ImageTileLoader;
43493 }());
43494 exports.ImageTileLoader = ImageTileLoader;
43495 exports.default = ImageTileLoader;
43496
43497 },{"rxjs":26}],422:[function(require,module,exports){
43498 "use strict";
43499 Object.defineProperty(exports, "__esModule", { value: true });
43500 /**
43501  * @class ImageTileStore
43502  *
43503  * @classdesc Represents a store for image tiles.
43504  */
43505 var ImageTileStore = /** @class */ (function () {
43506     /**
43507      * Create a new node image tile store instance.
43508      */
43509     function ImageTileStore() {
43510         this._images = {};
43511     }
43512     /**
43513      * Add an image tile to the store.
43514      *
43515      * @param {HTMLImageElement} image - The image tile.
43516      * @param {string} key - The identifier for the tile.
43517      * @param {number} level - The level of the tile.
43518      */
43519     ImageTileStore.prototype.addImage = function (image, key, level) {
43520         if (!(level in this._images)) {
43521             this._images[level] = {};
43522         }
43523         this._images[level][key] = image;
43524     };
43525     /**
43526      * Dispose the store.
43527      *
43528      * @description Disposes all cached assets.
43529      */
43530     ImageTileStore.prototype.dispose = function () {
43531         for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
43532             var level = _a[_i];
43533             var levelImages = this._images[level];
43534             for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
43535                 var key = _c[_b];
43536                 window.URL.revokeObjectURL(levelImages[key].src);
43537                 delete levelImages[key];
43538             }
43539             delete this._images[level];
43540         }
43541     };
43542     /**
43543      * Get an image tile from the store.
43544      *
43545      * @param {string} key - The identifier for the tile.
43546      * @param {number} level - The level of the tile.
43547      */
43548     ImageTileStore.prototype.getImage = function (key, level) {
43549         return this._images[level][key];
43550     };
43551     /**
43552      * Check if an image tile exist in the store.
43553      *
43554      * @param {string} key - The identifier for the tile.
43555      * @param {number} level - The level of the tile.
43556      */
43557     ImageTileStore.prototype.hasImage = function (key, level) {
43558         return level in this._images && key in this._images[level];
43559     };
43560     return ImageTileStore;
43561 }());
43562 exports.ImageTileStore = ImageTileStore;
43563 exports.default = ImageTileStore;
43564
43565 },{}],423:[function(require,module,exports){
43566 "use strict";
43567 Object.defineProperty(exports, "__esModule", { value: true });
43568 var Geo_1 = require("../Geo");
43569 /**
43570  * @class RegionOfInterestCalculator
43571  *
43572  * @classdesc Represents a calculator for regions of interest.
43573  */
43574 var RegionOfInterestCalculator = /** @class */ (function () {
43575     function RegionOfInterestCalculator() {
43576         this._viewportCoords = new Geo_1.ViewportCoords();
43577     }
43578     /**
43579      * Compute a region of interest based on the current render camera
43580      * and the viewport size.
43581      *
43582      * @param {RenderCamera} renderCamera - Render camera used for unprojections.
43583      * @param {ISize} size - Viewport size in pixels.
43584      * @param {Transform} transform - Transform used for projections.
43585      *
43586      * @returns {IRegionOfInterest} A region of interest.
43587      */
43588     RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
43589         var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
43590         var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
43591         this._clipBoundingBox(bbox);
43592         var viewportPixelWidth = 2 / size.width;
43593         var viewportPixelHeight = 2 / size.height;
43594         var centralViewportPixel = [
43595             [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
43596             [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
43597             [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
43598             [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
43599         ];
43600         var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
43601         return {
43602             bbox: bbox,
43603             pixelHeight: cpbox.maxY - cpbox.minY,
43604             pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
43605         };
43606     };
43607     RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
43608         var points = [];
43609         var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
43610         var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
43611         for (var side = 0; side < 4; ++side) {
43612             var o = os[side];
43613             var d = ds[side];
43614             for (var i = 0; i < pointsPerSide; ++i) {
43615                 points.push([o[0] + d[0] * i / pointsPerSide,
43616                     o[1] + d[1] * i / pointsPerSide]);
43617             }
43618         }
43619         return points;
43620     };
43621     RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
43622         var _this = this;
43623         var basicPoints = viewportPoints
43624             .map(function (point) {
43625             return _this._viewportCoords
43626                 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
43627         });
43628         if (transform.gpano != null) {
43629             return this._boundingBoxPano(basicPoints);
43630         }
43631         else {
43632             return this._boundingBox(basicPoints);
43633         }
43634     };
43635     RegionOfInterestCalculator.prototype._boundingBox = function (points) {
43636         var bbox = {
43637             maxX: Number.NEGATIVE_INFINITY,
43638             maxY: Number.NEGATIVE_INFINITY,
43639             minX: Number.POSITIVE_INFINITY,
43640             minY: Number.POSITIVE_INFINITY,
43641         };
43642         for (var i = 0; i < points.length; ++i) {
43643             bbox.minX = Math.min(bbox.minX, points[i][0]);
43644             bbox.maxX = Math.max(bbox.maxX, points[i][0]);
43645             bbox.minY = Math.min(bbox.minY, points[i][1]);
43646             bbox.maxY = Math.max(bbox.maxY, points[i][1]);
43647         }
43648         return bbox;
43649     };
43650     RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
43651         var _this = this;
43652         var xs = [];
43653         var ys = [];
43654         for (var i = 0; i < points.length; ++i) {
43655             xs.push(points[i][0]);
43656             ys.push(points[i][1]);
43657         }
43658         xs.sort(function (a, b) { return _this._sign(a - b); });
43659         ys.sort(function (a, b) { return _this._sign(a - b); });
43660         var intervalX = this._intervalPano(xs);
43661         return {
43662             maxX: intervalX[1],
43663             maxY: ys[ys.length - 1],
43664             minX: intervalX[0],
43665             minY: ys[0],
43666         };
43667     };
43668     /**
43669      * Find the max interval between consecutive numbers.
43670      * Assumes numbers are between 0 and 1, sorted and that
43671      * x is equivalent to x + 1.
43672      */
43673     RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
43674         var maxdx = 0;
43675         var maxi = -1;
43676         for (var i = 0; i < xs.length - 1; ++i) {
43677             var dx = xs[i + 1] - xs[i];
43678             if (dx > maxdx) {
43679                 maxdx = dx;
43680                 maxi = i;
43681             }
43682         }
43683         var loopdx = xs[0] + 1 - xs[xs.length - 1];
43684         if (loopdx > maxdx) {
43685             return [xs[0], xs[xs.length - 1]];
43686         }
43687         else {
43688             return [xs[maxi + 1], xs[maxi]];
43689         }
43690     };
43691     RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
43692         bbox.minX = Math.max(0, Math.min(1, bbox.minX));
43693         bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
43694         bbox.minY = Math.max(0, Math.min(1, bbox.minY));
43695         bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
43696     };
43697     RegionOfInterestCalculator.prototype._sign = function (n) {
43698         return n > 0 ? 1 : n < 0 ? -1 : 0;
43699     };
43700     return RegionOfInterestCalculator;
43701 }());
43702 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
43703 exports.default = RegionOfInterestCalculator;
43704
43705 },{"../Geo":277}],424:[function(require,module,exports){
43706 "use strict";
43707 Object.defineProperty(exports, "__esModule", { value: true });
43708 var operators_1 = require("rxjs/operators");
43709 var THREE = require("three");
43710 var rxjs_1 = require("rxjs");
43711 /**
43712  * @class TextureProvider
43713  *
43714  * @classdesc Represents a provider of textures.
43715  */
43716 var TextureProvider = /** @class */ (function () {
43717     /**
43718      * Create a new node texture provider instance.
43719      *
43720      * @param {string} key - The identifier of the image for which to request tiles.
43721      * @param {number} width - The full width of the original image.
43722      * @param {number} height - The full height of the original image.
43723      * @param {number} tileSize - The size used when requesting tiles.
43724      * @param {HTMLImageElement} background - Image to use as background.
43725      * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
43726      * @param {ImageTileStore} imageTileStore - Store for saving tiles.
43727      * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
43728      */
43729     function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
43730         this._disposed = false;
43731         this._key = key;
43732         if (width <= 0 || height <= 0) {
43733             console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
43734         }
43735         this._width = width;
43736         this._height = height;
43737         this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
43738         this._currentLevel = -1;
43739         this._tileSize = tileSize;
43740         this._updated$ = new rxjs_1.Subject();
43741         this._createdSubject$ = new rxjs_1.Subject();
43742         this._created$ = this._createdSubject$.pipe(operators_1.publishReplay(1), operators_1.refCount());
43743         this._createdSubscription = this._created$.subscribe(function () { });
43744         this._hasSubject$ = new rxjs_1.Subject();
43745         this._has$ = this._hasSubject$.pipe(operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
43746         this._hasSubscription = this._has$.subscribe(function () { });
43747         this._abortFunctions = [];
43748         this._tileSubscriptions = {};
43749         this._renderedCurrentLevelTiles = {};
43750         this._renderedTiles = {};
43751         this._background = background;
43752         this._camera = null;
43753         this._imageTileLoader = imageTileLoader;
43754         this._imageTileStore = imageTileStore;
43755         this._renderer = renderer;
43756         this._renderTarget = null;
43757         this._roi = null;
43758     }
43759     Object.defineProperty(TextureProvider.prototype, "disposed", {
43760         /**
43761          * Get disposed.
43762          *
43763          * @returns {boolean} Value indicating whether provider has
43764          * been disposed.
43765          */
43766         get: function () {
43767             return this._disposed;
43768         },
43769         enumerable: true,
43770         configurable: true
43771     });
43772     Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
43773         /**
43774          * Get hasTexture$.
43775          *
43776          * @returns {Observable<boolean>} Observable emitting
43777          * values indicating when the existance of a texture
43778          * changes.
43779          */
43780         get: function () {
43781             return this._has$;
43782         },
43783         enumerable: true,
43784         configurable: true
43785     });
43786     Object.defineProperty(TextureProvider.prototype, "key", {
43787         /**
43788          * Get key.
43789          *
43790          * @returns {boolean} The identifier of the image for
43791          * which to render textures.
43792          */
43793         get: function () {
43794             return this._key;
43795         },
43796         enumerable: true,
43797         configurable: true
43798     });
43799     Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
43800         /**
43801          * Get textureUpdated$.
43802          *
43803          * @returns {Observable<boolean>} Observable emitting
43804          * values when an existing texture has been updated.
43805          */
43806         get: function () {
43807             return this._updated$;
43808         },
43809         enumerable: true,
43810         configurable: true
43811     });
43812     Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
43813         /**
43814          * Get textureCreated$.
43815          *
43816          * @returns {Observable<boolean>} Observable emitting
43817          * values when a new texture has been created.
43818          */
43819         get: function () {
43820             return this._created$;
43821         },
43822         enumerable: true,
43823         configurable: true
43824     });
43825     /**
43826      * Abort all outstanding image tile requests.
43827      */
43828     TextureProvider.prototype.abort = function () {
43829         for (var key in this._tileSubscriptions) {
43830             if (!this._tileSubscriptions.hasOwnProperty(key)) {
43831                 continue;
43832             }
43833             this._tileSubscriptions[key].unsubscribe();
43834         }
43835         this._tileSubscriptions = {};
43836         for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
43837             var abort = _a[_i];
43838             abort();
43839         }
43840         this._abortFunctions = [];
43841     };
43842     /**
43843      * Dispose the provider.
43844      *
43845      * @description Disposes all cached assets and
43846      * aborts all outstanding image tile requests.
43847      */
43848     TextureProvider.prototype.dispose = function () {
43849         if (this._disposed) {
43850             console.warn("Texture already disposed (" + this._key + ")");
43851             return;
43852         }
43853         this.abort();
43854         if (this._renderTarget != null) {
43855             this._renderTarget.dispose();
43856             this._renderTarget = null;
43857         }
43858         this._imageTileStore.dispose();
43859         this._imageTileStore = null;
43860         this._background = null;
43861         this._camera = null;
43862         this._imageTileLoader = null;
43863         this._renderer = null;
43864         this._roi = null;
43865         this._createdSubscription.unsubscribe();
43866         this._hasSubscription.unsubscribe();
43867         this._disposed = true;
43868     };
43869     /**
43870      * Set the region of interest.
43871      *
43872      * @description When the region of interest is set the
43873      * the tile level is determined and tiles for the region
43874      * are fetched from the store or the loader and renderedLevel
43875      * to the texture.
43876      *
43877      * @param {IRegionOfInterest} roi - Spatial edges to cache.
43878      */
43879     TextureProvider.prototype.setRegionOfInterest = function (roi) {
43880         if (this._width <= 0 || this._height <= 0) {
43881             return;
43882         }
43883         this._roi = roi;
43884         var width = 1 / this._roi.pixelWidth;
43885         var height = 1 / this._roi.pixelHeight;
43886         var size = Math.max(height, width);
43887         var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.ceil(Math.log(size) / Math.log(2))));
43888         if (currentLevel !== this._currentLevel) {
43889             this.abort();
43890             this._currentLevel = currentLevel;
43891             if (!(this._currentLevel in this._renderedTiles)) {
43892                 this._renderedTiles[this._currentLevel] = [];
43893             }
43894             this._renderedCurrentLevelTiles = {};
43895             for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
43896                 var tile = _a[_i];
43897                 this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
43898             }
43899         }
43900         var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
43901         var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
43902         var tiles = this._getTiles(topLeft, bottomRight);
43903         if (this._camera == null) {
43904             this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
43905             this._camera.position.z = 1;
43906             var gl = this._renderer.getContext();
43907             var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
43908             var backgroundSize = Math.max(this._width, this._height);
43909             var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
43910             var targetWidth = Math.floor(scale * this._width);
43911             var targetHeight = Math.floor(scale * this._height);
43912             this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
43913                 depthBuffer: false,
43914                 format: THREE.RGBFormat,
43915                 magFilter: THREE.LinearFilter,
43916                 minFilter: THREE.LinearFilter,
43917                 stencilBuffer: false,
43918             });
43919             this._renderToTarget(0, 0, this._width, this._height, this._background);
43920             this._createdSubject$.next(this._renderTarget.texture);
43921             this._hasSubject$.next(true);
43922         }
43923         this._fetchTiles(tiles);
43924     };
43925     TextureProvider.prototype.setTileSize = function (tileSize) {
43926         this._tileSize = tileSize;
43927     };
43928     /**
43929      * Update the image used as background for the texture.
43930      *
43931      * @param {HTMLImageElement} background - The background image.
43932      */
43933     TextureProvider.prototype.updateBackground = function (background) {
43934         this._background = background;
43935     };
43936     /**
43937      * Retrieve an image tile.
43938      *
43939      * @description Retrieve an image tile and render it to the
43940      * texture. Add the tile to the store and emit to the updated
43941      * observable.
43942      *
43943      * @param {Array<number>} tile - The tile coordinates.
43944      * @param {number} level - The tile level.
43945      * @param {number} x - The top left x pixel coordinate of the tile.
43946      * @param {number} y - The top left y pixel coordinate of the tile.
43947      * @param {number} w - The pixel width of the tile.
43948      * @param {number} h - The pixel height of the tile.
43949      * @param {number} scaledW - The scaled width of the returned tile.
43950      * @param {number} scaledH - The scaled height of the returned tile.
43951      */
43952     TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
43953         var _this = this;
43954         var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
43955         var tile$ = getTile[0];
43956         var abort = getTile[1];
43957         this._abortFunctions.push(abort);
43958         var tileKey = this._tileKey(this._tileSize, tile);
43959         var subscription = tile$
43960             .subscribe(function (image) {
43961             _this._renderToTarget(x, y, w, h, image);
43962             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
43963             _this._removeFromArray(abort, _this._abortFunctions);
43964             _this._setTileRendered(tile, _this._currentLevel);
43965             _this._imageTileStore.addImage(image, tileKey, level);
43966             _this._updated$.next(true);
43967         }, function (error) {
43968             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
43969             _this._removeFromArray(abort, _this._abortFunctions);
43970             console.error(error);
43971         });
43972         if (!subscription.closed) {
43973             this._tileSubscriptions[tileKey] = subscription;
43974         }
43975     };
43976     /**
43977      * Retrieve image tiles.
43978      *
43979      * @description Retrieve a image tiles and render them to the
43980      * texture. Retrieve from store if it exists, otherwise Retrieve
43981      * from loader.
43982      *
43983      * @param {Array<Array<number>>} tiles - Array of tile coordinates to
43984      * retrieve.
43985      */
43986     TextureProvider.prototype._fetchTiles = function (tiles) {
43987         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
43988         for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
43989             var tile = tiles_1[_i];
43990             var tileKey = this._tileKey(this._tileSize, tile);
43991             if (tileKey in this._renderedCurrentLevelTiles ||
43992                 tileKey in this._tileSubscriptions) {
43993                 continue;
43994             }
43995             var tileX = tileSize * tile[0];
43996             var tileY = tileSize * tile[1];
43997             var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
43998             var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
43999             if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
44000                 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
44001                 this._setTileRendered(tile, this._currentLevel);
44002                 this._updated$.next(true);
44003                 continue;
44004             }
44005             var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
44006             var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
44007             this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
44008         }
44009     };
44010     /**
44011      * Get tile coordinates for a point using the current level.
44012      *
44013      * @param {Array<number>} point - Point in basic coordinates.
44014      *
44015      * @returns {Array<number>} x and y tile coodinates.
44016      */
44017     TextureProvider.prototype._getTileCoords = function (point) {
44018         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
44019         var maxX = Math.ceil(this._width / tileSize) - 1;
44020         var maxY = Math.ceil(this._height / tileSize) - 1;
44021         return [
44022             Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
44023             Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
44024         ];
44025     };
44026     /**
44027      * Get tile coordinates for all tiles contained in a bounding
44028      * box.
44029      *
44030      * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
44031      * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
44032      *
44033      * @returns {Array<Array<number>>} Array of x, y tile coodinates.
44034      */
44035     TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
44036         var xs = [];
44037         if (topLeft[0] > bottomRight[0]) {
44038             var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
44039             var maxX = Math.ceil(this._width / tileSize) - 1;
44040             for (var x = topLeft[0]; x <= maxX; x++) {
44041                 xs.push(x);
44042             }
44043             for (var x = 0; x <= bottomRight[0]; x++) {
44044                 xs.push(x);
44045             }
44046         }
44047         else {
44048             for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
44049                 xs.push(x);
44050             }
44051         }
44052         var tiles = [];
44053         for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
44054             var x = xs_1[_i];
44055             for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
44056                 tiles.push([x, y]);
44057             }
44058         }
44059         return tiles;
44060     };
44061     /**
44062      * Remove an item from an array if it exists in array.
44063      *
44064      * @param {T} item - Item to remove.
44065      * @param {Array<T>} array - Array from which item should be removed.
44066      */
44067     TextureProvider.prototype._removeFromArray = function (item, array) {
44068         var index = array.indexOf(item);
44069         if (index !== -1) {
44070             array.splice(index, 1);
44071         }
44072     };
44073     /**
44074      * Remove an item from a dictionary.
44075      *
44076      * @param {string} key - Key of the item to remove.
44077      * @param {Object} dict - Dictionary from which item should be removed.
44078      */
44079     TextureProvider.prototype._removeFromDictionary = function (key, dict) {
44080         if (key in dict) {
44081             delete dict[key];
44082         }
44083     };
44084     /**
44085      * Render an image tile to the target texture.
44086      *
44087      * @param {number} x - The top left x pixel coordinate of the tile.
44088      * @param {number} y - The top left y pixel coordinate of the tile.
44089      * @param {number} w - The pixel width of the tile.
44090      * @param {number} h - The pixel height of the tile.
44091      * @param {HTMLImageElement} background - The image tile to render.
44092      */
44093     TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
44094         var texture = new THREE.Texture(image);
44095         texture.minFilter = THREE.LinearFilter;
44096         texture.needsUpdate = true;
44097         var geometry = new THREE.PlaneGeometry(w, h);
44098         var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
44099         var mesh = new THREE.Mesh(geometry, material);
44100         mesh.position.x = -this._width / 2 + x + w / 2;
44101         mesh.position.y = this._height / 2 - y - h / 2;
44102         var scene = new THREE.Scene();
44103         scene.add(mesh);
44104         this._renderer.render(scene, this._camera, this._renderTarget);
44105         this._renderer.setRenderTarget(undefined);
44106         scene.remove(mesh);
44107         geometry.dispose();
44108         material.dispose();
44109         texture.dispose();
44110     };
44111     /**
44112      * Mark a tile as rendered.
44113      *
44114      * @description Clears tiles marked as rendered in other
44115      * levels of the tile pyramid  if they were rendered on
44116      * top of or below the tile.
44117      *
44118      * @param {Arrary<number>} tile - The tile coordinates.
44119      * @param {number} level - Tile level of the tile coordinates.
44120      */
44121     TextureProvider.prototype._setTileRendered = function (tile, level) {
44122         var otherLevels = Object.keys(this._renderedTiles)
44123             .map(function (key) {
44124             return parseInt(key, 10);
44125         })
44126             .filter(function (renderedLevel) {
44127             return renderedLevel !== level;
44128         });
44129         for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
44130             var otherLevel = otherLevels_1[_i];
44131             var scale = Math.pow(2, otherLevel - level);
44132             if (otherLevel < level) {
44133                 var x = Math.floor(scale * tile[0]);
44134                 var y = Math.floor(scale * tile[1]);
44135                 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
44136                     var otherTile = _b[_a];
44137                     if (otherTile[0] === x && otherTile[1] === y) {
44138                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
44139                         this._renderedTiles[otherLevel].splice(index, 1);
44140                     }
44141                 }
44142             }
44143             else {
44144                 var startX = scale * tile[0];
44145                 var endX = startX + scale - 1;
44146                 var startY = scale * tile[1];
44147                 var endY = startY + scale - 1;
44148                 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
44149                     var otherTile = _d[_c];
44150                     if (otherTile[0] >= startX && otherTile[0] <= endX &&
44151                         otherTile[1] >= startY && otherTile[1] <= endY) {
44152                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
44153                         this._renderedTiles[otherLevel].splice(index, 1);
44154                     }
44155                 }
44156             }
44157             if (this._renderedTiles[otherLevel].length === 0) {
44158                 delete this._renderedTiles[otherLevel];
44159             }
44160         }
44161         this._renderedTiles[level].push(tile);
44162         this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
44163     };
44164     /**
44165      * Create a tile key from a tile coordinates.
44166      *
44167      * @description Tile keys are used as a hash for
44168      * storing the tile in a dictionary.
44169      *
44170      * @param {number} tileSize - The tile size.
44171      * @param {Arrary<number>} tile - The tile coordinates.
44172      */
44173     TextureProvider.prototype._tileKey = function (tileSize, tile) {
44174         return tileSize + "-" + tile[0] + "-" + tile[1];
44175     };
44176     return TextureProvider;
44177 }());
44178 exports.TextureProvider = TextureProvider;
44179 exports.default = TextureProvider;
44180
44181 },{"rxjs":26,"rxjs/operators":224,"three":225}],425:[function(require,module,exports){
44182 "use strict";
44183 Object.defineProperty(exports, "__esModule", { value: true });
44184 var DOM = /** @class */ (function () {
44185     function DOM(doc) {
44186         this._document = !!doc ? doc : document;
44187     }
44188     Object.defineProperty(DOM.prototype, "document", {
44189         get: function () {
44190             return this._document;
44191         },
44192         enumerable: true,
44193         configurable: true
44194     });
44195     DOM.prototype.createElement = function (tagName, className, container) {
44196         var element = this._document.createElement(tagName);
44197         if (!!className) {
44198             element.className = className;
44199         }
44200         if (!!container) {
44201             container.appendChild(element);
44202         }
44203         return element;
44204     };
44205     return DOM;
44206 }());
44207 exports.DOM = DOM;
44208 exports.default = DOM;
44209
44210 },{}],426:[function(require,module,exports){
44211 "use strict";
44212 Object.defineProperty(exports, "__esModule", { value: true });
44213 var EventEmitter = /** @class */ (function () {
44214     function EventEmitter() {
44215         this._events = {};
44216     }
44217     /**
44218      * Subscribe to an event by its name.
44219      * @param {string }eventType - The name of the event to subscribe to.
44220      * @param {any} fn - The handler called when the event occurs.
44221      */
44222     EventEmitter.prototype.on = function (eventType, fn) {
44223         this._events[eventType] = this._events[eventType] || [];
44224         this._events[eventType].push(fn);
44225         return;
44226     };
44227     /**
44228      * Unsubscribe from an event by its name.
44229      * @param {string} eventType - The name of the event to subscribe to.
44230      * @param {any} fn - The handler to remove.
44231      */
44232     EventEmitter.prototype.off = function (eventType, fn) {
44233         if (!eventType) {
44234             this._events = {};
44235             return;
44236         }
44237         if (!this._listens(eventType)) {
44238             var idx = this._events[eventType].indexOf(fn);
44239             if (idx >= 0) {
44240                 this._events[eventType].splice(idx, 1);
44241             }
44242             if (this._events[eventType].length) {
44243                 delete this._events[eventType];
44244             }
44245         }
44246         else {
44247             delete this._events[eventType];
44248         }
44249         return;
44250     };
44251     EventEmitter.prototype.fire = function (eventType, data) {
44252         if (!this._listens(eventType)) {
44253             return;
44254         }
44255         for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
44256             var fn = _a[_i];
44257             fn.call(this, data);
44258         }
44259         return;
44260     };
44261     EventEmitter.prototype._listens = function (eventType) {
44262         return !!(this._events && this._events[eventType]);
44263     };
44264     return EventEmitter;
44265 }());
44266 exports.EventEmitter = EventEmitter;
44267 exports.default = EventEmitter;
44268
44269 },{}],427:[function(require,module,exports){
44270 "use strict";
44271 Object.defineProperty(exports, "__esModule", { value: true });
44272 var Viewer_1 = require("../Viewer");
44273 var Settings = /** @class */ (function () {
44274     function Settings() {
44275     }
44276     Settings.setOptions = function (options) {
44277         Settings._baseImageSize = options.baseImageSize != null ?
44278             options.baseImageSize :
44279             Viewer_1.ImageSize.Size640;
44280         Settings._basePanoramaSize = options.basePanoramaSize != null ?
44281             options.basePanoramaSize :
44282             Viewer_1.ImageSize.Size2048;
44283         Settings._maxImageSize = options.maxImageSize != null ?
44284             options.maxImageSize :
44285             Viewer_1.ImageSize.Size2048;
44286     };
44287     Object.defineProperty(Settings, "baseImageSize", {
44288         get: function () {
44289             return Settings._baseImageSize;
44290         },
44291         enumerable: true,
44292         configurable: true
44293     });
44294     Object.defineProperty(Settings, "basePanoramaSize", {
44295         get: function () {
44296             return Settings._basePanoramaSize;
44297         },
44298         enumerable: true,
44299         configurable: true
44300     });
44301     Object.defineProperty(Settings, "maxImageSize", {
44302         get: function () {
44303             return Settings._maxImageSize;
44304         },
44305         enumerable: true,
44306         configurable: true
44307     });
44308     return Settings;
44309 }());
44310 exports.Settings = Settings;
44311 exports.default = Settings;
44312
44313 },{"../Viewer":285}],428:[function(require,module,exports){
44314 "use strict";
44315 Object.defineProperty(exports, "__esModule", { value: true });
44316 function isBrowser() {
44317     return typeof window !== "undefined" && typeof document !== "undefined";
44318 }
44319 exports.isBrowser = isBrowser;
44320 function isArraySupported() {
44321     return !!(Array.prototype &&
44322         Array.prototype.filter &&
44323         Array.prototype.indexOf &&
44324         Array.prototype.map &&
44325         Array.prototype.reverse);
44326 }
44327 exports.isArraySupported = isArraySupported;
44328 function isFunctionSupported() {
44329     return !!(Function.prototype && Function.prototype.bind);
44330 }
44331 exports.isFunctionSupported = isFunctionSupported;
44332 function isJSONSupported() {
44333     return "JSON" in window && "parse" in JSON && "stringify" in JSON;
44334 }
44335 exports.isJSONSupported = isJSONSupported;
44336 function isObjectSupported() {
44337     return !!(Object.keys &&
44338         Object.assign);
44339 }
44340 exports.isObjectSupported = isObjectSupported;
44341 function isBlobSupported() {
44342     return "Blob" in window && "URL" in window;
44343 }
44344 exports.isBlobSupported = isBlobSupported;
44345 var isWebGLSupportedCache = undefined;
44346 function isWebGLSupportedCached() {
44347     if (isWebGLSupportedCache === undefined) {
44348         isWebGLSupportedCache = isWebGLSupported();
44349     }
44350     return isWebGLSupportedCache;
44351 }
44352 exports.isWebGLSupportedCached = isWebGLSupportedCached;
44353 function isWebGLSupported() {
44354     var webGLContextAttributes = {
44355         alpha: false,
44356         antialias: false,
44357         depth: true,
44358         failIfMajorPerformanceCaveat: false,
44359         premultipliedAlpha: true,
44360         preserveDrawingBuffer: false,
44361         stencil: true,
44362     };
44363     var canvas = document.createElement("canvas");
44364     var context = canvas.getContext("webgl", webGLContextAttributes) ||
44365         canvas.getContext("experimental-webgl", webGLContextAttributes);
44366     if (!context) {
44367         return false;
44368     }
44369     var requiredExtensions = [
44370         "OES_standard_derivatives",
44371     ];
44372     var supportedExtensions = context.getSupportedExtensions();
44373     for (var _i = 0, requiredExtensions_1 = requiredExtensions; _i < requiredExtensions_1.length; _i++) {
44374         var requiredExtension = requiredExtensions_1[_i];
44375         if (supportedExtensions.indexOf(requiredExtension) === -1) {
44376             return false;
44377         }
44378     }
44379     return true;
44380 }
44381 exports.isWebGLSupported = isWebGLSupported;
44382
44383 },{}],429:[function(require,module,exports){
44384 "use strict";
44385 Object.defineProperty(exports, "__esModule", { value: true });
44386 var Urls = /** @class */ (function () {
44387     function Urls() {
44388     }
44389     Object.defineProperty(Urls, "explore", {
44390         get: function () {
44391             return Urls._scheme + "://" + Urls._exploreHost;
44392         },
44393         enumerable: true,
44394         configurable: true
44395     });
44396     Object.defineProperty(Urls, "origin", {
44397         get: function () {
44398             return Urls._origin;
44399         },
44400         enumerable: true,
44401         configurable: true
44402     });
44403     Object.defineProperty(Urls, "tileScheme", {
44404         get: function () {
44405             return Urls._scheme;
44406         },
44407         enumerable: true,
44408         configurable: true
44409     });
44410     Object.defineProperty(Urls, "tileDomain", {
44411         get: function () {
44412             return Urls._imageTileHost;
44413         },
44414         enumerable: true,
44415         configurable: true
44416     });
44417     Urls.atomicReconstruction = function (key) {
44418         return Urls._scheme + "://" + Urls._atomicReconstructionHost + "/" + key + "/sfm/v1.0/atomic_reconstruction.json";
44419     };
44420     Urls.exporeImage = function (key) {
44421         return Urls._scheme + "://" + Urls._exploreHost + "/app/?pKey=" + key + "&focus=photo";
44422     };
44423     Urls.exporeUser = function (username) {
44424         return Urls._scheme + "://" + Urls._exploreHost + "/app/user/" + username;
44425     };
44426     Urls.falcorModel = function (clientId) {
44427         return Urls._scheme + "://" + Urls._apiHost + "/v3/model.json?client_id=" + clientId;
44428     };
44429     Urls.protoMesh = function (key) {
44430         return Urls._scheme + "://" + Urls._meshHost + "/v2/mesh/" + key;
44431     };
44432     Urls.thumbnail = function (key, size, origin) {
44433         var query = !!origin ? "?origin=" + origin : "";
44434         return Urls._scheme + "://" + Urls._imageHost + "/" + key + "/thumb-" + size + ".jpg" + query;
44435     };
44436     Urls.setOptions = function (options) {
44437         if (!options) {
44438             return;
44439         }
44440         if (!!options.apiHost) {
44441             Urls._apiHost = options.apiHost;
44442         }
44443         if (!!options.atomicReconstructionHost) {
44444             Urls._atomicReconstructionHost = options.atomicReconstructionHost;
44445         }
44446         if (!!options.exploreHost) {
44447             Urls._exploreHost = options.exploreHost;
44448         }
44449         if (!!options.imageHost) {
44450             Urls._imageHost = options.imageHost;
44451         }
44452         if (!!options.imageTileHost) {
44453             Urls._imageTileHost = options.imageTileHost;
44454         }
44455         if (!!options.meshHost) {
44456             Urls._meshHost = options.meshHost;
44457         }
44458         if (!!options.scheme) {
44459             Urls._scheme = options.scheme;
44460         }
44461     };
44462     Urls._apiHost = "a.mapillary.com";
44463     Urls._atomicReconstructionHost = "d3necqxnn15whe.cloudfront.net";
44464     Urls._exploreHost = "www.mapillary.com";
44465     Urls._imageHost = "d1cuyjsrcm0gby.cloudfront.net";
44466     Urls._imageTileHost = "d2qb1440i7l50o.cloudfront.net";
44467     Urls._meshHost = "d1brzeo354iq2l.cloudfront.net";
44468     Urls._origin = "mapillary.webgl";
44469     Urls._scheme = "https";
44470     return Urls;
44471 }());
44472 exports.Urls = Urls;
44473 exports.default = Urls;
44474
44475 },{}],430:[function(require,module,exports){
44476 "use strict";
44477 Object.defineProperty(exports, "__esModule", { value: true });
44478 /**
44479  * Enumeration for alignments
44480  * @enum {number}
44481  * @readonly
44482  */
44483 var Alignment;
44484 (function (Alignment) {
44485     /**
44486      * Align to bottom
44487      */
44488     Alignment[Alignment["Bottom"] = 0] = "Bottom";
44489     /**
44490      * Align to bottom left
44491      */
44492     Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft";
44493     /**
44494      * Align to bottom right
44495      */
44496     Alignment[Alignment["BottomRight"] = 2] = "BottomRight";
44497     /**
44498      * Align to center
44499      */
44500     Alignment[Alignment["Center"] = 3] = "Center";
44501     /**
44502      * Align to left
44503      */
44504     Alignment[Alignment["Left"] = 4] = "Left";
44505     /**
44506      * Align to right
44507      */
44508     Alignment[Alignment["Right"] = 5] = "Right";
44509     /**
44510      * Align to top
44511      */
44512     Alignment[Alignment["Top"] = 6] = "Top";
44513     /**
44514      * Align to top left
44515      */
44516     Alignment[Alignment["TopLeft"] = 7] = "TopLeft";
44517     /**
44518      * Align to top right
44519      */
44520     Alignment[Alignment["TopRight"] = 8] = "TopRight";
44521 })(Alignment = exports.Alignment || (exports.Alignment = {}));
44522 exports.default = Alignment;
44523
44524 },{}],431:[function(require,module,exports){
44525 "use strict";
44526 Object.defineProperty(exports, "__esModule", { value: true });
44527 var rxjs_1 = require("rxjs");
44528 var operators_1 = require("rxjs/operators");
44529 var Graph_1 = require("../Graph");
44530 var CacheService = /** @class */ (function () {
44531     function CacheService(graphService, stateService) {
44532         this._graphService = graphService;
44533         this._stateService = stateService;
44534         this._started = false;
44535     }
44536     Object.defineProperty(CacheService.prototype, "started", {
44537         get: function () {
44538             return this._started;
44539         },
44540         enumerable: true,
44541         configurable: true
44542     });
44543     CacheService.prototype.start = function () {
44544         var _this = this;
44545         if (this._started) {
44546             return;
44547         }
44548         this._uncacheSubscription = this._stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
44549             return frame.state.currentNode.key;
44550         }), operators_1.map(function (frame) {
44551             var trajectory = frame.state.trajectory;
44552             var trajectoryKeys = trajectory
44553                 .map(function (n) {
44554                 return n.key;
44555             });
44556             var sequenceKey = trajectory[trajectory.length - 1].sequenceKey;
44557             return [trajectoryKeys, sequenceKey];
44558         }), operators_1.bufferCount(1, 5), operators_1.withLatestFrom(this._graphService.graphMode$), operators_1.switchMap(function (_a) {
44559             var keepBuffer = _a[0], graphMode = _a[1];
44560             var keepKeys = keepBuffer[0][0];
44561             var keepSequenceKey = graphMode === Graph_1.GraphMode.Sequence ?
44562                 keepBuffer[0][1] : undefined;
44563             return _this._graphService.uncache$(keepKeys, keepSequenceKey);
44564         }))
44565             .subscribe(function () { });
44566         this._cacheNodeSubscription = this._graphService.graphMode$.pipe(operators_1.skip(1), operators_1.withLatestFrom(this._stateService.currentState$), operators_1.switchMap(function (_a) {
44567             var mode = _a[0], frame = _a[1];
44568             return mode === Graph_1.GraphMode.Sequence ?
44569                 _this._keyToEdges(frame.state.currentNode.key, function (node) {
44570                     return node.sequenceEdges$;
44571                 }) :
44572                 rxjs_1.from(frame.state.trajectory
44573                     .map(function (node) {
44574                     return node.key;
44575                 })
44576                     .slice(frame.state.currentIndex)).pipe(operators_1.mergeMap(function (key) {
44577                     return _this._keyToEdges(key, function (node) {
44578                         return node.spatialEdges$;
44579                     });
44580                 }, 6));
44581         }))
44582             .subscribe(function () { });
44583         this._started = true;
44584     };
44585     CacheService.prototype.stop = function () {
44586         if (!this._started) {
44587             return;
44588         }
44589         this._uncacheSubscription.unsubscribe();
44590         this._uncacheSubscription = null;
44591         this._cacheNodeSubscription.unsubscribe();
44592         this._cacheNodeSubscription = null;
44593         this._started = false;
44594     };
44595     CacheService.prototype._keyToEdges = function (key, nodeToEdgeMap) {
44596         return this._graphService.cacheNode$(key).pipe(operators_1.switchMap(nodeToEdgeMap), operators_1.first(function (status) {
44597             return status.cached;
44598         }), operators_1.timeout(15000), operators_1.catchError(function (error) {
44599             console.error("Failed to cache edges (" + key + ").", error);
44600             return rxjs_1.empty();
44601         }));
44602     };
44603     return CacheService;
44604 }());
44605 exports.CacheService = CacheService;
44606 exports.default = CacheService;
44607
44608 },{"../Graph":278,"rxjs":26,"rxjs/operators":224}],432:[function(require,module,exports){
44609 "use strict";
44610 Object.defineProperty(exports, "__esModule", { value: true });
44611 var operators_1 = require("rxjs/operators");
44612 var Component_1 = require("../Component");
44613 var ComponentController = /** @class */ (function () {
44614     function ComponentController(container, navigator, observer, key, options, componentService) {
44615         var _this = this;
44616         this._container = container;
44617         this._observer = observer;
44618         this._navigator = navigator;
44619         this._options = options != null ? options : {};
44620         this._key = key;
44621         this._navigable = key == null;
44622         this._componentService = !!componentService ?
44623             componentService :
44624             new Component_1.ComponentService(this._container, this._navigator);
44625         this._coverComponent = this._componentService.getCover();
44626         this._initializeComponents();
44627         if (key) {
44628             this._initilizeCoverComponent();
44629             this._subscribeCoverComponent();
44630         }
44631         else {
44632             this._navigator.movedToKey$.pipe(operators_1.first(function (k) {
44633                 return k != null;
44634             }))
44635                 .subscribe(function (k) {
44636                 _this._key = k;
44637                 _this._componentService.deactivateCover();
44638                 _this._coverComponent.configure({ key: _this._key, state: Component_1.CoverState.Hidden });
44639                 _this._subscribeCoverComponent();
44640                 _this._navigator.stateService.start();
44641                 _this._navigator.cacheService.start();
44642                 _this._observer.startEmit();
44643             });
44644         }
44645     }
44646     Object.defineProperty(ComponentController.prototype, "navigable", {
44647         get: function () {
44648             return this._navigable;
44649         },
44650         enumerable: true,
44651         configurable: true
44652     });
44653     ComponentController.prototype.get = function (name) {
44654         return this._componentService.get(name);
44655     };
44656     ComponentController.prototype.activate = function (name) {
44657         this._componentService.activate(name);
44658     };
44659     ComponentController.prototype.activateCover = function () {
44660         this._coverComponent.configure({ state: Component_1.CoverState.Visible });
44661     };
44662     ComponentController.prototype.deactivate = function (name) {
44663         this._componentService.deactivate(name);
44664     };
44665     ComponentController.prototype.deactivateCover = function () {
44666         this._coverComponent.configure({ state: Component_1.CoverState.Loading });
44667     };
44668     ComponentController.prototype._initializeComponents = function () {
44669         var options = this._options;
44670         this._uFalse(options.background, "background");
44671         this._uFalse(options.debug, "debug");
44672         this._uFalse(options.image, "image");
44673         this._uFalse(options.marker, "marker");
44674         this._uFalse(options.navigation, "navigation");
44675         this._uFalse(options.popup, "popup");
44676         this._uFalse(options.route, "route");
44677         this._uFalse(options.slider, "slider");
44678         this._uFalse(options.spatialData, "spatialData");
44679         this._uFalse(options.tag, "tag");
44680         this._uTrue(options.attribution, "attribution");
44681         this._uTrue(options.bearing, "bearing");
44682         this._uTrue(options.cache, "cache");
44683         this._uTrue(options.direction, "direction");
44684         this._uTrue(options.imagePlane, "imagePlane");
44685         this._uTrue(options.keyboard, "keyboard");
44686         this._uTrue(options.loading, "loading");
44687         this._uTrue(options.mouse, "mouse");
44688         this._uTrue(options.sequence, "sequence");
44689         this._uTrue(options.stats, "stats");
44690         this._uTrue(options.zoom, "zoom");
44691     };
44692     ComponentController.prototype._initilizeCoverComponent = function () {
44693         var options = this._options;
44694         this._coverComponent.configure({ key: this._key });
44695         if (options.cover === undefined || options.cover) {
44696             this.activateCover();
44697         }
44698         else {
44699             this.deactivateCover();
44700         }
44701     };
44702     ComponentController.prototype._setNavigable = function (navigable) {
44703         if (this._navigable === navigable) {
44704             return;
44705         }
44706         this._navigable = navigable;
44707         this._observer.navigable$.next(navigable);
44708     };
44709     ComponentController.prototype._subscribeCoverComponent = function () {
44710         var _this = this;
44711         this._coverComponent.configuration$.pipe(operators_1.distinctUntilChanged(undefined, function (c) {
44712             return c.state;
44713         }))
44714             .subscribe(function (conf) {
44715             if (conf.state === Component_1.CoverState.Loading) {
44716                 _this._navigator.stateService.currentKey$.pipe(operators_1.first(), operators_1.switchMap(function (key) {
44717                     var keyChanged = key == null || key !== conf.key;
44718                     if (keyChanged) {
44719                         _this._setNavigable(false);
44720                     }
44721                     return keyChanged ?
44722                         _this._navigator.moveToKey$(conf.key) :
44723                         _this._navigator.stateService.currentNode$.pipe(operators_1.first());
44724                 }))
44725                     .subscribe(function () {
44726                     _this._navigator.stateService.start();
44727                     _this._navigator.cacheService.start();
44728                     _this._observer.startEmit();
44729                     _this._coverComponent.configure({ state: Component_1.CoverState.Hidden });
44730                     _this._componentService.deactivateCover();
44731                     _this._setNavigable(true);
44732                 }, function (error) {
44733                     console.error("Failed to deactivate cover.", error);
44734                     _this._coverComponent.configure({ state: Component_1.CoverState.Visible });
44735                 });
44736             }
44737             else if (conf.state === Component_1.CoverState.Visible) {
44738                 _this._observer.stopEmit();
44739                 _this._navigator.stateService.stop();
44740                 _this._navigator.cacheService.stop();
44741                 _this._navigator.playService.stop();
44742                 _this._componentService.activateCover();
44743                 _this._setNavigable(conf.key == null);
44744             }
44745         });
44746     };
44747     ComponentController.prototype._uFalse = function (option, name) {
44748         if (option === undefined) {
44749             this._componentService.deactivate(name);
44750             return;
44751         }
44752         if (typeof option === "boolean") {
44753             if (option) {
44754                 this._componentService.activate(name);
44755             }
44756             else {
44757                 this._componentService.deactivate(name);
44758             }
44759             return;
44760         }
44761         this._componentService.configure(name, option);
44762         this._componentService.activate(name);
44763     };
44764     ComponentController.prototype._uTrue = function (option, name) {
44765         if (option === undefined) {
44766             this._componentService.activate(name);
44767             return;
44768         }
44769         if (typeof option === "boolean") {
44770             if (option) {
44771                 this._componentService.activate(name);
44772             }
44773             else {
44774                 this._componentService.deactivate(name);
44775             }
44776             return;
44777         }
44778         this._componentService.configure(name, option);
44779         this._componentService.activate(name);
44780     };
44781     return ComponentController;
44782 }());
44783 exports.ComponentController = ComponentController;
44784
44785 },{"../Component":274,"rxjs/operators":224}],433:[function(require,module,exports){
44786 "use strict";
44787 Object.defineProperty(exports, "__esModule", { value: true });
44788 var Render_1 = require("../Render");
44789 var Utils_1 = require("../Utils");
44790 var Viewer_1 = require("../Viewer");
44791 var Container = /** @class */ (function () {
44792     function Container(id, stateService, options, dom) {
44793         this.id = id;
44794         this._dom = !!dom ? dom : new Utils_1.DOM();
44795         this._container = this._dom.document.getElementById(id);
44796         if (!this._container) {
44797             throw new Error("Container '" + id + "' not found.");
44798         }
44799         this._container.classList.add("mapillary-js");
44800         this._canvasContainer = this._dom.createElement("div", "mapillary-js-interactive", this._container);
44801         this._domContainer = this._dom.createElement("div", "mapillary-js-dom", this._container);
44802         this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
44803         this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService, this._dom);
44804         this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$);
44805         this.keyboardService = new Viewer_1.KeyboardService(this._canvasContainer);
44806         this.mouseService = new Viewer_1.MouseService(this._container, this._canvasContainer, this._domContainer, document);
44807         this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer);
44808         this.spriteService = new Viewer_1.SpriteService(options.sprite);
44809     }
44810     Object.defineProperty(Container.prototype, "element", {
44811         get: function () {
44812             return this._container;
44813         },
44814         enumerable: true,
44815         configurable: true
44816     });
44817     Object.defineProperty(Container.prototype, "canvasContainer", {
44818         get: function () {
44819             return this._canvasContainer;
44820         },
44821         enumerable: true,
44822         configurable: true
44823     });
44824     Object.defineProperty(Container.prototype, "domContainer", {
44825         get: function () {
44826             return this._domContainer;
44827         },
44828         enumerable: true,
44829         configurable: true
44830     });
44831     return Container;
44832 }());
44833 exports.Container = Container;
44834 exports.default = Container;
44835
44836 },{"../Render":280,"../Utils":284,"../Viewer":285}],434:[function(require,module,exports){
44837 "use strict";
44838 Object.defineProperty(exports, "__esModule", { value: true });
44839 /**
44840  * Enumeration for image sizes
44841  * @enum {number}
44842  * @readonly
44843  * @description Image sizes in pixels for the long side of the image.
44844  */
44845 var ImageSize;
44846 (function (ImageSize) {
44847     /**
44848      * 320 pixels image size
44849      */
44850     ImageSize[ImageSize["Size320"] = 320] = "Size320";
44851     /**
44852      * 640 pixels image size
44853      */
44854     ImageSize[ImageSize["Size640"] = 640] = "Size640";
44855     /**
44856      * 1024 pixels image size
44857      */
44858     ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
44859     /**
44860      * 2048 pixels image size
44861      */
44862     ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
44863 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
44864
44865 },{}],435:[function(require,module,exports){
44866 "use strict";
44867 Object.defineProperty(exports, "__esModule", { value: true });
44868 var rxjs_1 = require("rxjs");
44869 var KeyboardService = /** @class */ (function () {
44870     function KeyboardService(canvasContainer) {
44871         this._keyDown$ = rxjs_1.fromEvent(canvasContainer, "keydown");
44872         this._keyUp$ = rxjs_1.fromEvent(canvasContainer, "keyup");
44873     }
44874     Object.defineProperty(KeyboardService.prototype, "keyDown$", {
44875         get: function () {
44876             return this._keyDown$;
44877         },
44878         enumerable: true,
44879         configurable: true
44880     });
44881     Object.defineProperty(KeyboardService.prototype, "keyUp$", {
44882         get: function () {
44883             return this._keyUp$;
44884         },
44885         enumerable: true,
44886         configurable: true
44887     });
44888     return KeyboardService;
44889 }());
44890 exports.KeyboardService = KeyboardService;
44891 exports.default = KeyboardService;
44892
44893 },{"rxjs":26}],436:[function(require,module,exports){
44894 "use strict";
44895 Object.defineProperty(exports, "__esModule", { value: true });
44896 var operators_1 = require("rxjs/operators");
44897 var rxjs_1 = require("rxjs");
44898 var LoadingService = /** @class */ (function () {
44899     function LoadingService() {
44900         this._loadersSubject$ = new rxjs_1.Subject();
44901         this._loaders$ = this._loadersSubject$.pipe(operators_1.scan(function (loaders, loader) {
44902             if (loader.task !== undefined) {
44903                 loaders[loader.task] = loader.loading;
44904             }
44905             return loaders;
44906         }, {}), operators_1.startWith({}), operators_1.publishReplay(1), operators_1.refCount());
44907     }
44908     Object.defineProperty(LoadingService.prototype, "loading$", {
44909         get: function () {
44910             return this._loaders$.pipe(operators_1.map(function (loaders) {
44911                 for (var key in loaders) {
44912                     if (!loaders.hasOwnProperty(key)) {
44913                         continue;
44914                     }
44915                     if (loaders[key]) {
44916                         return true;
44917                     }
44918                 }
44919                 return false;
44920             }), operators_1.debounceTime(100), operators_1.distinctUntilChanged());
44921         },
44922         enumerable: true,
44923         configurable: true
44924     });
44925     LoadingService.prototype.taskLoading$ = function (task) {
44926         return this._loaders$.pipe(operators_1.map(function (loaders) {
44927             return !!loaders[task];
44928         }), operators_1.debounceTime(100), operators_1.distinctUntilChanged());
44929     };
44930     LoadingService.prototype.startLoading = function (task) {
44931         this._loadersSubject$.next({ loading: true, task: task });
44932     };
44933     LoadingService.prototype.stopLoading = function (task) {
44934         this._loadersSubject$.next({ loading: false, task: task });
44935     };
44936     return LoadingService;
44937 }());
44938 exports.LoadingService = LoadingService;
44939 exports.default = LoadingService;
44940
44941 },{"rxjs":26,"rxjs/operators":224}],437:[function(require,module,exports){
44942 "use strict";
44943 Object.defineProperty(exports, "__esModule", { value: true });
44944 var rxjs_1 = require("rxjs");
44945 var operators_1 = require("rxjs/operators");
44946 var MouseService = /** @class */ (function () {
44947     function MouseService(container, canvasContainer, domContainer, doc) {
44948         var _this = this;
44949         this._activeSubject$ = new rxjs_1.BehaviorSubject(false);
44950         this._active$ = this._activeSubject$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
44951         this._claimMouse$ = new rxjs_1.Subject();
44952         this._claimWheel$ = new rxjs_1.Subject();
44953         this._deferPixelClaims$ = new rxjs_1.Subject();
44954         this._deferPixels$ = this._deferPixelClaims$.pipe(operators_1.scan(function (claims, claim) {
44955             if (claim.deferPixels == null) {
44956                 delete claims[claim.name];
44957             }
44958             else {
44959                 claims[claim.name] = claim.deferPixels;
44960             }
44961             return claims;
44962         }, {}), operators_1.map(function (claims) {
44963             var deferPixelMax = -1;
44964             for (var key in claims) {
44965                 if (!claims.hasOwnProperty(key)) {
44966                     continue;
44967                 }
44968                 var deferPixels = claims[key];
44969                 if (deferPixels > deferPixelMax) {
44970                     deferPixelMax = deferPixels;
44971                 }
44972             }
44973             return deferPixelMax;
44974         }), operators_1.startWith(-1), operators_1.publishReplay(1), operators_1.refCount());
44975         this._deferPixels$.subscribe(function () { });
44976         this._documentMouseMove$ = rxjs_1.fromEvent(doc, "mousemove");
44977         this._documentMouseUp$ = rxjs_1.fromEvent(doc, "mouseup");
44978         this._mouseDown$ = rxjs_1.fromEvent(canvasContainer, "mousedown");
44979         this._mouseLeave$ = rxjs_1.fromEvent(canvasContainer, "mouseleave");
44980         this._mouseMove$ = rxjs_1.fromEvent(canvasContainer, "mousemove");
44981         this._mouseUp$ = rxjs_1.fromEvent(canvasContainer, "mouseup");
44982         this._mouseOut$ = rxjs_1.fromEvent(canvasContainer, "mouseout");
44983         this._mouseOver$ = rxjs_1.fromEvent(canvasContainer, "mouseover");
44984         this._domMouseDown$ = rxjs_1.fromEvent(domContainer, "mousedown");
44985         this._domMouseMove$ = rxjs_1.fromEvent(domContainer, "mousemove");
44986         this._click$ = rxjs_1.fromEvent(canvasContainer, "click");
44987         this._contextMenu$ = rxjs_1.fromEvent(canvasContainer, "contextmenu");
44988         this._dblClick$ = rxjs_1.merge(rxjs_1.fromEvent(container, "click"), rxjs_1.fromEvent(canvasContainer, "dblclick")).pipe(operators_1.bufferCount(3, 1), operators_1.filter(function (events) {
44989             var event1 = events[0];
44990             var event2 = events[1];
44991             var event3 = events[2];
44992             return event1.type === "click" &&
44993                 event2.type === "click" &&
44994                 event3.type === "dblclick" &&
44995                 event1.target.parentNode === canvasContainer &&
44996                 event2.target.parentNode === canvasContainer;
44997         }), operators_1.map(function (events) {
44998             return events[2];
44999         }), operators_1.share());
45000         rxjs_1.merge(this._domMouseDown$, this._domMouseMove$, this._dblClick$, this._contextMenu$)
45001             .subscribe(function (event) {
45002             event.preventDefault();
45003         });
45004         this._mouseWheel$ = rxjs_1.merge(rxjs_1.fromEvent(canvasContainer, "wheel"), rxjs_1.fromEvent(domContainer, "wheel")).pipe(operators_1.share());
45005         this._consistentContextMenu$ = rxjs_1.merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$).pipe(operators_1.bufferCount(3, 1), operators_1.filter(function (events) {
45006             // fire context menu on mouse up both on mac and windows
45007             return events[0].type === "mousedown" &&
45008                 events[1].type === "contextmenu" &&
45009                 events[2].type === "mouseup";
45010         }), operators_1.map(function (events) {
45011             return events[1];
45012         }), operators_1.share());
45013         var dragStop$ = rxjs_1.merge(rxjs_1.fromEvent(window, "blur"), this._documentMouseUp$.pipe(operators_1.filter(function (e) {
45014             return e.button === 0;
45015         }))).pipe(operators_1.share());
45016         var mouseDragInitiate$ = this._createMouseDragInitiate$(this._mouseDown$, dragStop$, true).pipe(operators_1.share());
45017         this._mouseDragStart$ = this._createMouseDragStart$(mouseDragInitiate$).pipe(operators_1.share());
45018         this._mouseDrag$ = this._createMouseDrag$(mouseDragInitiate$, dragStop$).pipe(operators_1.share());
45019         this._mouseDragEnd$ = this._createMouseDragEnd$(this._mouseDragStart$, dragStop$).pipe(operators_1.share());
45020         var domMouseDragInitiate$ = this._createMouseDragInitiate$(this._domMouseDown$, dragStop$, false).pipe(operators_1.share());
45021         this._domMouseDragStart$ = this._createMouseDragStart$(domMouseDragInitiate$).pipe(operators_1.share());
45022         this._domMouseDrag$ = this._createMouseDrag$(domMouseDragInitiate$, dragStop$).pipe(operators_1.share());
45023         this._domMouseDragEnd$ = this._createMouseDragEnd$(this._domMouseDragStart$, dragStop$).pipe(operators_1.share());
45024         this._proximateClick$ = this._mouseDown$.pipe(operators_1.switchMap(function (mouseDown) {
45025             return _this._click$.pipe(operators_1.takeUntil(_this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$)), operators_1.take(1));
45026         }), operators_1.share());
45027         this._staticClick$ = this._mouseDown$.pipe(operators_1.switchMap(function (e) {
45028             return _this._click$.pipe(operators_1.takeUntil(_this._documentMouseMove$), operators_1.take(1));
45029         }), operators_1.share());
45030         this._mouseDragStart$.subscribe();
45031         this._mouseDrag$.subscribe();
45032         this._mouseDragEnd$.subscribe();
45033         this._domMouseDragStart$.subscribe();
45034         this._domMouseDrag$.subscribe();
45035         this._domMouseDragEnd$.subscribe();
45036         this._staticClick$.subscribe();
45037         this._mouseOwner$ = this._createOwner$(this._claimMouse$).pipe(operators_1.publishReplay(1), operators_1.refCount());
45038         this._wheelOwner$ = this._createOwner$(this._claimWheel$).pipe(operators_1.publishReplay(1), operators_1.refCount());
45039         this._mouseOwner$.subscribe(function () { });
45040         this._wheelOwner$.subscribe(function () { });
45041     }
45042     Object.defineProperty(MouseService.prototype, "active$", {
45043         get: function () {
45044             return this._active$;
45045         },
45046         enumerable: true,
45047         configurable: true
45048     });
45049     Object.defineProperty(MouseService.prototype, "activate$", {
45050         get: function () {
45051             return this._activeSubject$;
45052         },
45053         enumerable: true,
45054         configurable: true
45055     });
45056     Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
45057         get: function () {
45058             return this._documentMouseMove$;
45059         },
45060         enumerable: true,
45061         configurable: true
45062     });
45063     Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
45064         get: function () {
45065             return this._documentMouseUp$;
45066         },
45067         enumerable: true,
45068         configurable: true
45069     });
45070     Object.defineProperty(MouseService.prototype, "domMouseDragStart$", {
45071         get: function () {
45072             return this._domMouseDragStart$;
45073         },
45074         enumerable: true,
45075         configurable: true
45076     });
45077     Object.defineProperty(MouseService.prototype, "domMouseDrag$", {
45078         get: function () {
45079             return this._domMouseDrag$;
45080         },
45081         enumerable: true,
45082         configurable: true
45083     });
45084     Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", {
45085         get: function () {
45086             return this._domMouseDragEnd$;
45087         },
45088         enumerable: true,
45089         configurable: true
45090     });
45091     Object.defineProperty(MouseService.prototype, "domMouseDown$", {
45092         get: function () {
45093             return this._domMouseDown$;
45094         },
45095         enumerable: true,
45096         configurable: true
45097     });
45098     Object.defineProperty(MouseService.prototype, "domMouseMove$", {
45099         get: function () {
45100             return this._domMouseMove$;
45101         },
45102         enumerable: true,
45103         configurable: true
45104     });
45105     Object.defineProperty(MouseService.prototype, "mouseOwner$", {
45106         get: function () {
45107             return this._mouseOwner$;
45108         },
45109         enumerable: true,
45110         configurable: true
45111     });
45112     Object.defineProperty(MouseService.prototype, "mouseDown$", {
45113         get: function () {
45114             return this._mouseDown$;
45115         },
45116         enumerable: true,
45117         configurable: true
45118     });
45119     Object.defineProperty(MouseService.prototype, "mouseMove$", {
45120         get: function () {
45121             return this._mouseMove$;
45122         },
45123         enumerable: true,
45124         configurable: true
45125     });
45126     Object.defineProperty(MouseService.prototype, "mouseLeave$", {
45127         get: function () {
45128             return this._mouseLeave$;
45129         },
45130         enumerable: true,
45131         configurable: true
45132     });
45133     Object.defineProperty(MouseService.prototype, "mouseOut$", {
45134         get: function () {
45135             return this._mouseOut$;
45136         },
45137         enumerable: true,
45138         configurable: true
45139     });
45140     Object.defineProperty(MouseService.prototype, "mouseOver$", {
45141         get: function () {
45142             return this._mouseOver$;
45143         },
45144         enumerable: true,
45145         configurable: true
45146     });
45147     Object.defineProperty(MouseService.prototype, "mouseUp$", {
45148         get: function () {
45149             return this._mouseUp$;
45150         },
45151         enumerable: true,
45152         configurable: true
45153     });
45154     Object.defineProperty(MouseService.prototype, "click$", {
45155         get: function () {
45156             return this._click$;
45157         },
45158         enumerable: true,
45159         configurable: true
45160     });
45161     Object.defineProperty(MouseService.prototype, "dblClick$", {
45162         get: function () {
45163             return this._dblClick$;
45164         },
45165         enumerable: true,
45166         configurable: true
45167     });
45168     Object.defineProperty(MouseService.prototype, "contextMenu$", {
45169         get: function () {
45170             return this._consistentContextMenu$;
45171         },
45172         enumerable: true,
45173         configurable: true
45174     });
45175     Object.defineProperty(MouseService.prototype, "mouseWheel$", {
45176         get: function () {
45177             return this._mouseWheel$;
45178         },
45179         enumerable: true,
45180         configurable: true
45181     });
45182     Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
45183         get: function () {
45184             return this._mouseDragStart$;
45185         },
45186         enumerable: true,
45187         configurable: true
45188     });
45189     Object.defineProperty(MouseService.prototype, "mouseDrag$", {
45190         get: function () {
45191             return this._mouseDrag$;
45192         },
45193         enumerable: true,
45194         configurable: true
45195     });
45196     Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
45197         get: function () {
45198             return this._mouseDragEnd$;
45199         },
45200         enumerable: true,
45201         configurable: true
45202     });
45203     Object.defineProperty(MouseService.prototype, "proximateClick$", {
45204         get: function () {
45205             return this._proximateClick$;
45206         },
45207         enumerable: true,
45208         configurable: true
45209     });
45210     Object.defineProperty(MouseService.prototype, "staticClick$", {
45211         get: function () {
45212             return this._staticClick$;
45213         },
45214         enumerable: true,
45215         configurable: true
45216     });
45217     MouseService.prototype.claimMouse = function (name, zindex) {
45218         this._claimMouse$.next({ name: name, zindex: zindex });
45219     };
45220     MouseService.prototype.unclaimMouse = function (name) {
45221         this._claimMouse$.next({ name: name, zindex: null });
45222     };
45223     MouseService.prototype.deferPixels = function (name, deferPixels) {
45224         this._deferPixelClaims$.next({ name: name, deferPixels: deferPixels });
45225     };
45226     MouseService.prototype.undeferPixels = function (name) {
45227         this._deferPixelClaims$.next({ name: name, deferPixels: null });
45228     };
45229     MouseService.prototype.claimWheel = function (name, zindex) {
45230         this._claimWheel$.next({ name: name, zindex: zindex });
45231     };
45232     MouseService.prototype.unclaimWheel = function (name) {
45233         this._claimWheel$.next({ name: name, zindex: null });
45234     };
45235     MouseService.prototype.filtered$ = function (name, observable$) {
45236         return this._filtered(name, observable$, this._mouseOwner$);
45237     };
45238     MouseService.prototype.filteredWheel$ = function (name, observable$) {
45239         return this._filtered(name, observable$, this._wheelOwner$);
45240     };
45241     MouseService.prototype._createDeferredMouseMove$ = function (origin, mouseMove$) {
45242         return mouseMove$.pipe(operators_1.map(function (mouseMove) {
45243             var deltaX = mouseMove.clientX - origin.clientX;
45244             var deltaY = mouseMove.clientY - origin.clientY;
45245             return [mouseMove, Math.sqrt(deltaX * deltaX + deltaY * deltaY)];
45246         }), operators_1.withLatestFrom(this._deferPixels$), operators_1.filter(function (_a) {
45247             var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
45248             return delta > deferPixels;
45249         }), operators_1.map(function (_a) {
45250             var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
45251             return mouseMove;
45252         }));
45253     };
45254     MouseService.prototype._createMouseDrag$ = function (mouseDragStartInitiate$, stop$) {
45255         var _this = this;
45256         return mouseDragStartInitiate$.pipe(operators_1.map(function (_a) {
45257             var mouseDown = _a[0], mouseMove = _a[1];
45258             return mouseMove;
45259         }), operators_1.switchMap(function (mouseMove) {
45260             return rxjs_1.concat(rxjs_1.of(mouseMove), _this._documentMouseMove$).pipe(operators_1.takeUntil(stop$));
45261         }));
45262     };
45263     MouseService.prototype._createMouseDragEnd$ = function (mouseDragStart$, stop$) {
45264         return mouseDragStart$.pipe(operators_1.switchMap(function (event) {
45265             return stop$.pipe(operators_1.first());
45266         }));
45267     };
45268     MouseService.prototype._createMouseDragStart$ = function (mouseDragStartInitiate$) {
45269         return mouseDragStartInitiate$.pipe(operators_1.map(function (_a) {
45270             var mouseDown = _a[0], mouseMove = _a[1];
45271             return mouseDown;
45272         }));
45273     };
45274     MouseService.prototype._createMouseDragInitiate$ = function (mouseDown$, stop$, defer) {
45275         var _this = this;
45276         return mouseDown$.pipe(operators_1.filter(function (mouseDown) {
45277             return mouseDown.button === 0;
45278         }), operators_1.switchMap(function (mouseDown) {
45279             return rxjs_1.combineLatest(rxjs_1.of(mouseDown), defer ?
45280                 _this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$) :
45281                 _this._documentMouseMove$).pipe(operators_1.takeUntil(stop$), operators_1.take(1));
45282         }));
45283     };
45284     MouseService.prototype._createOwner$ = function (claim$) {
45285         return claim$.pipe(operators_1.scan(function (claims, claim) {
45286             if (claim.zindex == null) {
45287                 delete claims[claim.name];
45288             }
45289             else {
45290                 claims[claim.name] = claim.zindex;
45291             }
45292             return claims;
45293         }, {}), operators_1.map(function (claims) {
45294             var owner = null;
45295             var zIndexMax = -1;
45296             for (var name_1 in claims) {
45297                 if (!claims.hasOwnProperty(name_1)) {
45298                     continue;
45299                 }
45300                 if (claims[name_1] > zIndexMax) {
45301                     zIndexMax = claims[name_1];
45302                     owner = name_1;
45303                 }
45304             }
45305             return owner;
45306         }), operators_1.startWith(null));
45307     };
45308     MouseService.prototype._filtered = function (name, observable$, owner$) {
45309         return observable$.pipe(operators_1.withLatestFrom(owner$), operators_1.filter(function (_a) {
45310             var item = _a[0], owner = _a[1];
45311             return owner === name;
45312         }), operators_1.map(function (_a) {
45313             var item = _a[0], owner = _a[1];
45314             return item;
45315         }));
45316     };
45317     return MouseService;
45318 }());
45319 exports.MouseService = MouseService;
45320 exports.default = MouseService;
45321
45322 },{"rxjs":26,"rxjs/operators":224}],438:[function(require,module,exports){
45323 "use strict";
45324 Object.defineProperty(exports, "__esModule", { value: true });
45325 var rxjs_1 = require("rxjs");
45326 var operators_1 = require("rxjs/operators");
45327 var API_1 = require("../API");
45328 var Graph_1 = require("../Graph");
45329 var Edge_1 = require("../Edge");
45330 var Error_1 = require("../Error");
45331 var State_1 = require("../State");
45332 var Viewer_1 = require("../Viewer");
45333 var Navigator = /** @class */ (function () {
45334     function Navigator(clientId, options, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService, playService) {
45335         this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
45336         this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
45337         this._graphService = graphService != null ?
45338             graphService :
45339             new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
45340         this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
45341         this._loadingName = "navigator";
45342         this._stateService = stateService != null ? stateService : new State_1.StateService(options.transitionMode);
45343         this._cacheService = cacheService != null ?
45344             cacheService :
45345             new Viewer_1.CacheService(this._graphService, this._stateService);
45346         this._playService = playService != null ?
45347             playService :
45348             new Viewer_1.PlayService(this._graphService, this._stateService);
45349         this._keyRequested$ = new rxjs_1.BehaviorSubject(null);
45350         this._movedToKey$ = new rxjs_1.BehaviorSubject(null);
45351         this._request$ = null;
45352         this._requestSubscription = null;
45353         this._nodeRequestSubscription = null;
45354     }
45355     Object.defineProperty(Navigator.prototype, "apiV3", {
45356         get: function () {
45357             return this._apiV3;
45358         },
45359         enumerable: true,
45360         configurable: true
45361     });
45362     Object.defineProperty(Navigator.prototype, "cacheService", {
45363         get: function () {
45364             return this._cacheService;
45365         },
45366         enumerable: true,
45367         configurable: true
45368     });
45369     Object.defineProperty(Navigator.prototype, "graphService", {
45370         get: function () {
45371             return this._graphService;
45372         },
45373         enumerable: true,
45374         configurable: true
45375     });
45376     Object.defineProperty(Navigator.prototype, "imageLoadingService", {
45377         get: function () {
45378             return this._imageLoadingService;
45379         },
45380         enumerable: true,
45381         configurable: true
45382     });
45383     Object.defineProperty(Navigator.prototype, "loadingService", {
45384         get: function () {
45385             return this._loadingService;
45386         },
45387         enumerable: true,
45388         configurable: true
45389     });
45390     Object.defineProperty(Navigator.prototype, "movedToKey$", {
45391         get: function () {
45392             return this._movedToKey$;
45393         },
45394         enumerable: true,
45395         configurable: true
45396     });
45397     Object.defineProperty(Navigator.prototype, "playService", {
45398         get: function () {
45399             return this._playService;
45400         },
45401         enumerable: true,
45402         configurable: true
45403     });
45404     Object.defineProperty(Navigator.prototype, "stateService", {
45405         get: function () {
45406             return this._stateService;
45407         },
45408         enumerable: true,
45409         configurable: true
45410     });
45411     Navigator.prototype.moveToKey$ = function (key) {
45412         this._abortRequest("to key " + key);
45413         this._loadingService.startLoading(this._loadingName);
45414         var node$ = this._moveToKey$(key);
45415         return this._makeRequest$(node$);
45416     };
45417     Navigator.prototype.moveDir$ = function (direction) {
45418         var _this = this;
45419         this._abortRequest("in dir " + Edge_1.EdgeDirection[direction]);
45420         this._loadingService.startLoading(this._loadingName);
45421         var node$ = this.stateService.currentNode$.pipe(operators_1.first(), operators_1.mergeMap(function (node) {
45422             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
45423                 node.sequenceEdges$ :
45424                 node.spatialEdges$).pipe(operators_1.first(), operators_1.map(function (status) {
45425                 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
45426                     var edge = _a[_i];
45427                     if (edge.data.direction === direction) {
45428                         return edge.to;
45429                     }
45430                 }
45431                 return null;
45432             }));
45433         }), operators_1.mergeMap(function (directionKey) {
45434             if (directionKey == null) {
45435                 _this._loadingService.stopLoading(_this._loadingName);
45436                 return rxjs_1.throwError(new Error("Direction (" + direction + ") does not exist for current node."));
45437             }
45438             return _this._moveToKey$(directionKey);
45439         }));
45440         return this._makeRequest$(node$);
45441     };
45442     Navigator.prototype.moveCloseTo$ = function (lat, lon) {
45443         var _this = this;
45444         this._abortRequest("to lat " + lat + ", lon " + lon);
45445         this._loadingService.startLoading(this._loadingName);
45446         var node$ = this.apiV3.imageCloseTo$(lat, lon).pipe(operators_1.mergeMap(function (fullNode) {
45447             if (fullNode == null) {
45448                 _this._loadingService.stopLoading(_this._loadingName);
45449                 return rxjs_1.throwError(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
45450             }
45451             return _this._moveToKey$(fullNode.key);
45452         }));
45453         return this._makeRequest$(node$);
45454     };
45455     Navigator.prototype.setFilter$ = function (filter) {
45456         var _this = this;
45457         this._stateService.clearNodes();
45458         return this._movedToKey$.pipe(operators_1.first(), operators_1.mergeMap(function (key) {
45459             if (key != null) {
45460                 return _this._trajectoryKeys$().pipe(operators_1.mergeMap(function (keys) {
45461                     return _this._graphService.setFilter$(filter).pipe(operators_1.mergeMap(function () {
45462                         return _this._cacheKeys$(keys);
45463                     }));
45464                 }), operators_1.last());
45465             }
45466             return _this._keyRequested$.pipe(operators_1.first(), operators_1.mergeMap(function (requestedKey) {
45467                 if (requestedKey != null) {
45468                     return _this._graphService.setFilter$(filter).pipe(operators_1.mergeMap(function () {
45469                         return _this._graphService.cacheNode$(requestedKey);
45470                     }));
45471                 }
45472                 return _this._graphService.setFilter$(filter).pipe(operators_1.map(function () {
45473                     return undefined;
45474                 }));
45475             }));
45476         }), operators_1.map(function (node) {
45477             return undefined;
45478         }));
45479     };
45480     Navigator.prototype.setToken$ = function (token) {
45481         var _this = this;
45482         this._abortRequest("to set token");
45483         this._stateService.clearNodes();
45484         return this._movedToKey$.pipe(operators_1.first(), operators_1.tap(function (key) {
45485             _this._apiV3.setToken(token);
45486         }), operators_1.mergeMap(function (key) {
45487             return key == null ?
45488                 _this._graphService.reset$([]) :
45489                 _this._trajectoryKeys$().pipe(operators_1.mergeMap(function (keys) {
45490                     return _this._graphService.reset$(keys).pipe(operators_1.mergeMap(function () {
45491                         return _this._cacheKeys$(keys);
45492                     }));
45493                 }), operators_1.last(), operators_1.map(function (node) {
45494                     return undefined;
45495                 }));
45496         }));
45497     };
45498     Navigator.prototype._cacheKeys$ = function (keys) {
45499         var _this = this;
45500         var cacheNodes$ = keys
45501             .map(function (key) {
45502             return _this._graphService.cacheNode$(key);
45503         });
45504         return rxjs_1.from(cacheNodes$).pipe(operators_1.mergeAll());
45505     };
45506     Navigator.prototype._abortRequest = function (reason) {
45507         if (this._requestSubscription != null) {
45508             this._requestSubscription.unsubscribe();
45509             this._requestSubscription = null;
45510         }
45511         if (this._nodeRequestSubscription != null) {
45512             this._nodeRequestSubscription.unsubscribe();
45513             this._nodeRequestSubscription = null;
45514         }
45515         if (this._request$ != null) {
45516             if (!(this._request$.isStopped || this._request$.hasError)) {
45517                 this._request$.error(new Error_1.AbortMapillaryError("Request aborted by a subsequent request " + reason + "."));
45518             }
45519             this._request$ = null;
45520         }
45521     };
45522     Navigator.prototype._makeRequest$ = function (node$) {
45523         var _this = this;
45524         var request$ = new rxjs_1.ReplaySubject(1);
45525         this._requestSubscription = request$
45526             .subscribe(undefined, function () { });
45527         this._request$ = request$;
45528         this._nodeRequestSubscription = node$
45529             .subscribe(function (node) {
45530             _this._request$ = null;
45531             request$.next(node);
45532             request$.complete();
45533         }, function (error) {
45534             _this._request$ = null;
45535             request$.error(error);
45536         });
45537         return request$;
45538     };
45539     Navigator.prototype._moveToKey$ = function (key) {
45540         var _this = this;
45541         this._keyRequested$.next(key);
45542         return this._graphService.cacheNode$(key).pipe(operators_1.tap(function (node) {
45543             _this._stateService.setNodes([node]);
45544             _this._movedToKey$.next(node.key);
45545         }), operators_1.finalize(function () {
45546             _this._loadingService.stopLoading(_this._loadingName);
45547         }));
45548     };
45549     Navigator.prototype._trajectoryKeys$ = function () {
45550         return this._stateService.currentState$.pipe(operators_1.first(), operators_1.map(function (frame) {
45551             return frame.state.trajectory
45552                 .map(function (node) {
45553                 return node.key;
45554             });
45555         }));
45556     };
45557     return Navigator;
45558 }());
45559 exports.Navigator = Navigator;
45560 exports.default = Navigator;
45561
45562 },{"../API":273,"../Edge":275,"../Error":276,"../Graph":278,"../State":281,"../Viewer":285,"rxjs":26,"rxjs/operators":224}],439:[function(require,module,exports){
45563 "use strict";
45564 Object.defineProperty(exports, "__esModule", { value: true });
45565 var rxjs_1 = require("rxjs");
45566 var operators_1 = require("rxjs/operators");
45567 var Viewer_1 = require("../Viewer");
45568 var Observer = /** @class */ (function () {
45569     function Observer(eventEmitter, navigator, container) {
45570         var _this = this;
45571         this._container = container;
45572         this._eventEmitter = eventEmitter;
45573         this._navigator = navigator;
45574         this._projection = new Viewer_1.Projection();
45575         this._started = false;
45576         this._navigable$ = new rxjs_1.Subject();
45577         // navigable and loading should always emit, also when cover is activated.
45578         this._navigable$
45579             .subscribe(function (navigable) {
45580             _this._eventEmitter.fire(Viewer_1.Viewer.navigablechanged, navigable);
45581         });
45582         this._navigator.loadingService.loading$
45583             .subscribe(function (loading) {
45584             _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
45585         });
45586     }
45587     Object.defineProperty(Observer.prototype, "started", {
45588         get: function () {
45589             return this._started;
45590         },
45591         enumerable: true,
45592         configurable: true
45593     });
45594     Object.defineProperty(Observer.prototype, "navigable$", {
45595         get: function () {
45596             return this._navigable$;
45597         },
45598         enumerable: true,
45599         configurable: true
45600     });
45601     Observer.prototype.projectBasic$ = function (basicPoint) {
45602         var _this = this;
45603         return rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$).pipe(operators_1.first(), operators_1.map(function (_a) {
45604             var render = _a[0], transform = _a[1];
45605             var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform);
45606             return [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])];
45607         }));
45608     };
45609     Observer.prototype.startEmit = function () {
45610         var _this = this;
45611         if (this._started) {
45612             return;
45613         }
45614         this._started = true;
45615         this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
45616             .subscribe(function (node) {
45617             _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
45618         });
45619         this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$.pipe(operators_1.switchMap(function (node) {
45620             return node.sequenceEdges$;
45621         }))
45622             .subscribe(function (status) {
45623             _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
45624         });
45625         this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$.pipe(operators_1.switchMap(function (node) {
45626             return node.spatialEdges$;
45627         }))
45628             .subscribe(function (status) {
45629             _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
45630         });
45631         this._moveSubscription = rxjs_1.combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$).pipe(operators_1.map(function (values) {
45632             return values[0] || values[1] || values[2];
45633         }), operators_1.distinctUntilChanged())
45634             .subscribe(function (started) {
45635             if (started) {
45636                 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
45637             }
45638             else {
45639                 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
45640             }
45641         });
45642         this._bearingSubscription = this._container.renderService.bearing$.pipe(operators_1.auditTime(100), operators_1.distinctUntilChanged(function (b1, b2) {
45643             return Math.abs(b2 - b1) < 1;
45644         }))
45645             .subscribe(function (bearing) {
45646             _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
45647         });
45648         var mouseMove$ = this._container.mouseService.active$.pipe(operators_1.switchMap(function (active) {
45649             return active ?
45650                 rxjs_1.empty() :
45651                 _this._container.mouseService.mouseMove$;
45652         }));
45653         this._viewerMouseEventSubscription = rxjs_1.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$)).pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
45654             var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
45655             var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform);
45656             return {
45657                 basicPoint: unprojection.basicPoint,
45658                 latLon: unprojection.latLon,
45659                 originalEvent: event,
45660                 pixelPoint: unprojection.pixelPoint,
45661                 target: _this._eventEmitter,
45662                 type: type,
45663             };
45664         }))
45665             .subscribe(function (event) {
45666             _this._eventEmitter.fire(event.type, event);
45667         });
45668     };
45669     Observer.prototype.stopEmit = function () {
45670         if (!this.started) {
45671             return;
45672         }
45673         this._started = false;
45674         this._bearingSubscription.unsubscribe();
45675         this._currentNodeSubscription.unsubscribe();
45676         this._moveSubscription.unsubscribe();
45677         this._sequenceEdgesSubscription.unsubscribe();
45678         this._spatialEdgesSubscription.unsubscribe();
45679         this._viewerMouseEventSubscription.unsubscribe();
45680         this._bearingSubscription = null;
45681         this._currentNodeSubscription = null;
45682         this._moveSubscription = null;
45683         this._sequenceEdgesSubscription = null;
45684         this._spatialEdgesSubscription = null;
45685         this._viewerMouseEventSubscription = null;
45686     };
45687     Observer.prototype.unproject$ = function (canvasPoint) {
45688         var _this = this;
45689         return rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$).pipe(operators_1.first(), operators_1.map(function (_a) {
45690             var render = _a[0], reference = _a[1], transform = _a[2];
45691             var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform);
45692             return unprojection.latLon;
45693         }));
45694     };
45695     Observer.prototype.unprojectBasic$ = function (canvasPoint) {
45696         var _this = this;
45697         return rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$).pipe(operators_1.first(), operators_1.map(function (_a) {
45698             var render = _a[0], transform = _a[1];
45699             return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform);
45700         }));
45701     };
45702     Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
45703         return mouseEvent$.pipe(operators_1.map(function (event) {
45704             return [type, event];
45705         }));
45706     };
45707     return Observer;
45708 }());
45709 exports.Observer = Observer;
45710 exports.default = Observer;
45711
45712 },{"../Viewer":285,"rxjs":26,"rxjs/operators":224}],440:[function(require,module,exports){
45713 "use strict";
45714 Object.defineProperty(exports, "__esModule", { value: true });
45715 var rxjs_1 = require("rxjs");
45716 var operators_1 = require("rxjs/operators");
45717 var Edge_1 = require("../Edge");
45718 var Graph_1 = require("../Graph");
45719 var PlayService = /** @class */ (function () {
45720     function PlayService(graphService, stateService, graphCalculator) {
45721         this._graphService = graphService;
45722         this._stateService = stateService;
45723         this._graphCalculator = !!graphCalculator ? graphCalculator : new Graph_1.GraphCalculator();
45724         this._directionSubject$ = new rxjs_1.Subject();
45725         this._direction$ = this._directionSubject$.pipe(operators_1.startWith(Edge_1.EdgeDirection.Next), operators_1.publishReplay(1), operators_1.refCount());
45726         this._direction$.subscribe();
45727         this._playing = false;
45728         this._playingSubject$ = new rxjs_1.Subject();
45729         this._playing$ = this._playingSubject$.pipe(operators_1.startWith(this._playing), operators_1.publishReplay(1), operators_1.refCount());
45730         this._playing$.subscribe();
45731         this._speed = 0.5;
45732         this._speedSubject$ = new rxjs_1.Subject();
45733         this._speed$ = this._speedSubject$.pipe(operators_1.startWith(this._speed), operators_1.publishReplay(1), operators_1.refCount());
45734         this._speed$.subscribe();
45735         this._nodesAhead = this._mapNodesAhead(this._mapSpeed(this._speed));
45736         this._bridging$ = null;
45737     }
45738     Object.defineProperty(PlayService.prototype, "playing", {
45739         get: function () {
45740             return this._playing;
45741         },
45742         enumerable: true,
45743         configurable: true
45744     });
45745     Object.defineProperty(PlayService.prototype, "direction$", {
45746         get: function () {
45747             return this._direction$;
45748         },
45749         enumerable: true,
45750         configurable: true
45751     });
45752     Object.defineProperty(PlayService.prototype, "playing$", {
45753         get: function () {
45754             return this._playing$;
45755         },
45756         enumerable: true,
45757         configurable: true
45758     });
45759     Object.defineProperty(PlayService.prototype, "speed$", {
45760         get: function () {
45761             return this._speed$;
45762         },
45763         enumerable: true,
45764         configurable: true
45765     });
45766     PlayService.prototype.play = function () {
45767         var _this = this;
45768         if (this._playing) {
45769             return;
45770         }
45771         this._stateService.cutNodes();
45772         var stateSpeed = this._setSpeed(this._speed);
45773         this._stateService.setSpeed(stateSpeed);
45774         this._graphModeSubscription = this._speed$.pipe(operators_1.map(function (speed) {
45775             return speed > PlayService.sequenceSpeed ? Graph_1.GraphMode.Sequence : Graph_1.GraphMode.Spatial;
45776         }), operators_1.distinctUntilChanged())
45777             .subscribe(function (mode) {
45778             _this._graphService.setGraphMode(mode);
45779         });
45780         this._cacheSubscription = rxjs_1.combineLatest(this._stateService.currentNode$.pipe(operators_1.map(function (node) {
45781             return [node.sequenceKey, node.key];
45782         }), operators_1.distinctUntilChanged(undefined, function (_a) {
45783             var sequenceKey = _a[0], nodeKey = _a[1];
45784             return sequenceKey;
45785         })), this._graphService.graphMode$, this._direction$).pipe(operators_1.switchMap(function (_a) {
45786             var _b = _a[0], sequenceKey = _b[0], nodeKey = _b[1], mode = _a[1], direction = _a[2];
45787             if (direction !== Edge_1.EdgeDirection.Next && direction !== Edge_1.EdgeDirection.Prev) {
45788                 return rxjs_1.of([undefined, direction]);
45789             }
45790             var sequence$ = (mode === Graph_1.GraphMode.Sequence ?
45791                 _this._graphService.cacheSequenceNodes$(sequenceKey, nodeKey) :
45792                 _this._graphService.cacheSequence$(sequenceKey)).pipe(operators_1.retry(3), operators_1.catchError(function (error) {
45793                 console.error(error);
45794                 return rxjs_1.of(undefined);
45795             }));
45796             return rxjs_1.combineLatest(sequence$, rxjs_1.of(direction));
45797         }), operators_1.switchMap(function (_a) {
45798             var sequence = _a[0], direction = _a[1];
45799             if (sequence === undefined) {
45800                 return rxjs_1.empty();
45801             }
45802             var sequenceKeys = sequence.keys.slice();
45803             if (direction === Edge_1.EdgeDirection.Prev) {
45804                 sequenceKeys.reverse();
45805             }
45806             return _this._stateService.currentState$.pipe(operators_1.map(function (frame) {
45807                 return [frame.state.trajectory[frame.state.trajectory.length - 1].key, frame.state.nodesAhead];
45808             }), operators_1.scan(function (_a, _b) {
45809                 var lastRequestKey = _a[0], previousRequestKeys = _a[1];
45810                 var lastTrajectoryKey = _b[0], nodesAhead = _b[1];
45811                 if (lastRequestKey === undefined) {
45812                     lastRequestKey = lastTrajectoryKey;
45813                 }
45814                 var lastIndex = sequenceKeys.length - 1;
45815                 if (nodesAhead >= _this._nodesAhead || sequenceKeys[lastIndex] === lastRequestKey) {
45816                     return [lastRequestKey, []];
45817                 }
45818                 var current = sequenceKeys.indexOf(lastTrajectoryKey);
45819                 var start = sequenceKeys.indexOf(lastRequestKey) + 1;
45820                 var end = Math.min(lastIndex, current + _this._nodesAhead - nodesAhead) + 1;
45821                 if (end <= start) {
45822                     return [lastRequestKey, []];
45823                 }
45824                 return [sequenceKeys[end - 1], sequenceKeys.slice(start, end)];
45825             }, [undefined, []]), operators_1.mergeMap(function (_a) {
45826                 var lastRequestKey = _a[0], newRequestKeys = _a[1];
45827                 return rxjs_1.from(newRequestKeys);
45828             }));
45829         }), operators_1.mergeMap(function (key) {
45830             return _this._graphService.cacheNode$(key).pipe(operators_1.catchError(function () {
45831                 return rxjs_1.empty();
45832             }));
45833         }, 6))
45834             .subscribe();
45835         this._playingSubscription = this._stateService.currentState$.pipe(operators_1.filter(function (frame) {
45836             return frame.state.nodesAhead < _this._nodesAhead;
45837         }), operators_1.distinctUntilChanged(undefined, function (frame) {
45838             return frame.state.lastNode.key;
45839         }), operators_1.map(function (frame) {
45840             var lastNode = frame.state.lastNode;
45841             var trajectory = frame.state.trajectory;
45842             var increasingTime = undefined;
45843             for (var i = trajectory.length - 2; i >= 0; i--) {
45844                 var node = trajectory[i];
45845                 if (node.sequenceKey !== lastNode.sequenceKey) {
45846                     break;
45847                 }
45848                 if (node.capturedAt !== lastNode.capturedAt) {
45849                     increasingTime = node.capturedAt < lastNode.capturedAt;
45850                     break;
45851                 }
45852             }
45853             return [frame.state.lastNode, increasingTime];
45854         }), operators_1.withLatestFrom(this._direction$), operators_1.switchMap(function (_a) {
45855             var _b = _a[0], node = _b[0], increasingTime = _b[1], direction = _a[1];
45856             return rxjs_1.zip(([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
45857                 node.sequenceEdges$ :
45858                 node.spatialEdges$).pipe(operators_1.first(function (status) {
45859                 return status.cached;
45860             }), operators_1.timeout(15000)), rxjs_1.of(direction)).pipe(operators_1.map(function (_a) {
45861                 var s = _a[0], d = _a[1];
45862                 for (var _i = 0, _b = s.edges; _i < _b.length; _i++) {
45863                     var edge = _b[_i];
45864                     if (edge.data.direction === d) {
45865                         return edge.to;
45866                     }
45867                 }
45868                 return null;
45869             }), operators_1.switchMap(function (key) {
45870                 return key != null ?
45871                     _this._graphService.cacheNode$(key) :
45872                     _this._bridge$(node, increasingTime).pipe(operators_1.filter(function (n) {
45873                         return !!n;
45874                     }));
45875             }));
45876         }))
45877             .subscribe(function (node) {
45878             _this._stateService.appendNodes([node]);
45879         }, function (error) {
45880             console.error(error);
45881             _this.stop();
45882         });
45883         this._clearSubscription = this._stateService.currentNode$.pipe(operators_1.bufferCount(1, 10))
45884             .subscribe(function (nodes) {
45885             _this._stateService.clearPriorNodes();
45886         });
45887         this._setPlaying(true);
45888         var currentLastNodes$ = this._stateService.currentState$.pipe(operators_1.map(function (frame) {
45889             return frame.state;
45890         }), operators_1.distinctUntilChanged(function (_a, _b) {
45891             var kc1 = _a[0], kl1 = _a[1];
45892             var kc2 = _b[0], kl2 = _b[1];
45893             return kc1 === kc2 && kl1 === kl2;
45894         }, function (state) {
45895             return [state.currentNode.key, state.lastNode.key];
45896         }), operators_1.filter(function (state) {
45897             return state.currentNode.key === state.lastNode.key &&
45898                 state.currentIndex === state.trajectory.length - 1;
45899         }), operators_1.map(function (state) {
45900             return state.currentNode;
45901         }));
45902         this._stopSubscription = rxjs_1.combineLatest(currentLastNodes$, this._direction$).pipe(operators_1.switchMap(function (_a) {
45903             var node = _a[0], direction = _a[1];
45904             var edgeStatus$ = ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
45905                 node.sequenceEdges$ :
45906                 node.spatialEdges$).pipe(operators_1.first(function (status) {
45907                 return status.cached;
45908             }), operators_1.timeout(15000), operators_1.catchError(function (error) {
45909                 console.error(error);
45910                 return rxjs_1.of({ cached: false, edges: [] });
45911             }));
45912             return rxjs_1.combineLatest(rxjs_1.of(direction), edgeStatus$).pipe(operators_1.map(function (_a) {
45913                 var d = _a[0], es = _a[1];
45914                 for (var _i = 0, _b = es.edges; _i < _b.length; _i++) {
45915                     var edge = _b[_i];
45916                     if (edge.data.direction === d) {
45917                         return true;
45918                     }
45919                 }
45920                 return false;
45921             }));
45922         }), operators_1.mergeMap(function (hasEdge) {
45923             if (hasEdge || !_this._bridging$) {
45924                 return rxjs_1.of(hasEdge);
45925             }
45926             return _this._bridging$.pipe(operators_1.map(function (node) {
45927                 return node != null;
45928             }), operators_1.catchError(function (error) {
45929                 console.error(error);
45930                 return rxjs_1.of(false);
45931             }));
45932         }), operators_1.first(function (hasEdge) {
45933             return !hasEdge;
45934         }))
45935             .subscribe(undefined, undefined, function () { _this.stop(); });
45936         if (this._stopSubscription.closed) {
45937             this._stopSubscription = null;
45938         }
45939     };
45940     PlayService.prototype.setDirection = function (direction) {
45941         this._directionSubject$.next(direction);
45942     };
45943     PlayService.prototype.setSpeed = function (speed) {
45944         speed = Math.max(0, Math.min(1, speed));
45945         if (speed === this._speed) {
45946             return;
45947         }
45948         var stateSpeed = this._setSpeed(speed);
45949         if (this._playing) {
45950             this._stateService.setSpeed(stateSpeed);
45951         }
45952         this._speedSubject$.next(this._speed);
45953     };
45954     PlayService.prototype.stop = function () {
45955         if (!this._playing) {
45956             return;
45957         }
45958         if (!!this._stopSubscription) {
45959             if (!this._stopSubscription.closed) {
45960                 this._stopSubscription.unsubscribe();
45961             }
45962             this._stopSubscription = null;
45963         }
45964         this._graphModeSubscription.unsubscribe();
45965         this._graphModeSubscription = null;
45966         this._cacheSubscription.unsubscribe();
45967         this._cacheSubscription = null;
45968         this._playingSubscription.unsubscribe();
45969         this._playingSubscription = null;
45970         this._clearSubscription.unsubscribe();
45971         this._clearSubscription = null;
45972         this._stateService.setSpeed(1);
45973         this._stateService.cutNodes();
45974         this._graphService.setGraphMode(Graph_1.GraphMode.Spatial);
45975         this._setPlaying(false);
45976     };
45977     PlayService.prototype._bridge$ = function (node, increasingTime) {
45978         var _this = this;
45979         if (increasingTime === undefined) {
45980             return rxjs_1.of(null);
45981         }
45982         var boundingBox = this._graphCalculator.boundingBoxCorners(node.latLon, 25);
45983         this._bridging$ = this._graphService.cacheBoundingBox$(boundingBox[0], boundingBox[1]).pipe(operators_1.mergeMap(function (nodes) {
45984             var nextNode = null;
45985             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
45986                 var n = nodes_1[_i];
45987                 if (n.sequenceKey === node.sequenceKey ||
45988                     !n.cameraUuid ||
45989                     n.cameraUuid !== node.cameraUuid ||
45990                     n.capturedAt === node.capturedAt ||
45991                     n.capturedAt > node.capturedAt !== increasingTime) {
45992                     continue;
45993                 }
45994                 var delta = Math.abs(n.capturedAt - node.capturedAt);
45995                 if (delta > 15000) {
45996                     continue;
45997                 }
45998                 if (!nextNode || delta < Math.abs(nextNode.capturedAt - node.capturedAt)) {
45999                     nextNode = n;
46000                 }
46001             }
46002             return !!nextNode ?
46003                 _this._graphService.cacheNode$(nextNode.key) :
46004                 rxjs_1.of(null);
46005         }), operators_1.finalize(function () {
46006             _this._bridging$ = null;
46007         }), operators_1.publish(), operators_1.refCount());
46008         return this._bridging$;
46009     };
46010     PlayService.prototype._mapSpeed = function (speed) {
46011         var x = 2 * speed - 1;
46012         return Math.pow(10, x) - 0.2 * x;
46013     };
46014     PlayService.prototype._mapNodesAhead = function (stateSpeed) {
46015         return Math.round(Math.max(10, Math.min(50, 8 + 6 * stateSpeed)));
46016     };
46017     PlayService.prototype._setPlaying = function (playing) {
46018         this._playing = playing;
46019         this._playingSubject$.next(playing);
46020     };
46021     PlayService.prototype._setSpeed = function (speed) {
46022         this._speed = speed;
46023         var stateSpeed = this._mapSpeed(this._speed);
46024         this._nodesAhead = this._mapNodesAhead(stateSpeed);
46025         return stateSpeed;
46026     };
46027     PlayService.sequenceSpeed = 0.54;
46028     return PlayService;
46029 }());
46030 exports.PlayService = PlayService;
46031 exports.default = PlayService;
46032
46033 },{"../Edge":275,"../Graph":278,"rxjs":26,"rxjs/operators":224}],441:[function(require,module,exports){
46034 "use strict";
46035 Object.defineProperty(exports, "__esModule", { value: true });
46036 var THREE = require("three");
46037 var Geo_1 = require("../Geo");
46038 var Projection = /** @class */ (function () {
46039     function Projection(geoCoords, viewportCoords) {
46040         this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
46041         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
46042     }
46043     Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) {
46044         return this._viewportCoords
46045             .basicToCanvas(basicPoint[0], basicPoint[1], container, transform, render.perspective);
46046     };
46047     Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) {
46048         var basicPoint = this._viewportCoords
46049             .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective);
46050         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
46051             basicPoint = null;
46052         }
46053         return basicPoint;
46054     };
46055     Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) {
46056         var pixelPoint = this._viewportCoords.canvasPosition(event, container);
46057         return this.canvasToUnprojection(pixelPoint, container, render, reference, transform);
46058     };
46059     Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) {
46060         var canvasX = canvasPoint[0];
46061         var canvasY = canvasPoint[1];
46062         var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
46063         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
46064             .unproject(render.perspective);
46065         var basicPoint = transform.projectBasic(point3d.toArray());
46066         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
46067             basicPoint = null;
46068         }
46069         var direction3d = point3d.clone().sub(render.camera.position).normalize();
46070         var dist = -2 / direction3d.z;
46071         var latLon = null;
46072         if (dist > 0 && dist < 100 && !!basicPoint) {
46073             var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
46074             var latLonArray = this._geoCoords
46075                 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
46076                 .slice(0, 2);
46077             latLon = { lat: latLonArray[0], lon: latLonArray[1] };
46078         }
46079         var unprojection = {
46080             basicPoint: basicPoint,
46081             latLon: latLon,
46082             pixelPoint: [canvasX, canvasY],
46083         };
46084         return unprojection;
46085     };
46086     return Projection;
46087 }());
46088 exports.Projection = Projection;
46089 exports.default = Projection;
46090
46091 },{"../Geo":277,"three":225}],442:[function(require,module,exports){
46092 "use strict";
46093 Object.defineProperty(exports, "__esModule", { value: true });
46094 var operators_1 = require("rxjs/operators");
46095 var THREE = require("three");
46096 var vd = require("virtual-dom");
46097 var rxjs_1 = require("rxjs");
46098 var Viewer_1 = require("../Viewer");
46099 var SpriteAtlas = /** @class */ (function () {
46100     function SpriteAtlas() {
46101     }
46102     Object.defineProperty(SpriteAtlas.prototype, "json", {
46103         set: function (value) {
46104             this._json = value;
46105         },
46106         enumerable: true,
46107         configurable: true
46108     });
46109     Object.defineProperty(SpriteAtlas.prototype, "image", {
46110         set: function (value) {
46111             this._image = value;
46112             this._texture = new THREE.Texture(this._image);
46113             this._texture.minFilter = THREE.NearestFilter;
46114         },
46115         enumerable: true,
46116         configurable: true
46117     });
46118     Object.defineProperty(SpriteAtlas.prototype, "loaded", {
46119         get: function () {
46120             return !!(this._image && this._json);
46121         },
46122         enumerable: true,
46123         configurable: true
46124     });
46125     SpriteAtlas.prototype.getGLSprite = function (name) {
46126         if (!this.loaded) {
46127             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
46128         }
46129         var definition = this._json[name];
46130         if (!definition) {
46131             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
46132             return new THREE.Object3D();
46133         }
46134         var texture = this._texture.clone();
46135         texture.needsUpdate = true;
46136         var width = this._image.width;
46137         var height = this._image.height;
46138         texture.offset.x = definition.x / width;
46139         texture.offset.y = (height - definition.y - definition.height) / height;
46140         texture.repeat.x = definition.width / width;
46141         texture.repeat.y = definition.height / height;
46142         var material = new THREE.SpriteMaterial({ map: texture });
46143         return new THREE.Sprite(material);
46144     };
46145     SpriteAtlas.prototype.getDOMSprite = function (name, float) {
46146         if (!this.loaded) {
46147             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
46148         }
46149         if (float == null) {
46150             float = Viewer_1.Alignment.Center;
46151         }
46152         var definition = this._json[name];
46153         if (!definition) {
46154             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
46155             return vd.h("div", {}, []);
46156         }
46157         var clipTop = definition.y;
46158         var clipRigth = definition.x + definition.width;
46159         var clipBottom = definition.y + definition.height;
46160         var clipLeft = definition.x;
46161         var left = -definition.x;
46162         var top = -definition.y;
46163         var height = this._image.height;
46164         var width = this._image.width;
46165         switch (float) {
46166             case Viewer_1.Alignment.Bottom:
46167             case Viewer_1.Alignment.Center:
46168             case Viewer_1.Alignment.Top:
46169                 left -= definition.width / 2;
46170                 break;
46171             case Viewer_1.Alignment.BottomLeft:
46172             case Viewer_1.Alignment.Left:
46173             case Viewer_1.Alignment.TopLeft:
46174                 left -= definition.width;
46175                 break;
46176             case Viewer_1.Alignment.BottomRight:
46177             case Viewer_1.Alignment.Right:
46178             case Viewer_1.Alignment.TopRight:
46179             default:
46180                 break;
46181         }
46182         switch (float) {
46183             case Viewer_1.Alignment.Center:
46184             case Viewer_1.Alignment.Left:
46185             case Viewer_1.Alignment.Right:
46186                 top -= definition.height / 2;
46187                 break;
46188             case Viewer_1.Alignment.Top:
46189             case Viewer_1.Alignment.TopLeft:
46190             case Viewer_1.Alignment.TopRight:
46191                 top -= definition.height;
46192                 break;
46193             case Viewer_1.Alignment.Bottom:
46194             case Viewer_1.Alignment.BottomLeft:
46195             case Viewer_1.Alignment.BottomRight:
46196             default:
46197                 break;
46198         }
46199         var pixelRatioInverse = 1 / definition.pixelRatio;
46200         clipTop *= pixelRatioInverse;
46201         clipRigth *= pixelRatioInverse;
46202         clipBottom *= pixelRatioInverse;
46203         clipLeft *= pixelRatioInverse;
46204         left *= pixelRatioInverse;
46205         top *= pixelRatioInverse;
46206         height *= pixelRatioInverse;
46207         width *= pixelRatioInverse;
46208         var properties = {
46209             src: this._image.src,
46210             style: {
46211                 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
46212                 height: height + "px",
46213                 left: left + "px",
46214                 position: "absolute",
46215                 top: top + "px",
46216                 width: width + "px",
46217             },
46218         };
46219         return vd.h("img", properties, []);
46220     };
46221     return SpriteAtlas;
46222 }());
46223 var SpriteService = /** @class */ (function () {
46224     function SpriteService(sprite) {
46225         var _this = this;
46226         this._retina = window.devicePixelRatio > 1;
46227         this._spriteAtlasOperation$ = new rxjs_1.Subject();
46228         this._spriteAtlas$ = this._spriteAtlasOperation$.pipe(operators_1.startWith(function (atlas) {
46229             return atlas;
46230         }), operators_1.scan(function (atlas, operation) {
46231             return operation(atlas);
46232         }, new SpriteAtlas()), operators_1.publishReplay(1), operators_1.refCount());
46233         this._spriteAtlas$.subscribe(function () { });
46234         if (sprite == null) {
46235             return;
46236         }
46237         var format = this._retina ? "@2x" : "";
46238         var imageXmlHTTP = new XMLHttpRequest();
46239         imageXmlHTTP.open("GET", sprite + format + ".png", true);
46240         imageXmlHTTP.responseType = "arraybuffer";
46241         imageXmlHTTP.onload = function () {
46242             var image = new Image();
46243             image.onload = function () {
46244                 _this._spriteAtlasOperation$.next(function (atlas) {
46245                     atlas.image = image;
46246                     return atlas;
46247                 });
46248             };
46249             var blob = new Blob([imageXmlHTTP.response]);
46250             image.src = window.URL.createObjectURL(blob);
46251         };
46252         imageXmlHTTP.onerror = function (error) {
46253             console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
46254         };
46255         imageXmlHTTP.send();
46256         var jsonXmlHTTP = new XMLHttpRequest();
46257         jsonXmlHTTP.open("GET", sprite + format + ".json", true);
46258         jsonXmlHTTP.responseType = "text";
46259         jsonXmlHTTP.onload = function () {
46260             var json = JSON.parse(jsonXmlHTTP.response);
46261             _this._spriteAtlasOperation$.next(function (atlas) {
46262                 atlas.json = json;
46263                 return atlas;
46264             });
46265         };
46266         jsonXmlHTTP.onerror = function (error) {
46267             console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
46268         };
46269         jsonXmlHTTP.send();
46270     }
46271     Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
46272         get: function () {
46273             return this._spriteAtlas$;
46274         },
46275         enumerable: true,
46276         configurable: true
46277     });
46278     return SpriteService;
46279 }());
46280 exports.SpriteService = SpriteService;
46281 exports.default = SpriteService;
46282
46283
46284 },{"../Viewer":285,"rxjs":26,"rxjs/operators":224,"three":225,"virtual-dom":230}],443:[function(require,module,exports){
46285 "use strict";
46286 Object.defineProperty(exports, "__esModule", { value: true });
46287 var rxjs_1 = require("rxjs");
46288 var operators_1 = require("rxjs/operators");
46289 var TouchService = /** @class */ (function () {
46290     function TouchService(canvasContainer, domContainer) {
46291         var _this = this;
46292         this._activeSubject$ = new rxjs_1.BehaviorSubject(false);
46293         this._active$ = this._activeSubject$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
46294         rxjs_1.fromEvent(domContainer, "touchmove")
46295             .subscribe(function (event) {
46296             event.preventDefault();
46297         });
46298         this._touchStart$ = rxjs_1.fromEvent(canvasContainer, "touchstart");
46299         this._touchMove$ = rxjs_1.fromEvent(canvasContainer, "touchmove");
46300         this._touchEnd$ = rxjs_1.fromEvent(canvasContainer, "touchend");
46301         this._touchCancel$ = rxjs_1.fromEvent(canvasContainer, "touchcancel");
46302         var tapStart$ = this._touchStart$.pipe(operators_1.filter(function (te) {
46303             return te.touches.length === 1 && te.targetTouches.length === 1;
46304         }), operators_1.share());
46305         this._doubleTap$ = tapStart$.pipe(operators_1.bufferWhen(function () {
46306             return tapStart$.pipe(operators_1.first(), operators_1.switchMap(function (event) {
46307                 return rxjs_1.merge(rxjs_1.timer(300), tapStart$).pipe(operators_1.take(1));
46308             }));
46309         }), operators_1.filter(function (events) {
46310             return events.length === 2;
46311         }), operators_1.map(function (events) {
46312             return events[events.length - 1];
46313         }), operators_1.share());
46314         this._doubleTap$
46315             .subscribe(function (event) {
46316             event.preventDefault();
46317         });
46318         this._singleTouchMove$ = this._touchMove$.pipe(operators_1.filter(function (te) {
46319             return te.touches.length === 1 && te.targetTouches.length === 1;
46320         }), operators_1.share());
46321         var singleTouchStart$ = rxjs_1.merge(this._touchStart$, this._touchEnd$, this._touchCancel$).pipe(operators_1.filter(function (te) {
46322             return te.touches.length === 1 && te.targetTouches.length === 1;
46323         }));
46324         var multipleTouchStart$ = rxjs_1.merge(this._touchStart$, this._touchEnd$, this._touchCancel$).pipe(operators_1.filter(function (te) {
46325             return te.touches.length >= 1;
46326         }));
46327         var touchStop$ = rxjs_1.merge(this._touchEnd$, this._touchCancel$).pipe(operators_1.filter(function (te) {
46328             return te.touches.length === 0;
46329         }));
46330         this._singleTouchDragStart$ = singleTouchStart$.pipe(operators_1.mergeMap(function (e) {
46331             return _this._singleTouchMove$.pipe(operators_1.takeUntil(rxjs_1.merge(touchStop$, multipleTouchStart$)), operators_1.take(1));
46332         }));
46333         this._singleTouchDragEnd$ = singleTouchStart$.pipe(operators_1.mergeMap(function (e) {
46334             return rxjs_1.merge(touchStop$, multipleTouchStart$).pipe(operators_1.first());
46335         }));
46336         this._singleTouchDrag$ = singleTouchStart$.pipe(operators_1.switchMap(function (te) {
46337             return _this._singleTouchMove$.pipe(operators_1.skip(1), operators_1.takeUntil(rxjs_1.merge(multipleTouchStart$, touchStop$)));
46338         }));
46339         var touchesChanged$ = rxjs_1.merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
46340         this._pinchStart$ = touchesChanged$.pipe(operators_1.filter(function (te) {
46341             return te.touches.length === 2 && te.targetTouches.length === 2;
46342         }));
46343         this._pinchEnd$ = touchesChanged$.pipe(operators_1.filter(function (te) {
46344             return te.touches.length !== 2 || te.targetTouches.length !== 2;
46345         }));
46346         this._pinchOperation$ = new rxjs_1.Subject();
46347         this._pinch$ = this._pinchOperation$.pipe(operators_1.scan(function (pinch, operation) {
46348             return operation(pinch);
46349         }, {
46350             changeX: 0,
46351             changeY: 0,
46352             clientX: 0,
46353             clientY: 0,
46354             distance: 0,
46355             distanceChange: 0,
46356             distanceX: 0,
46357             distanceY: 0,
46358             originalEvent: null,
46359             pageX: 0,
46360             pageY: 0,
46361             screenX: 0,
46362             screenY: 0,
46363             touch1: null,
46364             touch2: null,
46365         }));
46366         this._touchMove$.pipe(operators_1.filter(function (te) {
46367             return te.touches.length === 2 && te.targetTouches.length === 2;
46368         }), operators_1.map(function (te) {
46369             return function (previous) {
46370                 var touch1 = te.touches[0];
46371                 var touch2 = te.touches[1];
46372                 var minX = Math.min(touch1.clientX, touch2.clientX);
46373                 var maxX = Math.max(touch1.clientX, touch2.clientX);
46374                 var minY = Math.min(touch1.clientY, touch2.clientY);
46375                 var maxY = Math.max(touch1.clientY, touch2.clientY);
46376                 var centerClientX = minX + (maxX - minX) / 2;
46377                 var centerClientY = minY + (maxY - minY) / 2;
46378                 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
46379                 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
46380                 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
46381                 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
46382                 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
46383                 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
46384                 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
46385                 var distanceChange = distance - previous.distance;
46386                 var changeX = distanceX - previous.distanceX;
46387                 var changeY = distanceY - previous.distanceY;
46388                 var current = {
46389                     changeX: changeX,
46390                     changeY: changeY,
46391                     clientX: centerClientX,
46392                     clientY: centerClientY,
46393                     distance: distance,
46394                     distanceChange: distanceChange,
46395                     distanceX: distanceX,
46396                     distanceY: distanceY,
46397                     originalEvent: te,
46398                     pageX: centerPageX,
46399                     pageY: centerPageY,
46400                     screenX: centerScreenX,
46401                     screenY: centerScreenY,
46402                     touch1: touch1,
46403                     touch2: touch2,
46404                 };
46405                 return current;
46406             };
46407         }))
46408             .subscribe(this._pinchOperation$);
46409         this._pinchChange$ = this._pinchStart$.pipe(operators_1.switchMap(function (te) {
46410             return _this._pinch$.pipe(operators_1.skip(1), operators_1.takeUntil(_this._pinchEnd$));
46411         }));
46412     }
46413     Object.defineProperty(TouchService.prototype, "active$", {
46414         get: function () {
46415             return this._active$;
46416         },
46417         enumerable: true,
46418         configurable: true
46419     });
46420     Object.defineProperty(TouchService.prototype, "activate$", {
46421         get: function () {
46422             return this._activeSubject$;
46423         },
46424         enumerable: true,
46425         configurable: true
46426     });
46427     Object.defineProperty(TouchService.prototype, "doubleTap$", {
46428         get: function () {
46429             return this._doubleTap$;
46430         },
46431         enumerable: true,
46432         configurable: true
46433     });
46434     Object.defineProperty(TouchService.prototype, "touchStart$", {
46435         get: function () {
46436             return this._touchStart$;
46437         },
46438         enumerable: true,
46439         configurable: true
46440     });
46441     Object.defineProperty(TouchService.prototype, "touchMove$", {
46442         get: function () {
46443             return this._touchMove$;
46444         },
46445         enumerable: true,
46446         configurable: true
46447     });
46448     Object.defineProperty(TouchService.prototype, "touchEnd$", {
46449         get: function () {
46450             return this._touchEnd$;
46451         },
46452         enumerable: true,
46453         configurable: true
46454     });
46455     Object.defineProperty(TouchService.prototype, "touchCancel$", {
46456         get: function () {
46457             return this._touchCancel$;
46458         },
46459         enumerable: true,
46460         configurable: true
46461     });
46462     Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
46463         get: function () {
46464             return this._singleTouchDragStart$;
46465         },
46466         enumerable: true,
46467         configurable: true
46468     });
46469     Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
46470         get: function () {
46471             return this._singleTouchDrag$;
46472         },
46473         enumerable: true,
46474         configurable: true
46475     });
46476     Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
46477         get: function () {
46478             return this._singleTouchDragEnd$;
46479         },
46480         enumerable: true,
46481         configurable: true
46482     });
46483     Object.defineProperty(TouchService.prototype, "pinch$", {
46484         get: function () {
46485             return this._pinchChange$;
46486         },
46487         enumerable: true,
46488         configurable: true
46489     });
46490     Object.defineProperty(TouchService.prototype, "pinchStart$", {
46491         get: function () {
46492             return this._pinchStart$;
46493         },
46494         enumerable: true,
46495         configurable: true
46496     });
46497     Object.defineProperty(TouchService.prototype, "pinchEnd$", {
46498         get: function () {
46499             return this._pinchEnd$;
46500         },
46501         enumerable: true,
46502         configurable: true
46503     });
46504     return TouchService;
46505 }());
46506 exports.TouchService = TouchService;
46507
46508 },{"rxjs":26,"rxjs/operators":224}],444:[function(require,module,exports){
46509 "use strict";
46510 var __extends = (this && this.__extends) || (function () {
46511     var extendStatics = function (d, b) {
46512         extendStatics = Object.setPrototypeOf ||
46513             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
46514             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
46515         return extendStatics(d, b);
46516     }
46517     return function (d, b) {
46518         extendStatics(d, b);
46519         function __() { this.constructor = d; }
46520         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
46521     };
46522 })();
46523 Object.defineProperty(exports, "__esModule", { value: true });
46524 var rxjs_1 = require("rxjs");
46525 var operators_1 = require("rxjs/operators");
46526 var when = require("when");
46527 var Viewer_1 = require("../Viewer");
46528 var Utils_1 = require("../Utils");
46529 /**
46530  * @class Viewer
46531  *
46532  * @classdesc The Viewer object represents the navigable image viewer.
46533  * Create a Viewer by specifying a container, client ID, image key and
46534  * other options. The viewer exposes methods and events for programmatic
46535  * interaction.
46536  *
46537  * In the case of asynchronous methods, MapillaryJS returns promises to
46538  * the results. Notifications are always emitted through JavaScript events.
46539  *
46540  * The viewer works with a few different coordinate systems.
46541  *
46542  * Container pixel coordinates
46543  *
46544  * Pixel coordinates are coordinates on the viewer container. The origin is
46545  * in the top left corner of the container. The axes are
46546  * directed according to the following for a viewer container with a width
46547  * of 640 pixels and height of 480 pixels.
46548  *
46549  * ```
46550  * (0,0)                          (640, 0)
46551  *      +------------------------>
46552  *      |
46553  *      |
46554  *      |
46555  *      v                        +
46556  * (0, 480)                       (640, 480)
46557  * ```
46558  *
46559  * Basic image coordinates
46560  *
46561  * Basic image coordinates represents points in the original image adjusted for
46562  * orientation. They range from 0 to 1 on both axes. The origin is in the top left
46563  * corner of the image and the axes are directed
46564  * according to the following for all image types.
46565  *
46566  * ```
46567  * (0,0)                          (1, 0)
46568  *      +------------------------>
46569  *      |
46570  *      |
46571  *      |
46572  *      v                        +
46573  * (0, 1)                         (1, 1)
46574  * ```
46575  *
46576  * For every camera viewing direction it is possible to convert between these
46577  * two coordinate systems for the current node. The image can be panned and
46578  * zoomed independently of the size of the viewer container resulting in
46579  * different conversion results for different viewing directions.
46580  */
46581 var Viewer = /** @class */ (function (_super) {
46582     __extends(Viewer, _super);
46583     /**
46584      * Create a new viewer instance.
46585      *
46586      * @description It is possible to initialize the viewer with or
46587      * without a key.
46588      *
46589      * When you want to show a specific image in the viewer from
46590      * the start you should initialize it with a key.
46591      *
46592      * When you do not know the first image key at implementation
46593      * time, e.g. in a map-viewer application you should initialize
46594      * the viewer without a key and call `moveToKey` instead.
46595      *
46596      * When initializing with a key the viewer is bound to that key
46597      * until the node for that key has been successfully loaded.
46598      * Also, a cover with the image of the key will be shown.
46599      * If the data for that key can not be loaded because the key is
46600      * faulty or other errors occur it is not possible to navigate
46601      * to another key because the viewer is not navigable. The viewer
46602      * becomes navigable when the data for the key has been loaded and
46603      * the image is shown in the viewer. This way of initializing
46604      * the viewer is mostly for embedding in blog posts and similar
46605      * where one wants to show a specific image initially.
46606      *
46607      * If the viewer is initialized without a key (with null or
46608      * undefined) it is not bound to any particular key and it is
46609      * possible to move to any key with `viewer.moveToKey("<my-image-key>")`.
46610      * If the first move to a key fails it is possible to move to another
46611      * key. The viewer will show a black background until a move
46612      * succeeds. This way of intitializing is suited for a map-viewer
46613      * application when the initial key is not known at implementation
46614      * time.
46615      *
46616      * @param {string} id - Required `id` of a DOM element which will
46617      * be transformed into the viewer.
46618      * @param {string} clientId - Required `Mapillary API ClientID`. Can
46619      * be obtained from https://www.mapillary.com/app/settings/developers.
46620      * @param {string} key - Optional `image-key` to start from. The key
46621      * can be any Mapillary image. If a key is provided the viewer is
46622      * bound to that key until it has been fully loaded. If null is provided
46623      * no image is loaded at viewer initialization and the viewer is not
46624      * bound to any particular key. Any image can then be navigated to
46625      * with e.g. `viewer.moveToKey("<my-image-key>")`.
46626      * @param {IViewerOptions} options - Optional configuration object
46627      * specifing Viewer's and the components' initial setup.
46628      * @param {string} token - Optional bearer token for API requests of
46629      * protected resources.
46630      *
46631      * @example
46632      * ```
46633      * var viewer = new Mapillary.Viewer("<element-id>", "<client-id>", "<image-key>");
46634      * ```
46635      */
46636     function Viewer(id, clientId, key, options, token) {
46637         var _this = _super.call(this) || this;
46638         options = options != null ? options : {};
46639         Utils_1.Settings.setOptions(options);
46640         Utils_1.Urls.setOptions(options.url);
46641         _this._navigator = new Viewer_1.Navigator(clientId, options, token);
46642         _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
46643         _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
46644         _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
46645         return _this;
46646     }
46647     Object.defineProperty(Viewer.prototype, "isNavigable", {
46648         /**
46649          * Return a boolean indicating if the viewer is in a navigable state.
46650          *
46651          * @description The navigable state indicates if the viewer supports
46652          * moving, i.e. calling the {@link moveToKey}, {@link moveDir`}
46653          * and {@link moveCloseTo} methods or changing the authentication state,
46654          * i.e. calling {@link setAuthToken}. The viewer will not be in a navigable
46655          * state if the cover is activated and the viewer has been supplied a key.
46656          * When the cover is deactivated or the viewer is activated without being
46657          * supplied a key it will be navigable.
46658          *
46659          * @returns {boolean} Boolean indicating whether the viewer is navigable.
46660          */
46661         get: function () {
46662             return this._componentController.navigable;
46663         },
46664         enumerable: true,
46665         configurable: true
46666     });
46667     /**
46668      * Activate a component.
46669      *
46670      * @param {string} name - Name of the component which will become active.
46671      *
46672      * @example
46673      * ```
46674      * viewer.activateComponent("marker");
46675      * ```
46676      */
46677     Viewer.prototype.activateComponent = function (name) {
46678         this._componentController.activate(name);
46679     };
46680     /**
46681      * Activate the cover (deactivates all other components).
46682      */
46683     Viewer.prototype.activateCover = function () {
46684         this._componentController.activateCover();
46685     };
46686     /**
46687      * Deactivate a component.
46688      *
46689      * @param {string} name - Name of component which become inactive.
46690      *
46691      * @example
46692      * ```
46693      * viewer.deactivateComponent("mouse");
46694      * ```
46695      */
46696     Viewer.prototype.deactivateComponent = function (name) {
46697         this._componentController.deactivate(name);
46698     };
46699     /**
46700      * Deactivate the cover (activates all components marked as active).
46701      */
46702     Viewer.prototype.deactivateCover = function () {
46703         this._componentController.deactivateCover();
46704     };
46705     /**
46706      * Get the bearing of the current viewer camera.
46707      *
46708      * @description The bearing depends on how the camera
46709      * is currently rotated and does not correspond
46710      * to the compass angle of the current node if the view
46711      * has been panned.
46712      *
46713      * Bearing is measured in degrees clockwise with respect to
46714      * north.
46715      *
46716      * @returns {Promise<number>} Promise to the bearing
46717      * of the current viewer camera.
46718      *
46719      * @example
46720      * ```
46721      * viewer.getBearing().then((b) => { console.log(b); });
46722      * ```
46723      */
46724     Viewer.prototype.getBearing = function () {
46725         var _this = this;
46726         return when.promise(function (resolve, reject) {
46727             _this._container.renderService.bearing$.pipe(operators_1.first())
46728                 .subscribe(function (bearing) {
46729                 resolve(bearing);
46730             }, function (error) {
46731                 reject(error);
46732             });
46733         });
46734     };
46735     /**
46736      * Get the basic coordinates of the current image that is
46737      * at the center of the viewport.
46738      *
46739      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
46740      * and have the origin point, (0, 0), at the top left corner and the
46741      * maximum value, (1, 1), at the bottom right corner of the original
46742      * image.
46743      *
46744      * @returns {Promise<number[]>} Promise to the basic coordinates
46745      * of the current image at the center for the viewport.
46746      *
46747      * @example
46748      * ```
46749      * viewer.getCenter().then((c) => { console.log(c); });
46750      * ```
46751      */
46752     Viewer.prototype.getCenter = function () {
46753         var _this = this;
46754         return when.promise(function (resolve, reject) {
46755             _this._navigator.stateService.getCenter()
46756                 .subscribe(function (center) {
46757                 resolve(center);
46758             }, function (error) {
46759                 reject(error);
46760             });
46761         });
46762     };
46763     /**
46764      * Get a component.
46765      *
46766      * @param {string} name - Name of component.
46767      * @returns {Component} The requested component.
46768      *
46769      * @example
46770      * ```
46771      * var mouseComponent = viewer.getComponent("mouse");
46772      * ```
46773      */
46774     Viewer.prototype.getComponent = function (name) {
46775         return this._componentController.get(name);
46776     };
46777     /**
46778      * Returns the viewer's containing HTML element.
46779      *
46780      * @returns {HTMLElement} The viewer's container.
46781      */
46782     Viewer.prototype.getContainer = function () {
46783         return this._container.element;
46784     };
46785     /**
46786      * Get the image's current zoom level.
46787      *
46788      * @returns {Promise<number>} Promise to the viewers's current
46789      * zoom level.
46790      *
46791      * @example
46792      * ```
46793      * viewer.getZoom().then((z) => { console.log(z); });
46794      * ```
46795      */
46796     Viewer.prototype.getZoom = function () {
46797         var _this = this;
46798         return when.promise(function (resolve, reject) {
46799             _this._navigator.stateService.getZoom()
46800                 .subscribe(function (zoom) {
46801                 resolve(zoom);
46802             }, function (error) {
46803                 reject(error);
46804             });
46805         });
46806     };
46807     /**
46808      * Move close to given latitude and longitude.
46809      *
46810      * @description Because the method propagates IO errors, these potential errors
46811      * need to be handled by the method caller (see example).
46812      *
46813      * @param {Number} lat - Latitude, in degrees.
46814      * @param {Number} lon - Longitude, in degrees.
46815      * @returns {Promise<Node>} Promise to the node that was navigated to.
46816      * @throws {Error} If no nodes exist close to provided latitude
46817      * longitude.
46818      * @throws {Error} Propagates any IO errors to the caller.
46819      * @throws {Error} When viewer is not navigable.
46820      * @throws {AbortMapillaryError} When a subsequent move request is made
46821      * before the move close to call has completed.
46822      *
46823      * @example
46824      * ```
46825      * viewer.moveCloseTo(0, 0).then(
46826      *     (n) => { console.log(n); },
46827      *     (e) => { console.error(e); });
46828      * ```
46829      */
46830     Viewer.prototype.moveCloseTo = function (lat, lon) {
46831         var moveCloseTo$ = this.isNavigable ?
46832             this._navigator.moveCloseTo$(lat, lon) :
46833             rxjs_1.throwError(new Error("Calling moveCloseTo is not supported when viewer is not navigable."));
46834         return when.promise(function (resolve, reject) {
46835             moveCloseTo$.subscribe(function (node) {
46836                 resolve(node);
46837             }, function (error) {
46838                 reject(error);
46839             });
46840         });
46841     };
46842     /**
46843      * Navigate in a given direction.
46844      *
46845      * @description This method has to be called through EdgeDirection enumeration as in the example.
46846      *
46847      * @param {EdgeDirection} dir - Direction in which which to move.
46848      * @returns {Promise<Node>} Promise to the node that was navigated to.
46849      * @throws {Error} If the current node does not have the edge direction
46850      * or the edges has not yet been cached.
46851      * @throws {Error} Propagates any IO errors to the caller.
46852      * @throws {Error} When viewer is not navigable.
46853      * @throws {AbortMapillaryError} When a subsequent move request is made
46854      * before the move dir call has completed.
46855      *
46856      * @example
46857      * ```
46858      * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
46859      *     (n) => { console.log(n); },
46860      *     (e) => { console.error(e); });
46861      * ```
46862      */
46863     Viewer.prototype.moveDir = function (dir) {
46864         var moveDir$ = this.isNavigable ?
46865             this._navigator.moveDir$(dir) :
46866             rxjs_1.throwError(new Error("Calling moveDir is not supported when viewer is not navigable."));
46867         return when.promise(function (resolve, reject) {
46868             moveDir$.subscribe(function (node) {
46869                 resolve(node);
46870             }, function (error) {
46871                 reject(error);
46872             });
46873         });
46874     };
46875     /**
46876      * Navigate to a given image key.
46877      *
46878      * @param {string} key - A valid Mapillary image key.
46879      * @returns {Promise<Node>} Promise to the node that was navigated to.
46880      * @throws {Error} Propagates any IO errors to the caller.
46881      * @throws {Error} When viewer is not navigable.
46882      * @throws {AbortMapillaryError} When a subsequent move request is made
46883      * before the move to key call has completed.
46884      *
46885      * @example
46886      * ```
46887      * viewer.moveToKey("<my key>").then(
46888      *     (n) => { console.log(n); },
46889      *     (e) => { console.error(e); });
46890      * ```
46891      */
46892     Viewer.prototype.moveToKey = function (key) {
46893         var moveToKey$ = this.isNavigable ?
46894             this._navigator.moveToKey$(key) :
46895             rxjs_1.throwError(new Error("Calling moveToKey is not supported when viewer is not navigable."));
46896         return when.promise(function (resolve, reject) {
46897             moveToKey$.subscribe(function (node) {
46898                 resolve(node);
46899             }, function (error) {
46900                 reject(error);
46901             });
46902         });
46903     };
46904     /**
46905      * Project basic image coordinates for the current node to canvas pixel
46906      * coordinates.
46907      *
46908      * @description The basic image coordinates may not always correspond to a
46909      * pixel point that lies in the visible area of the viewer container.
46910      *
46911      * @param {Array<number>} basicPoint - Basic images coordinates to project.
46912      * @returns {Promise<Array<number>>} Promise to the pixel coordinates corresponding
46913      * to the basic image point.
46914      *
46915      * @example
46916      * ```
46917      * viewer.projectFromBasic([0.3, 0.7])
46918      *     .then((pixelPoint) => { console.log(pixelPoint); });
46919      * ```
46920      */
46921     Viewer.prototype.projectFromBasic = function (basicPoint) {
46922         var _this = this;
46923         return when.promise(function (resolve, reject) {
46924             _this._observer.projectBasic$(basicPoint)
46925                 .subscribe(function (pixelPoint) {
46926                 resolve(pixelPoint);
46927             }, function (error) {
46928                 reject(error);
46929             });
46930         });
46931     };
46932     /**
46933      * Detect the viewer's new width and height and resize it.
46934      *
46935      * @description The components will also detect the viewer's
46936      * new size and resize their rendered elements if needed.
46937      *
46938      * @example
46939      * ```
46940      * viewer.resize();
46941      * ```
46942      */
46943     Viewer.prototype.resize = function () {
46944         this._container.renderService.resize$.next(null);
46945     };
46946     /**
46947      * Set a bearer token for authenticated API requests of
46948      * protected resources.
46949      *
46950      * @description When the supplied token is null or undefined,
46951      * any previously set bearer token will be cleared and the
46952      * viewer will make unauthenticated requests.
46953      *
46954      * Calling setAuthToken aborts all outstanding move requests.
46955      * The promises of those move requests will be rejected with a
46956      * {@link AbortMapillaryError} the rejections need to be caught.
46957      *
46958      * Calling setAuthToken also resets the complete viewer cache
46959      * so it should not be called repeatedly.
46960      *
46961      * @param {string} [token] token - Bearer token.
46962      * @returns {Promise<void>} Promise that resolves after token
46963      * is set.
46964      *
46965      * @throws {Error} When viewer is not navigable.
46966      *
46967      * @example
46968      * ```
46969      * viewer.setAuthToken("<my token>")
46970      *     .then(() => { console.log("token set"); });
46971      * ```
46972      */
46973     Viewer.prototype.setAuthToken = function (token) {
46974         var setToken$ = this.isNavigable ?
46975             this._navigator.setToken$(token) :
46976             rxjs_1.throwError(new Error("Calling setAuthToken is not supported when viewer is not navigable."));
46977         return when.promise(function (resolve, reject) {
46978             setToken$
46979                 .subscribe(function () {
46980                 resolve(undefined);
46981             }, function (error) {
46982                 reject(error);
46983             });
46984         });
46985     };
46986     /**
46987      * Set the basic coordinates of the current image to be in the
46988      * center of the viewport.
46989      *
46990      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
46991      * and has the origin point, (0, 0), at the top left corner and the
46992      * maximum value, (1, 1), at the bottom right corner of the original
46993      * image.
46994      *
46995      * @param {number[]} The basic coordinates of the current
46996      * image to be at the center for the viewport.
46997      *
46998      * @example
46999      * ```
47000      * viewer.setCenter([0.5, 0.5]);
47001      * ```
47002      */
47003     Viewer.prototype.setCenter = function (center) {
47004         this._navigator.stateService.setCenter(center);
47005     };
47006     /**
47007      * Set the filter selecting nodes to use when calculating
47008      * the spatial edges.
47009      *
47010      * @description The following filter types are supported:
47011      *
47012      * Comparison
47013      *
47014      * `["==", key, value]` equality: `node[key] = value`
47015      *
47016      * `["!=", key, value]` inequality: `node[key] â‰  value`
47017      *
47018      * `["<", key, value]` less than: `node[key] < value`
47019      *
47020      * `["<=", key, value]` less than or equal: `node[key] â‰¤ value`
47021      *
47022      * `[">", key, value]` greater than: `node[key] > value`
47023      *
47024      * `[">=", key, value]` greater than or equal: `node[key] â‰¥ value`
47025      *
47026      * Set membership
47027      *
47028      * `["in", key, v0, ..., vn]` set inclusion: `node[key] âˆˆ {v0, ..., vn}`
47029      *
47030      * `["!in", key, v0, ..., vn]` set exclusion: `node[key] âˆ‰ {v0, ..., vn}`
47031      *
47032      * Combining
47033      *
47034      * `["all", f0, ..., fn]` logical `AND`: `f0 âˆ§ ... âˆ§ fn`
47035      *
47036      * A key must be a string that identifies a property name of a
47037      * simple {@link Node} property. A value must be a string, number, or
47038      * boolean. Strictly-typed comparisons are used. The values
47039      * `f0, ..., fn` of the combining filter must be filter expressions.
47040      *
47041      * Clear the filter by setting it to null or empty array.
47042      *
47043      * @param {FilterExpression} filter - The filter expression.
47044      * @returns {Promise<void>} Promise that resolves after filter is applied.
47045      *
47046      * @example
47047      * ```
47048      * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
47049      * ```
47050      */
47051     Viewer.prototype.setFilter = function (filter) {
47052         var _this = this;
47053         return when.promise(function (resolve, reject) {
47054             _this._navigator.setFilter$(filter)
47055                 .subscribe(function () {
47056                 resolve(undefined);
47057             }, function (error) {
47058                 reject(error);
47059             });
47060         });
47061     };
47062     /**
47063      * Set the viewer's render mode.
47064      *
47065      * @param {RenderMode} renderMode - Render mode.
47066      *
47067      * @example
47068      * ```
47069      * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
47070      * ```
47071      */
47072     Viewer.prototype.setRenderMode = function (renderMode) {
47073         this._container.renderService.renderMode$.next(renderMode);
47074     };
47075     /**
47076      * Set the viewer's transition mode.
47077      *
47078      * @param {TransitionMode} transitionMode - Transition mode.
47079      *
47080      * @example
47081      * ```
47082      * viewer.setTransitionMode(Mapillary.TransitionMode.Instantaneous);
47083      * ```
47084      */
47085     Viewer.prototype.setTransitionMode = function (transitionMode) {
47086         this._navigator.stateService.setTransitionMode(transitionMode);
47087     };
47088     /**
47089      * Set the image's current zoom level.
47090      *
47091      * @description Possible zoom level values are on the [0, 3] interval.
47092      * Zero means zooming out to fit the image to the view whereas three
47093      * shows the highest level of detail.
47094      *
47095      * @param {number} The image's current zoom level.
47096      *
47097      * @example
47098      * ```
47099      * viewer.setZoom(2);
47100      * ```
47101      */
47102     Viewer.prototype.setZoom = function (zoom) {
47103         this._navigator.stateService.setZoom(zoom);
47104     };
47105     /**
47106      * Unproject canvas pixel coordinates to an ILatLon representing geographical
47107      * coordinates.
47108      *
47109      * @description The pixel point may not always correspond to geographical
47110      * coordinates. In the case of no correspondence the returned value will
47111      * be `null`.
47112      *
47113      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
47114      * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
47115      *
47116      * @example
47117      * ```
47118      * viewer.unproject([100, 100])
47119      *     .then((latLon) => { console.log(latLon); });
47120      * ```
47121      */
47122     Viewer.prototype.unproject = function (pixelPoint) {
47123         var _this = this;
47124         return when.promise(function (resolve, reject) {
47125             _this._observer.unproject$(pixelPoint)
47126                 .subscribe(function (latLon) {
47127                 resolve(latLon);
47128             }, function (error) {
47129                 reject(error);
47130             });
47131         });
47132     };
47133     /**
47134      * Unproject canvas pixel coordinates to basic image coordinates for the
47135      * current node.
47136      *
47137      * @description The pixel point may not always correspond to basic image
47138      * coordinates. In the case of no correspondence the returned value will
47139      * be `null`.
47140      *
47141      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
47142      * @returns {Promise<ILatLon>} Promise to the basic coordinates corresponding
47143      * to the pixel point.
47144      *
47145      * @example
47146      * ```
47147      * viewer.unprojectToBasic([100, 100])
47148      *     .then((basicPoint) => { console.log(basicPoint); });
47149      * ```
47150      */
47151     Viewer.prototype.unprojectToBasic = function (pixelPoint) {
47152         var _this = this;
47153         return when.promise(function (resolve, reject) {
47154             _this._observer.unprojectBasic$(pixelPoint)
47155                 .subscribe(function (basicPoint) {
47156                 resolve(basicPoint);
47157             }, function (error) {
47158                 reject(error);
47159             });
47160         });
47161     };
47162     /**
47163      * Fired when the viewing direction of the camera changes.
47164      *
47165      * @description Related to the computed compass angle
47166      * ({@link Node.computedCa}) from SfM, not the original EXIF compass
47167      * angle.
47168      *
47169      * @event
47170      * @type {number} bearing - Value indicating the current bearing
47171      * measured in degrees clockwise with respect to north.
47172      */
47173     Viewer.bearingchanged = "bearingchanged";
47174     /**
47175      * Fired when a pointing device (usually a mouse) is pressed and released at
47176      * the same point in the viewer.
47177      * @event
47178      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47179      */
47180     Viewer.click = "click";
47181     /**
47182      * Fired when the right button of the mouse is clicked within the viewer.
47183      * @event
47184      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47185      */
47186     Viewer.contextmenu = "contextmenu";
47187     /**
47188      * Fired when a pointing device (usually a mouse) is clicked twice at
47189      * the same point in the viewer.
47190      * @event
47191      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47192      */
47193     Viewer.dblclick = "dblclick";
47194     /**
47195      * Fired when the viewer is loading more data.
47196      * @event
47197      * @type {boolean} loading - Boolean indicating whether the viewer is loading.
47198      */
47199     Viewer.loadingchanged = "loadingchanged";
47200     /**
47201      * Fired when a pointing device (usually a mouse) is pressed within the viewer.
47202      * @event
47203      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47204      */
47205     Viewer.mousedown = "mousedown";
47206     /**
47207      * Fired when a pointing device (usually a mouse) is moved within the viewer.
47208      * @description Will not fire when the mouse is actively used, e.g. for drag pan.
47209      * @event
47210      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47211      */
47212     Viewer.mousemove = "mousemove";
47213     /**
47214      * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
47215      * @event
47216      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47217      */
47218     Viewer.mouseout = "mouseout";
47219     /**
47220      * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
47221      * @event
47222      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47223      */
47224     Viewer.mouseover = "mouseover";
47225     /**
47226      * Fired when a pointing device (usually a mouse) is released within the viewer.
47227      * @event
47228      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47229      */
47230     Viewer.mouseup = "mouseup";
47231     /**
47232      * Fired when the viewer motion stops and it is in a fixed
47233      * position with a fixed point of view.
47234      * @event
47235      */
47236     Viewer.moveend = "moveend";
47237     /**
47238      * Fired when the motion from one view to another start,
47239      * either by changing the position (e.g. when changing node) or
47240      * when changing point of view (e.g. by interaction such as pan and zoom).
47241      * @event
47242      */
47243     Viewer.movestart = "movestart";
47244     /**
47245      * Fired when the navigable state of the viewer changes.
47246      *
47247      * @description The navigable state indicates if the viewer supports
47248      * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
47249      * methods. The viewer will not be in a navigable state if the cover
47250      * is activated and the viewer has been supplied a key. When the cover
47251      * is deactivated or activated without being supplied a key it will
47252      * be navigable.
47253      *
47254      * @event
47255      * @type {boolean} navigable - Boolean indicating whether the viewer is navigable.
47256      */
47257     Viewer.navigablechanged = "navigablechanged";
47258     /**
47259      * Fired every time the viewer navigates to a new node.
47260      * @event
47261      * @type {Node} node - Current node.
47262      */
47263     Viewer.nodechanged = "nodechanged";
47264     /**
47265      * Fired every time the sequence edges of the current node changes.
47266      * @event
47267      * @type {IEdgeStatus} status - The edge status object.
47268      */
47269     Viewer.sequenceedgeschanged = "sequenceedgeschanged";
47270     /**
47271      * Fired every time the spatial edges of the current node changes.
47272      * @event
47273      * @type {IEdgeStatus} status - The edge status object.
47274      */
47275     Viewer.spatialedgeschanged = "spatialedgeschanged";
47276     return Viewer;
47277 }(Utils_1.EventEmitter));
47278 exports.Viewer = Viewer;
47279
47280 },{"../Utils":284,"../Viewer":285,"rxjs":26,"rxjs/operators":224,"when":271}]},{},[279])(279)
47281 });
47282 //# sourceMappingURL=mapillary.js.map