]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/iD/iD/mapillary-js/mapillary.js
Merge remote-tracking branch 'upstream/pull/2469'
[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":243}],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 /**
3887  * martinez v0.5.0
3888  * Martinez polygon clipping algorithm, does boolean operation on polygons (multipolygons, polygons with holes etc): intersection, union, difference, xor
3889  *
3890  * @author Alex Milevski <info@w8r.name>
3891  * @license MIT
3892  * @preserve
3893  */
3894
3895 (function (global, factory) {
3896   typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3897   typeof define === 'function' && define.amd ? define(['exports'], factory) :
3898   (factory((global.martinez = {})));
3899 }(this, (function (exports) { 'use strict';
3900
3901   function DEFAULT_COMPARE (a, b) { return a > b ? 1 : a < b ? -1 : 0; }
3902
3903   var SplayTree = function SplayTree(compare, noDuplicates) {
3904     if ( compare === void 0 ) compare = DEFAULT_COMPARE;
3905     if ( noDuplicates === void 0 ) noDuplicates = false;
3906
3907     this._compare = compare;
3908     this._root = null;
3909     this._size = 0;
3910     this._noDuplicates = !!noDuplicates;
3911   };
3912
3913   var prototypeAccessors = { size: { configurable: true } };
3914
3915
3916   SplayTree.prototype.rotateLeft = function rotateLeft (x) {
3917     var y = x.right;
3918     if (y) {
3919       x.right = y.left;
3920       if (y.left) { y.left.parent = x; }
3921       y.parent = x.parent;
3922     }
3923
3924     if (!x.parent)              { this._root = y; }
3925     else if (x === x.parent.left) { x.parent.left = y; }
3926     else                        { x.parent.right = y; }
3927     if (y) { y.left = x; }
3928     x.parent = y;
3929   };
3930
3931
3932   SplayTree.prototype.rotateRight = function rotateRight (x) {
3933     var y = x.left;
3934     if (y) {
3935       x.left = y.right;
3936       if (y.right) { y.right.parent = x; }
3937       y.parent = x.parent;
3938     }
3939
3940     if (!x.parent)             { this._root = y; }
3941     else if(x === x.parent.left) { x.parent.left = y; }
3942     else                       { x.parent.right = y; }
3943     if (y) { y.right = x; }
3944     x.parent = y;
3945   };
3946
3947
3948   SplayTree.prototype._splay = function _splay (x) {
3949       var this$1 = this;
3950
3951     while (x.parent) {
3952       var p = x.parent;
3953       if (!p.parent) {
3954         if (p.left === x) { this$1.rotateRight(p); }
3955         else            { this$1.rotateLeft(p); }
3956       } else if (p.left === x && p.parent.left === p) {
3957         this$1.rotateRight(p.parent);
3958         this$1.rotateRight(p);
3959       } else if (p.right === x && p.parent.right === p) {
3960         this$1.rotateLeft(p.parent);
3961         this$1.rotateLeft(p);
3962       } else if (p.left === x && p.parent.right === p) {
3963         this$1.rotateRight(p);
3964         this$1.rotateLeft(p);
3965       } else {
3966         this$1.rotateLeft(p);
3967         this$1.rotateRight(p);
3968       }
3969     }
3970   };
3971
3972
3973   SplayTree.prototype.splay = function splay (x) {
3974       var this$1 = this;
3975
3976     var p, gp, ggp, l, r;
3977
3978     while (x.parent) {
3979       p = x.parent;
3980       gp = p.parent;
3981
3982       if (gp && gp.parent) {
3983         ggp = gp.parent;
3984         if (ggp.left === gp) { ggp.left= x; }
3985         else               { ggp.right = x; }
3986         x.parent = ggp;
3987       } else {
3988         x.parent = null;
3989         this$1._root = x;
3990       }
3991
3992       l = x.left; r = x.right;
3993
3994       if (x === p.left) { // left
3995         if (gp) {
3996           if (gp.left === p) {
3997             /* zig-zig */
3998             if (p.right) {
3999               gp.left = p.right;
4000               gp.left.parent = gp;
4001             } else { gp.left = null; }
4002
4003             p.right = gp;
4004             gp.parent = p;
4005           } else {
4006             /* zig-zag */
4007             if (l) {
4008               gp.right = l;
4009               l.parent = gp;
4010             } else { gp.right = null; }
4011
4012             x.left  = gp;
4013             gp.parent = x;
4014           }
4015         }
4016         if (r) {
4017           p.left = r;
4018           r.parent = p;
4019         } else { p.left = null; }
4020
4021         x.right= p;
4022         p.parent = x;
4023       } else { // right
4024         if (gp) {
4025           if (gp.right === p) {
4026             /* zig-zig */
4027             if (p.left) {
4028               gp.right = p.left;
4029               gp.right.parent = gp;
4030             } else { gp.right = null; }
4031
4032             p.left = gp;
4033             gp.parent = p;
4034           } else {
4035             /* zig-zag */
4036             if (r) {
4037               gp.left = r;
4038               r.parent = gp;
4039             } else { gp.left = null; }
4040
4041             x.right = gp;
4042             gp.parent = x;
4043           }
4044         }
4045         if (l) {
4046           p.right = l;
4047           l.parent = p;
4048         } else { p.right = null; }
4049
4050         x.left = p;
4051         p.parent = x;
4052       }
4053     }
4054   };
4055
4056
4057   SplayTree.prototype.replace = function replace (u, v) {
4058     if (!u.parent) { this._root = v; }
4059     else if (u === u.parent.left) { u.parent.left = v; }
4060     else { u.parent.right = v; }
4061     if (v) { v.parent = u.parent; }
4062   };
4063
4064
4065   SplayTree.prototype.minNode = function minNode (u) {
4066       if ( u === void 0 ) u = this._root;
4067
4068     if (u) { while (u.left) { u = u.left; } }
4069     return u;
4070   };
4071
4072
4073   SplayTree.prototype.maxNode = function maxNode (u) {
4074       if ( u === void 0 ) u = this._root;
4075
4076     if (u) { while (u.right) { u = u.right; } }
4077     return u;
4078   };
4079
4080
4081   SplayTree.prototype.insert = function insert (key, data) {
4082     var z = this._root;
4083     var p = null;
4084     var comp = this._compare;
4085     var cmp;
4086
4087     if (this._noDuplicates) {
4088       while (z) {
4089         p = z;
4090         cmp = comp(z.key, key);
4091         if (cmp === 0) { return; }
4092         else if (comp(z.key, key) < 0) { z = z.right; }
4093         else { z = z.left; }
4094       }
4095     } else {
4096       while (z) {
4097         p = z;
4098         if (comp(z.key, key) < 0) { z = z.right; }
4099         else { z = z.left; }
4100       }
4101     }
4102
4103     z = { key: key, data: data, left: null, right: null, parent: p };
4104
4105     if (!p)                        { this._root = z; }
4106     else if (comp(p.key, z.key) < 0) { p.right = z; }
4107     else                           { p.left= z; }
4108
4109     this.splay(z);
4110     this._size++;
4111     return z;
4112   };
4113
4114
4115   SplayTree.prototype.find = function find (key) {
4116     var z  = this._root;
4117     var comp = this._compare;
4118     while (z) {
4119       var cmp = comp(z.key, key);
4120       if    (cmp < 0) { z = z.right; }
4121       else if (cmp > 0) { z = z.left; }
4122       else            { return z; }
4123     }
4124     return null;
4125   };
4126
4127   /**
4128    * Whether the tree contains a node with the given key
4129    * @param{Key} key
4130    * @return {boolean} true/false
4131    */
4132   SplayTree.prototype.contains = function contains (key) {
4133     var node     = this._root;
4134     var comparator = this._compare;
4135     while (node){
4136       var cmp = comparator(key, node.key);
4137       if    (cmp === 0) { return true; }
4138       else if (cmp < 0) { node = node.left; }
4139       else              { node = node.right; }
4140     }
4141
4142     return false;
4143   };
4144
4145
4146   SplayTree.prototype.remove = function remove (key) {
4147     var z = this.find(key);
4148
4149     if (!z) { return false; }
4150
4151     this.splay(z);
4152
4153     if (!z.left) { this.replace(z, z.right); }
4154     else if (!z.right) { this.replace(z, z.left); }
4155     else {
4156       var y = this.minNode(z.right);
4157       if (y.parent !== z) {
4158         this.replace(y, y.right);
4159         y.right = z.right;
4160         y.right.parent = y;
4161       }
4162       this.replace(z, y);
4163       y.left = z.left;
4164       y.left.parent = y;
4165     }
4166
4167     this._size--;
4168     return true;
4169   };
4170
4171
4172   SplayTree.prototype.removeNode = function removeNode (z) {
4173     if (!z) { return false; }
4174
4175     this.splay(z);
4176
4177     if (!z.left) { this.replace(z, z.right); }
4178     else if (!z.right) { this.replace(z, z.left); }
4179     else {
4180       var y = this.minNode(z.right);
4181       if (y.parent !== z) {
4182         this.replace(y, y.right);
4183         y.right = z.right;
4184         y.right.parent = y;
4185       }
4186       this.replace(z, y);
4187       y.left = z.left;
4188       y.left.parent = y;
4189     }
4190
4191     this._size--;
4192     return true;
4193   };
4194
4195
4196   SplayTree.prototype.erase = function erase (key) {
4197     var z = this.find(key);
4198     if (!z) { return; }
4199
4200     this.splay(z);
4201
4202     var s = z.left;
4203     var t = z.right;
4204
4205     var sMax = null;
4206     if (s) {
4207       s.parent = null;
4208       sMax = this.maxNode(s);
4209       this.splay(sMax);
4210       this._root = sMax;
4211     }
4212     if (t) {
4213       if (s) { sMax.right = t; }
4214       else { this._root = t; }
4215       t.parent = sMax;
4216     }
4217
4218     this._size--;
4219   };
4220
4221   /**
4222    * Removes and returns the node with smallest key
4223    * @return {?Node}
4224    */
4225   SplayTree.prototype.pop = function pop () {
4226     var node = this._root, returnValue = null;
4227     if (node) {
4228       while (node.left) { node = node.left; }
4229       returnValue = { key: node.key, data: node.data };
4230       this.remove(node.key);
4231     }
4232     return returnValue;
4233   };
4234
4235
4236   /* eslint-disable class-methods-use-this */
4237
4238   /**
4239    * Successor node
4240    * @param{Node} node
4241    * @return {?Node}
4242    */
4243   SplayTree.prototype.next = function next (node) {
4244     var successor = node;
4245     if (successor) {
4246       if (successor.right) {
4247         successor = successor.right;
4248         while (successor && successor.left) { successor = successor.left; }
4249       } else {
4250         successor = node.parent;
4251         while (successor && successor.right === node) {
4252           node = successor; successor = successor.parent;
4253         }
4254       }
4255     }
4256     return successor;
4257   };
4258
4259
4260   /**
4261    * Predecessor node
4262    * @param{Node} node
4263    * @return {?Node}
4264    */
4265   SplayTree.prototype.prev = function prev (node) {
4266     var predecessor = node;
4267     if (predecessor) {
4268       if (predecessor.left) {
4269         predecessor = predecessor.left;
4270         while (predecessor && predecessor.right) { predecessor = predecessor.right; }
4271       } else {
4272         predecessor = node.parent;
4273         while (predecessor && predecessor.left === node) {
4274           node = predecessor;
4275           predecessor = predecessor.parent;
4276         }
4277       }
4278     }
4279     return predecessor;
4280   };
4281   /* eslint-enable class-methods-use-this */
4282
4283
4284   /**
4285    * @param{forEachCallback} callback
4286    * @return {SplayTree}
4287    */
4288   SplayTree.prototype.forEach = function forEach (callback) {
4289     var current = this._root;
4290     var s = [], done = false, i = 0;
4291
4292     while (!done) {
4293       // Reach the left most Node of the current Node
4294       if (current) {
4295         // Place pointer to a tree node on the stack
4296         // before traversing the node's left subtree
4297         s.push(current);
4298         current = current.left;
4299       } else {
4300         // BackTrack from the empty subtree and visit the Node
4301         // at the top of the stack; however, if the stack is
4302         // empty you are done
4303         if (s.length > 0) {
4304           current = s.pop();
4305           callback(current, i++);
4306
4307           // We have visited the node and its left
4308           // subtree. Now, it's right subtree's turn
4309           current = current.right;
4310         } else { done = true; }
4311       }
4312     }
4313     return this;
4314   };
4315
4316
4317   /**
4318    * Walk key range from `low` to `high`. Stops if `fn` returns a value.
4319    * @param{Key}    low
4320    * @param{Key}    high
4321    * @param{Function} fn
4322    * @param{*?}     ctx
4323    * @return {SplayTree}
4324    */
4325   SplayTree.prototype.range = function range (low, high, fn, ctx) {
4326       var this$1 = this;
4327
4328     var Q = [];
4329     var compare = this._compare;
4330     var node = this._root, cmp;
4331
4332     while (Q.length !== 0 || node) {
4333       if (node) {
4334         Q.push(node);
4335         node = node.left;
4336       } else {
4337         node = Q.pop();
4338         cmp = compare(node.key, high);
4339         if (cmp > 0) {
4340           break;
4341         } else if (compare(node.key, low) >= 0) {
4342           if (fn.call(ctx, node)) { return this$1; } // stop if smth is returned
4343         }
4344         node = node.right;
4345       }
4346     }
4347     return this;
4348   };
4349
4350   /**
4351    * Returns all keys in order
4352    * @return {Array<Key>}
4353    */
4354   SplayTree.prototype.keys = function keys () {
4355     var current = this._root;
4356     var s = [], r = [], done = false;
4357
4358     while (!done) {
4359       if (current) {
4360         s.push(current);
4361         current = current.left;
4362       } else {
4363         if (s.length > 0) {
4364           current = s.pop();
4365           r.push(current.key);
4366           current = current.right;
4367         } else { done = true; }
4368       }
4369     }
4370     return r;
4371   };
4372
4373
4374   /**
4375    * Returns `data` fields of all nodes in order.
4376    * @return {Array<Value>}
4377    */
4378   SplayTree.prototype.values = function values () {
4379     var current = this._root;
4380     var s = [], r = [], done = false;
4381
4382     while (!done) {
4383       if (current) {
4384         s.push(current);
4385         current = current.left;
4386       } else {
4387         if (s.length > 0) {
4388           current = s.pop();
4389           r.push(current.data);
4390           current = current.right;
4391         } else { done = true; }
4392       }
4393     }
4394     return r;
4395   };
4396
4397
4398   /**
4399    * Returns node at given index
4400    * @param{number} index
4401    * @return {?Node}
4402    */
4403   SplayTree.prototype.at = function at (index) {
4404     // removed after a consideration, more misleading than useful
4405     // index = index % this.size;
4406     // if (index < 0) index = this.size - index;
4407
4408     var current = this._root;
4409     var s = [], done = false, i = 0;
4410
4411     while (!done) {
4412       if (current) {
4413         s.push(current);
4414         current = current.left;
4415       } else {
4416         if (s.length > 0) {
4417           current = s.pop();
4418           if (i === index) { return current; }
4419           i++;
4420           current = current.right;
4421         } else { done = true; }
4422       }
4423     }
4424     return null;
4425   };
4426
4427   /**
4428    * Bulk-load items. Both array have to be same size
4429    * @param{Array<Key>}  keys
4430    * @param{Array<Value>}[values]
4431    * @param{Boolean}     [presort=false] Pre-sort keys and values, using
4432    *                                       tree's comparator. Sorting is done
4433    *                                       in-place
4434    * @return {AVLTree}
4435    */
4436   SplayTree.prototype.load = function load (keys, values, presort) {
4437       if ( keys === void 0 ) keys = [];
4438       if ( values === void 0 ) values = [];
4439       if ( presort === void 0 ) presort = false;
4440
4441     if (this._size !== 0) { throw new Error('bulk-load: tree is not empty'); }
4442     var size = keys.length;
4443     if (presort) { sort(keys, values, 0, size - 1, this._compare); }
4444     this._root = loadRecursive(null, keys, values, 0, size);
4445     this._size = size;
4446     return this;
4447   };
4448
4449
4450   SplayTree.prototype.min = function min () {
4451     var node = this.minNode(this._root);
4452     if (node) { return node.key; }
4453     else    { return null; }
4454   };
4455
4456
4457   SplayTree.prototype.max = function max () {
4458     var node = this.maxNode(this._root);
4459     if (node) { return node.key; }
4460     else    { return null; }
4461   };
4462
4463   SplayTree.prototype.isEmpty = function isEmpty () { return this._root === null; };
4464   prototypeAccessors.size.get = function () { return this._size; };
4465
4466
4467   /**
4468    * Create a tree and load it with items
4469    * @param{Array<Key>}        keys
4470    * @param{Array<Value>?}      [values]
4471
4472    * @param{Function?}          [comparator]
4473    * @param{Boolean?}           [presort=false] Pre-sort keys and values, using
4474    *                                             tree's comparator. Sorting is done
4475    *                                             in-place
4476    * @param{Boolean?}           [noDuplicates=false] Allow duplicates
4477    * @return {SplayTree}
4478    */
4479   SplayTree.createTree = function createTree (keys, values, comparator, presort, noDuplicates) {
4480     return new SplayTree(comparator, noDuplicates).load(keys, values, presort);
4481   };
4482
4483   Object.defineProperties( SplayTree.prototype, prototypeAccessors );
4484
4485
4486   function loadRecursive (parent, keys, values, start, end) {
4487     var size = end - start;
4488     if (size > 0) {
4489       var middle = start + Math.floor(size / 2);
4490       var key    = keys[middle];
4491       var data   = values[middle];
4492       var node   = { key: key, data: data, parent: parent };
4493       node.left    = loadRecursive(node, keys, values, start, middle);
4494       node.right   = loadRecursive(node, keys, values, middle + 1, end);
4495       return node;
4496     }
4497     return null;
4498   }
4499
4500
4501   function sort(keys, values, left, right, compare) {
4502     if (left >= right) { return; }
4503
4504     var pivot = keys[(left + right) >> 1];
4505     var i = left - 1;
4506     var j = right + 1;
4507
4508     while (true) {
4509       do { i++; } while (compare(keys[i], pivot) < 0);
4510       do { j--; } while (compare(keys[j], pivot) > 0);
4511       if (i >= j) { break; }
4512
4513       var tmp = keys[i];
4514       keys[i] = keys[j];
4515       keys[j] = tmp;
4516
4517       tmp = values[i];
4518       values[i] = values[j];
4519       values[j] = tmp;
4520     }
4521
4522     sort(keys, values,  left,     j, compare);
4523     sort(keys, values, j + 1, right, compare);
4524   }
4525
4526   var NORMAL               = 0;
4527   var NON_CONTRIBUTING     = 1;
4528   var SAME_TRANSITION      = 2;
4529   var DIFFERENT_TRANSITION = 3;
4530
4531   var INTERSECTION = 0;
4532   var UNION        = 1;
4533   var DIFFERENCE   = 2;
4534   var XOR          = 3;
4535
4536   /**
4537    * @param  {SweepEvent} event
4538    * @param  {SweepEvent} prev
4539    * @param  {Operation} operation
4540    */
4541   function computeFields (event, prev, operation) {
4542     // compute inOut and otherInOut fields
4543     if (prev === null) {
4544       event.inOut      = false;
4545       event.otherInOut = true;
4546
4547     // previous line segment in sweepline belongs to the same polygon
4548     } else {
4549       if (event.isSubject === prev.isSubject) {
4550         event.inOut      = !prev.inOut;
4551         event.otherInOut = prev.otherInOut;
4552
4553       // previous line segment in sweepline belongs to the clipping polygon
4554       } else {
4555         event.inOut      = !prev.otherInOut;
4556         event.otherInOut = prev.isVertical() ? !prev.inOut : prev.inOut;
4557       }
4558
4559       // compute prevInResult field
4560       if (prev) {
4561         event.prevInResult = (!inResult(prev, operation) || prev.isVertical())
4562           ? prev.prevInResult : prev;
4563       }
4564     }
4565
4566     // check if the line segment belongs to the Boolean operation
4567     event.inResult = inResult(event, operation);
4568   }
4569
4570
4571   /* eslint-disable indent */
4572   function inResult(event, operation) {
4573     switch (event.type) {
4574       case NORMAL:
4575         switch (operation) {
4576           case INTERSECTION:
4577             return !event.otherInOut;
4578           case UNION:
4579             return event.otherInOut;
4580           case DIFFERENCE:
4581             // return (event.isSubject && !event.otherInOut) ||
4582             //         (!event.isSubject && event.otherInOut);
4583             return (event.isSubject && event.otherInOut) ||
4584                     (!event.isSubject && !event.otherInOut);
4585           case XOR:
4586             return true;
4587         }
4588         break;
4589       case SAME_TRANSITION:
4590         return operation === INTERSECTION || operation === UNION;
4591       case DIFFERENT_TRANSITION:
4592         return operation === DIFFERENCE;
4593       case NON_CONTRIBUTING:
4594         return false;
4595     }
4596     return false;
4597   }
4598   /* eslint-enable indent */
4599
4600   var SweepEvent = function SweepEvent (point, left, otherEvent, isSubject, edgeType) {
4601
4602     /**
4603      * Is left endpoint?
4604      * @type {Boolean}
4605      */
4606     this.left = left;
4607
4608     /**
4609      * @type {Array.<Number>}
4610      */
4611     this.point = point;
4612
4613     /**
4614      * Other edge reference
4615      * @type {SweepEvent}
4616      */
4617     this.otherEvent = otherEvent;
4618
4619     /**
4620      * Belongs to source or clipping polygon
4621      * @type {Boolean}
4622      */
4623     this.isSubject = isSubject;
4624
4625     /**
4626      * Edge contribution type
4627      * @type {Number}
4628      */
4629     this.type = edgeType || NORMAL;
4630
4631
4632     /**
4633      * In-out transition for the sweepline crossing polygon
4634      * @type {Boolean}
4635      */
4636     this.inOut = false;
4637
4638
4639     /**
4640      * @type {Boolean}
4641      */
4642     this.otherInOut = false;
4643
4644     /**
4645      * Previous event in result?
4646      * @type {SweepEvent}
4647      */
4648     this.prevInResult = null;
4649
4650     /**
4651      * Does event belong to result?
4652      * @type {Boolean}
4653      */
4654     this.inResult = false;
4655
4656
4657     // connection step
4658
4659     /**
4660      * @type {Boolean}
4661      */
4662     this.resultInOut = false;
4663
4664     this.isExteriorRing = true;
4665   };
4666
4667
4668   /**
4669    * @param{Array.<Number>}p
4670    * @return {Boolean}
4671    */
4672   SweepEvent.prototype.isBelow = function isBelow (p) {
4673     var p0 = this.point, p1 = this.otherEvent.point;
4674     return this.left
4675       ? (p0[0] - p[0]) * (p1[1] - p[1]) - (p1[0] - p[0]) * (p0[1] - p[1]) > 0
4676       // signedArea(this.point, this.otherEvent.point, p) > 0 :
4677       : (p1[0] - p[0]) * (p0[1] - p[1]) - (p0[0] - p[0]) * (p1[1] - p[1]) > 0;
4678       //signedArea(this.otherEvent.point, this.point, p) > 0;
4679   };
4680
4681
4682   /**
4683    * @param{Array.<Number>}p
4684    * @return {Boolean}
4685    */
4686   SweepEvent.prototype.isAbove = function isAbove (p) {
4687     return !this.isBelow(p);
4688   };
4689
4690
4691   /**
4692    * @return {Boolean}
4693    */
4694   SweepEvent.prototype.isVertical = function isVertical () {
4695     return this.point[0] === this.otherEvent.point[0];
4696   };
4697
4698
4699   SweepEvent.prototype.clone = function clone () {
4700     var copy = new SweepEvent(
4701       this.point, this.left, this.otherEvent, this.isSubject, this.type);
4702
4703     copy.inResult     = this.inResult;
4704     copy.prevInResult = this.prevInResult;
4705     copy.isExteriorRing = this.isExteriorRing;
4706     copy.inOut        = this.inOut;
4707     copy.otherInOut   = this.otherInOut;
4708
4709     return copy;
4710   };
4711
4712   function equals(p1, p2) {
4713     if (p1[0] === p2[0]) {
4714       if (p1[1] === p2[1]) {
4715         return true;
4716       } else {
4717         return false;
4718       }
4719     }
4720     return false;
4721   }
4722
4723   // const EPSILON = 1e-9;
4724   // const abs = Math.abs;
4725   // TODO https://github.com/w8r/martinez/issues/6#issuecomment-262847164
4726   // Precision problem.
4727   //
4728   // module.exports = function equals(p1, p2) {
4729   //   return abs(p1[0] - p2[0]) <= EPSILON && abs(p1[1] - p2[1]) <= EPSILON;
4730   // };
4731
4732   /**
4733    * Signed area of the triangle (p0, p1, p2)
4734    * @param  {Array.<Number>} p0
4735    * @param  {Array.<Number>} p1
4736    * @param  {Array.<Number>} p2
4737    * @return {Number}
4738    */
4739   function signedArea(p0, p1, p2) {
4740     return (p0[0] - p2[0]) * (p1[1] - p2[1]) - (p1[0] - p2[0]) * (p0[1] - p2[1]);
4741   }
4742
4743   /**
4744    * @param  {SweepEvent} e1
4745    * @param  {SweepEvent} e2
4746    * @return {Number}
4747    */
4748   function compareEvents(e1, e2) {
4749     var p1 = e1.point;
4750     var p2 = e2.point;
4751
4752     // Different x-coordinate
4753     if (p1[0] > p2[0]) { return 1; }
4754     if (p1[0] < p2[0]) { return -1; }
4755
4756     // Different points, but same x-coordinate
4757     // Event with lower y-coordinate is processed first
4758     if (p1[1] !== p2[1]) { return p1[1] > p2[1] ? 1 : -1; }
4759
4760     return specialCases(e1, e2, p1, p2);
4761   }
4762
4763
4764   /* eslint-disable no-unused-vars */
4765   function specialCases(e1, e2, p1, p2) {
4766     // Same coordinates, but one is a left endpoint and the other is
4767     // a right endpoint. The right endpoint is processed first
4768     if (e1.left !== e2.left)
4769       { return e1.left ? 1 : -1; }
4770
4771     // const p2 = e1.otherEvent.point, p3 = e2.otherEvent.point;
4772     // const sa = (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1])
4773     // Same coordinates, both events
4774     // are left endpoints or right endpoints.
4775     // not collinear
4776     if (signedArea(p1, e1.otherEvent.point, e2.otherEvent.point) !== 0) {
4777       // the event associate to the bottom segment is processed first
4778       return (!e1.isBelow(e2.otherEvent.point)) ? 1 : -1;
4779     }
4780
4781     return (!e1.isSubject && e2.isSubject) ? 1 : -1;
4782   }
4783   /* eslint-enable no-unused-vars */
4784
4785   /**
4786    * @param  {SweepEvent} se
4787    * @param  {Array.<Number>} p
4788    * @param  {Queue} queue
4789    * @return {Queue}
4790    */
4791   function divideSegment(se, p, queue)  {
4792     var r = new SweepEvent(p, false, se,            se.isSubject);
4793     var l = new SweepEvent(p, true,  se.otherEvent, se.isSubject);
4794
4795     /* eslint-disable no-console */
4796     if (equals(se.point, se.otherEvent.point)) {
4797
4798       console.warn('what is that, a collapsed segment?', se);
4799     }
4800     /* eslint-enable no-console */
4801
4802     r.contourId = l.contourId = se.contourId;
4803
4804     // avoid a rounding error. The left event would be processed after the right event
4805     if (compareEvents(l, se.otherEvent) > 0) {
4806       se.otherEvent.left = true;
4807       l.left = false;
4808     }
4809
4810     // avoid a rounding error. The left event would be processed after the right event
4811     // if (compareEvents(se, r) > 0) {}
4812
4813     se.otherEvent.otherEvent = l;
4814     se.otherEvent = r;
4815
4816     queue.push(l);
4817     queue.push(r);
4818
4819     return queue;
4820   }
4821
4822   //const EPS = 1e-9;
4823
4824   /**
4825    * Finds the magnitude of the cross product of two vectors (if we pretend
4826    * they're in three dimensions)
4827    *
4828    * @param {Object} a First vector
4829    * @param {Object} b Second vector
4830    * @private
4831    * @returns {Number} The magnitude of the cross product
4832    */
4833   function crossProduct(a, b) {
4834     return (a[0] * b[1]) - (a[1] * b[0]);
4835   }
4836
4837   /**
4838    * Finds the dot product of two vectors.
4839    *
4840    * @param {Object} a First vector
4841    * @param {Object} b Second vector
4842    * @private
4843    * @returns {Number} The dot product
4844    */
4845   function dotProduct(a, b) {
4846     return (a[0] * b[0]) + (a[1] * b[1]);
4847   }
4848
4849   /**
4850    * Finds the intersection (if any) between two line segments a and b, given the
4851    * line segments' end points a1, a2 and b1, b2.
4852    *
4853    * This algorithm is based on Schneider and Eberly.
4854    * http://www.cimec.org.ar/~ncalvo/Schneider_Eberly.pdf
4855    * Page 244.
4856    *
4857    * @param {Array.<Number>} a1 point of first line
4858    * @param {Array.<Number>} a2 point of first line
4859    * @param {Array.<Number>} b1 point of second line
4860    * @param {Array.<Number>} b2 point of second line
4861    * @param {Boolean=}       noEndpointTouch whether to skip single touchpoints
4862    *                                         (meaning connected segments) as
4863    *                                         intersections
4864    * @returns {Array.<Array.<Number>>|Null} If the lines intersect, the point of
4865    * intersection. If they overlap, the two end points of the overlapping segment.
4866    * Otherwise, null.
4867    */
4868   function intersection (a1, a2, b1, b2, noEndpointTouch) {
4869     // The algorithm expects our lines in the form P + sd, where P is a point,
4870     // s is on the interval [0, 1], and d is a vector.
4871     // We are passed two points. P can be the first point of each pair. The
4872     // vector, then, could be thought of as the distance (in x and y components)
4873     // from the first point to the second point.
4874     // So first, let's make our vectors:
4875     var va = [a2[0] - a1[0], a2[1] - a1[1]];
4876     var vb = [b2[0] - b1[0], b2[1] - b1[1]];
4877     // We also define a function to convert back to regular point form:
4878
4879     /* eslint-disable arrow-body-style */
4880
4881     function toPoint(p, s, d) {
4882       return [
4883         p[0] + s * d[0],
4884         p[1] + s * d[1]
4885       ];
4886     }
4887
4888     /* eslint-enable arrow-body-style */
4889
4890     // The rest is pretty much a straight port of the algorithm.
4891     var e = [b1[0] - a1[0], b1[1] - a1[1]];
4892     var kross    = crossProduct(va, vb);
4893     var sqrKross = kross * kross;
4894     var sqrLenA  = dotProduct(va, va);
4895     //const sqrLenB  = dotProduct(vb, vb);
4896
4897     // Check for line intersection. This works because of the properties of the
4898     // cross product -- specifically, two vectors are parallel if and only if the
4899     // cross product is the 0 vector. The full calculation involves relative error
4900     // to account for possible very small line segments. See Schneider & Eberly
4901     // for details.
4902     if (sqrKross > 0/* EPS * sqrLenB * sqLenA */) {
4903       // If they're not parallel, then (because these are line segments) they
4904       // still might not actually intersect. This code checks that the
4905       // intersection point of the lines is actually on both line segments.
4906       var s = crossProduct(e, vb) / kross;
4907       if (s < 0 || s > 1) {
4908         // not on line segment a
4909         return null;
4910       }
4911       var t = crossProduct(e, va) / kross;
4912       if (t < 0 || t > 1) {
4913         // not on line segment b
4914         return null;
4915       }
4916       if (s === 0 || s === 1) {
4917         // on an endpoint of line segment a
4918         return noEndpointTouch ? null : [toPoint(a1, s, va)];
4919       }
4920       if (t === 0 || t === 1) {
4921         // on an endpoint of line segment b
4922         return noEndpointTouch ? null : [toPoint(b1, t, vb)];
4923       }
4924       return [toPoint(a1, s, va)];
4925     }
4926
4927     // If we've reached this point, then the lines are either parallel or the
4928     // same, but the segments could overlap partially or fully, or not at all.
4929     // So we need to find the overlap, if any. To do that, we can use e, which is
4930     // the (vector) difference between the two initial points. If this is parallel
4931     // with the line itself, then the two lines are the same line, and there will
4932     // be overlap.
4933     //const sqrLenE = dotProduct(e, e);
4934     kross = crossProduct(e, va);
4935     sqrKross = kross * kross;
4936
4937     if (sqrKross > 0 /* EPS * sqLenB * sqLenE */) {
4938     // Lines are just parallel, not the same. No overlap.
4939       return null;
4940     }
4941
4942     var sa = dotProduct(va, e) / sqrLenA;
4943     var sb = sa + dotProduct(va, vb) / sqrLenA;
4944     var smin = Math.min(sa, sb);
4945     var smax = Math.max(sa, sb);
4946
4947     // this is, essentially, the FindIntersection acting on floats from
4948     // Schneider & Eberly, just inlined into this function.
4949     if (smin <= 1 && smax >= 0) {
4950
4951       // overlap on an end point
4952       if (smin === 1) {
4953         return noEndpointTouch ? null : [toPoint(a1, smin > 0 ? smin : 0, va)];
4954       }
4955
4956       if (smax === 0) {
4957         return noEndpointTouch ? null : [toPoint(a1, smax < 1 ? smax : 1, va)];
4958       }
4959
4960       if (noEndpointTouch && smin === 0 && smax === 1) { return null; }
4961
4962       // There's overlap on a segment -- two points of intersection. Return both.
4963       return [
4964         toPoint(a1, smin > 0 ? smin : 0, va),
4965         toPoint(a1, smax < 1 ? smax : 1, va)
4966       ];
4967     }
4968
4969     return null;
4970   }
4971
4972   /**
4973    * @param  {SweepEvent} se1
4974    * @param  {SweepEvent} se2
4975    * @param  {Queue}      queue
4976    * @return {Number}
4977    */
4978   function possibleIntersection (se1, se2, queue) {
4979     // that disallows self-intersecting polygons,
4980     // did cost us half a day, so I'll leave it
4981     // out of respect
4982     // if (se1.isSubject === se2.isSubject) return;
4983     var inter = intersection(
4984       se1.point, se1.otherEvent.point,
4985       se2.point, se2.otherEvent.point
4986     );
4987
4988     var nintersections = inter ? inter.length : 0;
4989     if (nintersections === 0) { return 0; } // no intersection
4990
4991     // the line segments intersect at an endpoint of both line segments
4992     if ((nintersections === 1) &&
4993         (equals(se1.point, se2.point) ||
4994          equals(se1.otherEvent.point, se2.otherEvent.point))) {
4995       return 0;
4996     }
4997
4998     if (nintersections === 2 && se1.isSubject === se2.isSubject) {
4999       // if(se1.contourId === se2.contourId){
5000       // console.warn('Edges of the same polygon overlap',
5001       //   se1.point, se1.otherEvent.point, se2.point, se2.otherEvent.point);
5002       // }
5003       //throw new Error('Edges of the same polygon overlap');
5004       return 0;
5005     }
5006
5007     // The line segments associated to se1 and se2 intersect
5008     if (nintersections === 1) {
5009
5010       // if the intersection point is not an endpoint of se1
5011       if (!equals(se1.point, inter[0]) && !equals(se1.otherEvent.point, inter[0])) {
5012         divideSegment(se1, inter[0], queue);
5013       }
5014
5015       // if the intersection point is not an endpoint of se2
5016       if (!equals(se2.point, inter[0]) && !equals(se2.otherEvent.point, inter[0])) {
5017         divideSegment(se2, inter[0], queue);
5018       }
5019       return 1;
5020     }
5021
5022     // The line segments associated to se1 and se2 overlap
5023     var events        = [];
5024     var leftCoincide  = false;
5025     var rightCoincide = false;
5026
5027     if (equals(se1.point, se2.point)) {
5028       leftCoincide = true; // linked
5029     } else if (compareEvents(se1, se2) === 1) {
5030       events.push(se2, se1);
5031     } else {
5032       events.push(se1, se2);
5033     }
5034
5035     if (equals(se1.otherEvent.point, se2.otherEvent.point)) {
5036       rightCoincide = true;
5037     } else if (compareEvents(se1.otherEvent, se2.otherEvent) === 1) {
5038       events.push(se2.otherEvent, se1.otherEvent);
5039     } else {
5040       events.push(se1.otherEvent, se2.otherEvent);
5041     }
5042
5043     if ((leftCoincide && rightCoincide) || leftCoincide) {
5044       // both line segments are equal or share the left endpoint
5045       se2.type = NON_CONTRIBUTING;
5046       se1.type = (se2.inOut === se1.inOut)
5047         ? SAME_TRANSITION : DIFFERENT_TRANSITION;
5048
5049       if (leftCoincide && !rightCoincide) {
5050         // honestly no idea, but changing events selection from [2, 1]
5051         // to [0, 1] fixes the overlapping self-intersecting polygons issue
5052         divideSegment(events[1].otherEvent, events[0].point, queue);
5053       }
5054       return 2;
5055     }
5056
5057     // the line segments share the right endpoint
5058     if (rightCoincide) {
5059       divideSegment(events[0], events[1].point, queue);
5060       return 3;
5061     }
5062
5063     // no line segment includes totally the other one
5064     if (events[0] !== events[3].otherEvent) {
5065       divideSegment(events[0], events[1].point, queue);
5066       divideSegment(events[1], events[2].point, queue);
5067       return 3;
5068     }
5069
5070     // one line segment includes the other one
5071     divideSegment(events[0], events[1].point, queue);
5072     divideSegment(events[3].otherEvent, events[2].point, queue);
5073
5074     return 3;
5075   }
5076
5077   /**
5078    * @param  {SweepEvent} le1
5079    * @param  {SweepEvent} le2
5080    * @return {Number}
5081    */
5082   function compareSegments(le1, le2) {
5083     if (le1 === le2) { return 0; }
5084
5085     // Segments are not collinear
5086     if (signedArea(le1.point, le1.otherEvent.point, le2.point) !== 0 ||
5087       signedArea(le1.point, le1.otherEvent.point, le2.otherEvent.point) !== 0) {
5088
5089       // If they share their left endpoint use the right endpoint to sort
5090       if (equals(le1.point, le2.point)) { return le1.isBelow(le2.otherEvent.point) ? -1 : 1; }
5091
5092       // Different left endpoint: use the left endpoint to sort
5093       if (le1.point[0] === le2.point[0]) { return le1.point[1] < le2.point[1] ? -1 : 1; }
5094
5095       // has the line segment associated to e1 been inserted
5096       // into S after the line segment associated to e2 ?
5097       if (compareEvents(le1, le2) === 1) { return le2.isAbove(le1.point) ? -1 : 1; }
5098
5099       // The line segment associated to e2 has been inserted
5100       // into S after the line segment associated to e1
5101       return le1.isBelow(le2.point) ? -1 : 1;
5102     }
5103
5104     if (le1.isSubject === le2.isSubject) { // same polygon
5105       var p1 = le1.point, p2 = le2.point;
5106       if (p1[0] === p2[0] && p1[1] === p2[1]/*equals(le1.point, le2.point)*/) {
5107         p1 = le1.otherEvent.point; p2 = le2.otherEvent.point;
5108         if (p1[0] === p2[0] && p1[1] === p2[1]) { return 0; }
5109         else { return le1.contourId > le2.contourId ? 1 : -1; }
5110       }
5111     } else { // Segments are collinear, but belong to separate polygons
5112       return le1.isSubject ? -1 : 1;
5113     }
5114
5115     return compareEvents(le1, le2) === 1 ? 1 : -1;
5116   }
5117
5118   function subdivide(eventQueue, subject, clipping, sbbox, cbbox, operation) {
5119     var sweepLine = new SplayTree(compareSegments);
5120     var sortedEvents = [];
5121
5122     var rightbound = Math.min(sbbox[2], cbbox[2]);
5123
5124     var prev, next, begin;
5125
5126     while (eventQueue.length !== 0) {
5127       var event = eventQueue.pop();
5128       sortedEvents.push(event);
5129
5130       // optimization by bboxes for intersection and difference goes here
5131       if ((operation === INTERSECTION && event.point[0] > rightbound) ||
5132           (operation === DIFFERENCE   && event.point[0] > sbbox[2])) {
5133         break;
5134       }
5135
5136       if (event.left) {
5137         next  = prev = sweepLine.insert(event);
5138         begin = sweepLine.minNode();
5139
5140         if (prev !== begin) { prev = sweepLine.prev(prev); }
5141         else                { prev = null; }
5142
5143         next = sweepLine.next(next);
5144
5145         var prevEvent = prev ? prev.key : null;
5146         var prevprevEvent = (void 0);
5147         computeFields(event, prevEvent, operation);
5148         if (next) {
5149           if (possibleIntersection(event, next.key, eventQueue) === 2) {
5150             computeFields(event, prevEvent, operation);
5151             computeFields(event, next.key, operation);
5152           }
5153         }
5154
5155         if (prev) {
5156           if (possibleIntersection(prev.key, event, eventQueue) === 2) {
5157             var prevprev = prev;
5158             if (prevprev !== begin) { prevprev = sweepLine.prev(prevprev); }
5159             else                    { prevprev = null; }
5160
5161             prevprevEvent = prevprev ? prevprev.key : null;
5162             computeFields(prevEvent, prevprevEvent, operation);
5163             computeFields(event,     prevEvent,     operation);
5164           }
5165         }
5166       } else {
5167         event = event.otherEvent;
5168         next = prev = sweepLine.find(event);
5169
5170         if (prev && next) {
5171
5172           if (prev !== begin) { prev = sweepLine.prev(prev); }
5173           else                { prev = null; }
5174
5175           next = sweepLine.next(next);
5176           sweepLine.remove(event);
5177
5178           if (next && prev) {
5179             possibleIntersection(prev.key, next.key, eventQueue);
5180           }
5181         }
5182       }
5183     }
5184     return sortedEvents;
5185   }
5186
5187   /**
5188    * @param  {Array.<SweepEvent>} sortedEvents
5189    * @return {Array.<SweepEvent>}
5190    */
5191   function orderEvents(sortedEvents) {
5192     var event, i, len, tmp;
5193     var resultEvents = [];
5194     for (i = 0, len = sortedEvents.length; i < len; i++) {
5195       event = sortedEvents[i];
5196       if ((event.left && event.inResult) ||
5197         (!event.left && event.otherEvent.inResult)) {
5198         resultEvents.push(event);
5199       }
5200     }
5201     // Due to overlapping edges the resultEvents array can be not wholly sorted
5202     var sorted = false;
5203     while (!sorted) {
5204       sorted = true;
5205       for (i = 0, len = resultEvents.length; i < len; i++) {
5206         if ((i + 1) < len &&
5207           compareEvents(resultEvents[i], resultEvents[i + 1]) === 1) {
5208           tmp = resultEvents[i];
5209           resultEvents[i] = resultEvents[i + 1];
5210           resultEvents[i + 1] = tmp;
5211           sorted = false;
5212         }
5213       }
5214     }
5215
5216
5217     for (i = 0, len = resultEvents.length; i < len; i++) {
5218       event = resultEvents[i];
5219       event.pos = i;
5220     }
5221
5222     // imagine, the right event is found in the beginning of the queue,
5223     // when his left counterpart is not marked yet
5224     for (i = 0, len = resultEvents.length; i < len; i++) {
5225       event = resultEvents[i];
5226       if (!event.left) {
5227         tmp = event.pos;
5228         event.pos = event.otherEvent.pos;
5229         event.otherEvent.pos = tmp;
5230       }
5231     }
5232
5233     return resultEvents;
5234   }
5235
5236
5237   /**
5238    * @param  {Number} pos
5239    * @param  {Array.<SweepEvent>} resultEvents
5240    * @param  {Object>}    processed
5241    * @return {Number}
5242    */
5243   function nextPos(pos, resultEvents, processed, origIndex) {
5244     var p, p1;
5245     var newPos = pos + 1;
5246     var length = resultEvents.length;
5247
5248     p  = resultEvents[pos].point;
5249
5250     if (newPos < length)
5251       { p1 = resultEvents[newPos].point; }
5252
5253
5254     // while in range and not the current one by value
5255     while (newPos < length && p1[0] === p[0] && p1[1] === p[1]) {
5256       if (!processed[newPos]) {
5257         return newPos;
5258       } else   {
5259         newPos++;
5260       }
5261       p1 = resultEvents[newPos].point;
5262     }
5263
5264     newPos = pos - 1;
5265
5266     while (processed[newPos] && newPos >= origIndex) {
5267       newPos--;
5268     }
5269     return newPos;
5270   }
5271
5272
5273   /**
5274    * @param  {Array.<SweepEvent>} sortedEvents
5275    * @return {Array.<*>} polygons
5276    */
5277   function connectEdges(sortedEvents, operation) {
5278     var i, len;
5279     var resultEvents = orderEvents(sortedEvents);
5280
5281     // "false"-filled array
5282     var processed = {};
5283     var result = [];
5284     var event;
5285
5286     for (i = 0, len = resultEvents.length; i < len; i++) {
5287       if (processed[i]) { continue; }
5288       var contour = [[]];
5289
5290       if (!resultEvents[i].isExteriorRing) {
5291         if (operation === DIFFERENCE && !resultEvents[i].isSubject && result.length === 0) {
5292           result.push(contour);
5293         } else if (result.length === 0) {
5294           result.push([[contour]]);
5295         } else {
5296           result[result.length - 1].push(contour[0]);
5297         }
5298       } else if (operation === DIFFERENCE && !resultEvents[i].isSubject && result.length > 1) {
5299         result[result.length - 1].push(contour[0]);
5300       } else {
5301         result.push(contour);
5302       }
5303
5304       var ringId = result.length - 1;
5305       var pos = i;
5306
5307       var initial = resultEvents[i].point;
5308       contour[0].push(initial);
5309
5310       while (pos >= i) {
5311         event = resultEvents[pos];
5312         processed[pos] = true;
5313
5314         if (event.left) {
5315           event.resultInOut = false;
5316           event.contourId   = ringId;
5317         } else {
5318           event.otherEvent.resultInOut = true;
5319           event.otherEvent.contourId   = ringId;
5320         }
5321
5322         pos = event.pos;
5323         processed[pos] = true;
5324         contour[0].push(resultEvents[pos].point);
5325         pos = nextPos(pos, resultEvents, processed, i);
5326       }
5327
5328       pos = pos === -1 ? i : pos;
5329
5330       event = resultEvents[pos];
5331       processed[pos] = processed[event.pos] = true;
5332       event.otherEvent.resultInOut = true;
5333       event.otherEvent.contourId   = ringId;
5334     }
5335
5336     // Handle if the result is a polygon (eg not multipoly)
5337     // Commented it again, let's see what do we mean by that
5338     // if (result.length === 1) result = result[0];
5339     return result;
5340   }
5341
5342   var tinyqueue = TinyQueue;
5343   var default_1 = TinyQueue;
5344
5345   function TinyQueue(data, compare) {
5346       var this$1 = this;
5347
5348       if (!(this instanceof TinyQueue)) { return new TinyQueue(data, compare); }
5349
5350       this.data = data || [];
5351       this.length = this.data.length;
5352       this.compare = compare || defaultCompare;
5353
5354       if (this.length > 0) {
5355           for (var i = (this.length >> 1) - 1; i >= 0; i--) { this$1._down(i); }
5356       }
5357   }
5358
5359   function defaultCompare(a, b) {
5360       return a < b ? -1 : a > b ? 1 : 0;
5361   }
5362
5363   TinyQueue.prototype = {
5364
5365       push: function (item) {
5366           this.data.push(item);
5367           this.length++;
5368           this._up(this.length - 1);
5369       },
5370
5371       pop: function () {
5372           if (this.length === 0) { return undefined; }
5373
5374           var top = this.data[0];
5375           this.length--;
5376
5377           if (this.length > 0) {
5378               this.data[0] = this.data[this.length];
5379               this._down(0);
5380           }
5381           this.data.pop();
5382
5383           return top;
5384       },
5385
5386       peek: function () {
5387           return this.data[0];
5388       },
5389
5390       _up: function (pos) {
5391           var data = this.data;
5392           var compare = this.compare;
5393           var item = data[pos];
5394
5395           while (pos > 0) {
5396               var parent = (pos - 1) >> 1;
5397               var current = data[parent];
5398               if (compare(item, current) >= 0) { break; }
5399               data[pos] = current;
5400               pos = parent;
5401           }
5402
5403           data[pos] = item;
5404       },
5405
5406       _down: function (pos) {
5407           var this$1 = this;
5408
5409           var data = this.data;
5410           var compare = this.compare;
5411           var halfLength = this.length >> 1;
5412           var item = data[pos];
5413
5414           while (pos < halfLength) {
5415               var left = (pos << 1) + 1;
5416               var right = left + 1;
5417               var best = data[left];
5418
5419               if (right < this$1.length && compare(data[right], best) < 0) {
5420                   left = right;
5421                   best = data[right];
5422               }
5423               if (compare(best, item) >= 0) { break; }
5424
5425               data[pos] = best;
5426               pos = left;
5427           }
5428
5429           data[pos] = item;
5430       }
5431   };
5432   tinyqueue.default = default_1;
5433
5434   var max = Math.max;
5435   var min = Math.min;
5436
5437   var contourId = 0;
5438
5439
5440   function processPolygon(contourOrHole, isSubject, depth, Q, bbox, isExteriorRing) {
5441     var i, len, s1, s2, e1, e2;
5442     for (i = 0, len = contourOrHole.length - 1; i < len; i++) {
5443       s1 = contourOrHole[i];
5444       s2 = contourOrHole[i + 1];
5445       e1 = new SweepEvent(s1, false, undefined, isSubject);
5446       e2 = new SweepEvent(s2, false, e1,        isSubject);
5447       e1.otherEvent = e2;
5448
5449       if (s1[0] === s2[0] && s1[1] === s2[1]) {
5450         continue; // skip collapsed edges, or it breaks
5451       }
5452
5453       e1.contourId = e2.contourId = depth;
5454       if (!isExteriorRing) {
5455         e1.isExteriorRing = false;
5456         e2.isExteriorRing = false;
5457       }
5458       if (compareEvents(e1, e2) > 0) {
5459         e2.left = true;
5460       } else {
5461         e1.left = true;
5462       }
5463
5464       var x = s1[0], y = s1[1];
5465       bbox[0] = min(bbox[0], x);
5466       bbox[1] = min(bbox[1], y);
5467       bbox[2] = max(bbox[2], x);
5468       bbox[3] = max(bbox[3], y);
5469
5470       // Pushing it so the queue is sorted from left to right,
5471       // with object on the left having the highest priority.
5472       Q.push(e1);
5473       Q.push(e2);
5474     }
5475   }
5476
5477
5478   function fillQueue(subject, clipping, sbbox, cbbox, operation) {
5479     var eventQueue = new tinyqueue(null, compareEvents);
5480     var polygonSet, isExteriorRing, i, ii, j, jj; //, k, kk;
5481
5482     for (i = 0, ii = subject.length; i < ii; i++) {
5483       polygonSet = subject[i];
5484       for (j = 0, jj = polygonSet.length; j < jj; j++) {
5485         isExteriorRing = j === 0;
5486         if (isExteriorRing) { contourId++; }
5487         processPolygon(polygonSet[j], true, contourId, eventQueue, sbbox, isExteriorRing);
5488       }
5489     }
5490
5491     for (i = 0, ii = clipping.length; i < ii; i++) {
5492       polygonSet = clipping[i];
5493       for (j = 0, jj = polygonSet.length; j < jj; j++) {
5494         isExteriorRing = j === 0;
5495         if (operation === DIFFERENCE) { isExteriorRing = false; }
5496         if (isExteriorRing) { contourId++; }
5497         processPolygon(polygonSet[j], false, contourId, eventQueue, cbbox, isExteriorRing);
5498       }
5499     }
5500
5501     return eventQueue;
5502   }
5503
5504   var EMPTY = [];
5505
5506
5507   function trivialOperation(subject, clipping, operation) {
5508     var result = null;
5509     if (subject.length * clipping.length === 0) {
5510       if        (operation === INTERSECTION) {
5511         result = EMPTY;
5512       } else if (operation === DIFFERENCE) {
5513         result = subject;
5514       } else if (operation === UNION ||
5515                  operation === XOR) {
5516         result = (subject.length === 0) ? clipping : subject;
5517       }
5518     }
5519     return result;
5520   }
5521
5522
5523   function compareBBoxes(subject, clipping, sbbox, cbbox, operation) {
5524     var result = null;
5525     if (sbbox[0] > cbbox[2] ||
5526         cbbox[0] > sbbox[2] ||
5527         sbbox[1] > cbbox[3] ||
5528         cbbox[1] > sbbox[3]) {
5529       if        (operation === INTERSECTION) {
5530         result = EMPTY;
5531       } else if (operation === DIFFERENCE) {
5532         result = subject;
5533       } else if (operation === UNION ||
5534                  operation === XOR) {
5535         result = subject.concat(clipping);
5536       }
5537     }
5538     return result;
5539   }
5540
5541
5542   function boolean(subject, clipping, operation) {
5543     if (typeof subject[0][0][0] === 'number') {
5544       subject = [subject];
5545     }
5546     if (typeof clipping[0][0][0] === 'number') {
5547       clipping = [clipping];
5548     }
5549     var trivial = trivialOperation(subject, clipping, operation);
5550     if (trivial) {
5551       return trivial === EMPTY ? null : trivial;
5552     }
5553     var sbbox = [Infinity, Infinity, -Infinity, -Infinity];
5554     var cbbox = [Infinity, Infinity, -Infinity, -Infinity];
5555
5556     //console.time('fill queue');
5557     var eventQueue = fillQueue(subject, clipping, sbbox, cbbox, operation);
5558     //console.timeEnd('fill queue');
5559
5560     trivial = compareBBoxes(subject, clipping, sbbox, cbbox, operation);
5561     if (trivial) {
5562       return trivial === EMPTY ? null : trivial;
5563     }
5564     //console.time('subdivide edges');
5565     var sortedEvents = subdivide(eventQueue, subject, clipping, sbbox, cbbox, operation);
5566     //console.timeEnd('subdivide edges');
5567
5568     //console.time('connect vertices');
5569     var result = connectEdges(sortedEvents, operation);
5570     //console.timeEnd('connect vertices');
5571     return result;
5572   }
5573
5574   function union (subject, clipping) {
5575     return boolean(subject, clipping, UNION);
5576   }
5577
5578   function diff (subject, clipping) {
5579     return boolean(subject, clipping, DIFFERENCE);
5580   }
5581
5582   function xor (subject, clipping){
5583     return boolean(subject, clipping, XOR);
5584   }
5585
5586   function intersection$1 (subject, clipping) {
5587     return boolean(subject, clipping, INTERSECTION);
5588   }
5589
5590   /**
5591    * @enum {Number}
5592    */
5593   var operations = { UNION: UNION, DIFFERENCE: DIFFERENCE, INTERSECTION: INTERSECTION, XOR: XOR };
5594
5595   exports.union = union;
5596   exports.diff = diff;
5597   exports.xor = xor;
5598   exports.intersection = intersection$1;
5599   exports.operations = operations;
5600
5601   Object.defineProperty(exports, '__esModule', { value: true });
5602
5603 })));
5604
5605
5606 },{}],23:[function(require,module,exports){
5607 // Top level file is just a mixin of submodules & constants
5608 'use strict';
5609
5610 var assign    = require('./lib/utils/common').assign;
5611
5612 var deflate   = require('./lib/deflate');
5613 var inflate   = require('./lib/inflate');
5614 var constants = require('./lib/zlib/constants');
5615
5616 var pako = {};
5617
5618 assign(pako, deflate, inflate, constants);
5619
5620 module.exports = pako;
5621
5622 },{"./lib/deflate":24,"./lib/inflate":25,"./lib/utils/common":26,"./lib/zlib/constants":29}],24:[function(require,module,exports){
5623 'use strict';
5624
5625
5626 var zlib_deflate = require('./zlib/deflate');
5627 var utils        = require('./utils/common');
5628 var strings      = require('./utils/strings');
5629 var msg          = require('./zlib/messages');
5630 var ZStream      = require('./zlib/zstream');
5631
5632 var toString = Object.prototype.toString;
5633
5634 /* Public constants ==========================================================*/
5635 /* ===========================================================================*/
5636
5637 var Z_NO_FLUSH      = 0;
5638 var Z_FINISH        = 4;
5639
5640 var Z_OK            = 0;
5641 var Z_STREAM_END    = 1;
5642 var Z_SYNC_FLUSH    = 2;
5643
5644 var Z_DEFAULT_COMPRESSION = -1;
5645
5646 var Z_DEFAULT_STRATEGY    = 0;
5647
5648 var Z_DEFLATED  = 8;
5649
5650 /* ===========================================================================*/
5651
5652
5653 /**
5654  * class Deflate
5655  *
5656  * Generic JS-style wrapper for zlib calls. If you don't need
5657  * streaming behaviour - use more simple functions: [[deflate]],
5658  * [[deflateRaw]] and [[gzip]].
5659  **/
5660
5661 /* internal
5662  * Deflate.chunks -> Array
5663  *
5664  * Chunks of output data, if [[Deflate#onData]] not overridden.
5665  **/
5666
5667 /**
5668  * Deflate.result -> Uint8Array|Array
5669  *
5670  * Compressed result, generated by default [[Deflate#onData]]
5671  * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
5672  * (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
5673  * push a chunk with explicit flush (call [[Deflate#push]] with
5674  * `Z_SYNC_FLUSH` param).
5675  **/
5676
5677 /**
5678  * Deflate.err -> Number
5679  *
5680  * Error code after deflate finished. 0 (Z_OK) on success.
5681  * You will not need it in real life, because deflate errors
5682  * are possible only on wrong options or bad `onData` / `onEnd`
5683  * custom handlers.
5684  **/
5685
5686 /**
5687  * Deflate.msg -> String
5688  *
5689  * Error message, if [[Deflate.err]] != 0
5690  **/
5691
5692
5693 /**
5694  * new Deflate(options)
5695  * - options (Object): zlib deflate options.
5696  *
5697  * Creates new deflator instance with specified params. Throws exception
5698  * on bad params. Supported options:
5699  *
5700  * - `level`
5701  * - `windowBits`
5702  * - `memLevel`
5703  * - `strategy`
5704  * - `dictionary`
5705  *
5706  * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
5707  * for more information on these.
5708  *
5709  * Additional options, for internal needs:
5710  *
5711  * - `chunkSize` - size of generated data chunks (16K by default)
5712  * - `raw` (Boolean) - do raw deflate
5713  * - `gzip` (Boolean) - create gzip wrapper
5714  * - `to` (String) - if equal to 'string', then result will be "binary string"
5715  *    (each char code [0..255])
5716  * - `header` (Object) - custom header for gzip
5717  *   - `text` (Boolean) - true if compressed data believed to be text
5718  *   - `time` (Number) - modification time, unix timestamp
5719  *   - `os` (Number) - operation system code
5720  *   - `extra` (Array) - array of bytes with extra data (max 65536)
5721  *   - `name` (String) - file name (binary string)
5722  *   - `comment` (String) - comment (binary string)
5723  *   - `hcrc` (Boolean) - true if header crc should be added
5724  *
5725  * ##### Example:
5726  *
5727  * ```javascript
5728  * var pako = require('pako')
5729  *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
5730  *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
5731  *
5732  * var deflate = new pako.Deflate({ level: 3});
5733  *
5734  * deflate.push(chunk1, false);
5735  * deflate.push(chunk2, true);  // true -> last chunk
5736  *
5737  * if (deflate.err) { throw new Error(deflate.err); }
5738  *
5739  * console.log(deflate.result);
5740  * ```
5741  **/
5742 function Deflate(options) {
5743   if (!(this instanceof Deflate)) return new Deflate(options);
5744
5745   this.options = utils.assign({
5746     level: Z_DEFAULT_COMPRESSION,
5747     method: Z_DEFLATED,
5748     chunkSize: 16384,
5749     windowBits: 15,
5750     memLevel: 8,
5751     strategy: Z_DEFAULT_STRATEGY,
5752     to: ''
5753   }, options || {});
5754
5755   var opt = this.options;
5756
5757   if (opt.raw && (opt.windowBits > 0)) {
5758     opt.windowBits = -opt.windowBits;
5759   }
5760
5761   else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
5762     opt.windowBits += 16;
5763   }
5764
5765   this.err    = 0;      // error code, if happens (0 = Z_OK)
5766   this.msg    = '';     // error message
5767   this.ended  = false;  // used to avoid multiple onEnd() calls
5768   this.chunks = [];     // chunks of compressed data
5769
5770   this.strm = new ZStream();
5771   this.strm.avail_out = 0;
5772
5773   var status = zlib_deflate.deflateInit2(
5774     this.strm,
5775     opt.level,
5776     opt.method,
5777     opt.windowBits,
5778     opt.memLevel,
5779     opt.strategy
5780   );
5781
5782   if (status !== Z_OK) {
5783     throw new Error(msg[status]);
5784   }
5785
5786   if (opt.header) {
5787     zlib_deflate.deflateSetHeader(this.strm, opt.header);
5788   }
5789
5790   if (opt.dictionary) {
5791     var dict;
5792     // Convert data if needed
5793     if (typeof opt.dictionary === 'string') {
5794       // If we need to compress text, change encoding to utf8.
5795       dict = strings.string2buf(opt.dictionary);
5796     } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
5797       dict = new Uint8Array(opt.dictionary);
5798     } else {
5799       dict = opt.dictionary;
5800     }
5801
5802     status = zlib_deflate.deflateSetDictionary(this.strm, dict);
5803
5804     if (status !== Z_OK) {
5805       throw new Error(msg[status]);
5806     }
5807
5808     this._dict_set = true;
5809   }
5810 }
5811
5812 /**
5813  * Deflate#push(data[, mode]) -> Boolean
5814  * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
5815  *   converted to utf8 byte sequence.
5816  * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
5817  *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
5818  *
5819  * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
5820  * new compressed chunks. Returns `true` on success. The last data block must have
5821  * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
5822  * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
5823  * can use mode Z_SYNC_FLUSH, keeping the compression context.
5824  *
5825  * On fail call [[Deflate#onEnd]] with error code and return false.
5826  *
5827  * We strongly recommend to use `Uint8Array` on input for best speed (output
5828  * array format is detected automatically). Also, don't skip last param and always
5829  * use the same type in your code (boolean or number). That will improve JS speed.
5830  *
5831  * For regular `Array`-s make sure all elements are [0..255].
5832  *
5833  * ##### Example
5834  *
5835  * ```javascript
5836  * push(chunk, false); // push one of data chunks
5837  * ...
5838  * push(chunk, true);  // push last chunk
5839  * ```
5840  **/
5841 Deflate.prototype.push = function (data, mode) {
5842   var strm = this.strm;
5843   var chunkSize = this.options.chunkSize;
5844   var status, _mode;
5845
5846   if (this.ended) { return false; }
5847
5848   _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
5849
5850   // Convert data if needed
5851   if (typeof data === 'string') {
5852     // If we need to compress text, change encoding to utf8.
5853     strm.input = strings.string2buf(data);
5854   } else if (toString.call(data) === '[object ArrayBuffer]') {
5855     strm.input = new Uint8Array(data);
5856   } else {
5857     strm.input = data;
5858   }
5859
5860   strm.next_in = 0;
5861   strm.avail_in = strm.input.length;
5862
5863   do {
5864     if (strm.avail_out === 0) {
5865       strm.output = new utils.Buf8(chunkSize);
5866       strm.next_out = 0;
5867       strm.avail_out = chunkSize;
5868     }
5869     status = zlib_deflate.deflate(strm, _mode);    /* no bad return value */
5870
5871     if (status !== Z_STREAM_END && status !== Z_OK) {
5872       this.onEnd(status);
5873       this.ended = true;
5874       return false;
5875     }
5876     if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
5877       if (this.options.to === 'string') {
5878         this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
5879       } else {
5880         this.onData(utils.shrinkBuf(strm.output, strm.next_out));
5881       }
5882     }
5883   } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
5884
5885   // Finalize on the last chunk.
5886   if (_mode === Z_FINISH) {
5887     status = zlib_deflate.deflateEnd(this.strm);
5888     this.onEnd(status);
5889     this.ended = true;
5890     return status === Z_OK;
5891   }
5892
5893   // callback interim results if Z_SYNC_FLUSH.
5894   if (_mode === Z_SYNC_FLUSH) {
5895     this.onEnd(Z_OK);
5896     strm.avail_out = 0;
5897     return true;
5898   }
5899
5900   return true;
5901 };
5902
5903
5904 /**
5905  * Deflate#onData(chunk) -> Void
5906  * - chunk (Uint8Array|Array|String): output data. Type of array depends
5907  *   on js engine support. When string output requested, each chunk
5908  *   will be string.
5909  *
5910  * By default, stores data blocks in `chunks[]` property and glue
5911  * those in `onEnd`. Override this handler, if you need another behaviour.
5912  **/
5913 Deflate.prototype.onData = function (chunk) {
5914   this.chunks.push(chunk);
5915 };
5916
5917
5918 /**
5919  * Deflate#onEnd(status) -> Void
5920  * - status (Number): deflate status. 0 (Z_OK) on success,
5921  *   other if not.
5922  *
5923  * Called once after you tell deflate that the input stream is
5924  * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
5925  * or if an error happened. By default - join collected chunks,
5926  * free memory and fill `results` / `err` properties.
5927  **/
5928 Deflate.prototype.onEnd = function (status) {
5929   // On success - join
5930   if (status === Z_OK) {
5931     if (this.options.to === 'string') {
5932       this.result = this.chunks.join('');
5933     } else {
5934       this.result = utils.flattenChunks(this.chunks);
5935     }
5936   }
5937   this.chunks = [];
5938   this.err = status;
5939   this.msg = this.strm.msg;
5940 };
5941
5942
5943 /**
5944  * deflate(data[, options]) -> Uint8Array|Array|String
5945  * - data (Uint8Array|Array|String): input data to compress.
5946  * - options (Object): zlib deflate options.
5947  *
5948  * Compress `data` with deflate algorithm and `options`.
5949  *
5950  * Supported options are:
5951  *
5952  * - level
5953  * - windowBits
5954  * - memLevel
5955  * - strategy
5956  * - dictionary
5957  *
5958  * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
5959  * for more information on these.
5960  *
5961  * Sugar (options):
5962  *
5963  * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
5964  *   negative windowBits implicitly.
5965  * - `to` (String) - if equal to 'string', then result will be "binary string"
5966  *    (each char code [0..255])
5967  *
5968  * ##### Example:
5969  *
5970  * ```javascript
5971  * var pako = require('pako')
5972  *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
5973  *
5974  * console.log(pako.deflate(data));
5975  * ```
5976  **/
5977 function deflate(input, options) {
5978   var deflator = new Deflate(options);
5979
5980   deflator.push(input, true);
5981
5982   // That will never happens, if you don't cheat with options :)
5983   if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
5984
5985   return deflator.result;
5986 }
5987
5988
5989 /**
5990  * deflateRaw(data[, options]) -> Uint8Array|Array|String
5991  * - data (Uint8Array|Array|String): input data to compress.
5992  * - options (Object): zlib deflate options.
5993  *
5994  * The same as [[deflate]], but creates raw data, without wrapper
5995  * (header and adler32 crc).
5996  **/
5997 function deflateRaw(input, options) {
5998   options = options || {};
5999   options.raw = true;
6000   return deflate(input, options);
6001 }
6002
6003
6004 /**
6005  * gzip(data[, options]) -> Uint8Array|Array|String
6006  * - data (Uint8Array|Array|String): input data to compress.
6007  * - options (Object): zlib deflate options.
6008  *
6009  * The same as [[deflate]], but create gzip wrapper instead of
6010  * deflate one.
6011  **/
6012 function gzip(input, options) {
6013   options = options || {};
6014   options.gzip = true;
6015   return deflate(input, options);
6016 }
6017
6018
6019 exports.Deflate = Deflate;
6020 exports.deflate = deflate;
6021 exports.deflateRaw = deflateRaw;
6022 exports.gzip = gzip;
6023
6024 },{"./utils/common":26,"./utils/strings":27,"./zlib/deflate":31,"./zlib/messages":36,"./zlib/zstream":38}],25:[function(require,module,exports){
6025 'use strict';
6026
6027
6028 var zlib_inflate = require('./zlib/inflate');
6029 var utils        = require('./utils/common');
6030 var strings      = require('./utils/strings');
6031 var c            = require('./zlib/constants');
6032 var msg          = require('./zlib/messages');
6033 var ZStream      = require('./zlib/zstream');
6034 var GZheader     = require('./zlib/gzheader');
6035
6036 var toString = Object.prototype.toString;
6037
6038 /**
6039  * class Inflate
6040  *
6041  * Generic JS-style wrapper for zlib calls. If you don't need
6042  * streaming behaviour - use more simple functions: [[inflate]]
6043  * and [[inflateRaw]].
6044  **/
6045
6046 /* internal
6047  * inflate.chunks -> Array
6048  *
6049  * Chunks of output data, if [[Inflate#onData]] not overridden.
6050  **/
6051
6052 /**
6053  * Inflate.result -> Uint8Array|Array|String
6054  *
6055  * Uncompressed result, generated by default [[Inflate#onData]]
6056  * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
6057  * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
6058  * push a chunk with explicit flush (call [[Inflate#push]] with
6059  * `Z_SYNC_FLUSH` param).
6060  **/
6061
6062 /**
6063  * Inflate.err -> Number
6064  *
6065  * Error code after inflate finished. 0 (Z_OK) on success.
6066  * Should be checked if broken data possible.
6067  **/
6068
6069 /**
6070  * Inflate.msg -> String
6071  *
6072  * Error message, if [[Inflate.err]] != 0
6073  **/
6074
6075
6076 /**
6077  * new Inflate(options)
6078  * - options (Object): zlib inflate options.
6079  *
6080  * Creates new inflator instance with specified params. Throws exception
6081  * on bad params. Supported options:
6082  *
6083  * - `windowBits`
6084  * - `dictionary`
6085  *
6086  * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
6087  * for more information on these.
6088  *
6089  * Additional options, for internal needs:
6090  *
6091  * - `chunkSize` - size of generated data chunks (16K by default)
6092  * - `raw` (Boolean) - do raw inflate
6093  * - `to` (String) - if equal to 'string', then result will be converted
6094  *   from utf8 to utf16 (javascript) string. When string output requested,
6095  *   chunk length can differ from `chunkSize`, depending on content.
6096  *
6097  * By default, when no options set, autodetect deflate/gzip data format via
6098  * wrapper header.
6099  *
6100  * ##### Example:
6101  *
6102  * ```javascript
6103  * var pako = require('pako')
6104  *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
6105  *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
6106  *
6107  * var inflate = new pako.Inflate({ level: 3});
6108  *
6109  * inflate.push(chunk1, false);
6110  * inflate.push(chunk2, true);  // true -> last chunk
6111  *
6112  * if (inflate.err) { throw new Error(inflate.err); }
6113  *
6114  * console.log(inflate.result);
6115  * ```
6116  **/
6117 function Inflate(options) {
6118   if (!(this instanceof Inflate)) return new Inflate(options);
6119
6120   this.options = utils.assign({
6121     chunkSize: 16384,
6122     windowBits: 0,
6123     to: ''
6124   }, options || {});
6125
6126   var opt = this.options;
6127
6128   // Force window size for `raw` data, if not set directly,
6129   // because we have no header for autodetect.
6130   if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
6131     opt.windowBits = -opt.windowBits;
6132     if (opt.windowBits === 0) { opt.windowBits = -15; }
6133   }
6134
6135   // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
6136   if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
6137       !(options && options.windowBits)) {
6138     opt.windowBits += 32;
6139   }
6140
6141   // Gzip header has no info about windows size, we can do autodetect only
6142   // for deflate. So, if window size not set, force it to max when gzip possible
6143   if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
6144     // bit 3 (16) -> gzipped data
6145     // bit 4 (32) -> autodetect gzip/deflate
6146     if ((opt.windowBits & 15) === 0) {
6147       opt.windowBits |= 15;
6148     }
6149   }
6150
6151   this.err    = 0;      // error code, if happens (0 = Z_OK)
6152   this.msg    = '';     // error message
6153   this.ended  = false;  // used to avoid multiple onEnd() calls
6154   this.chunks = [];     // chunks of compressed data
6155
6156   this.strm   = new ZStream();
6157   this.strm.avail_out = 0;
6158
6159   var status  = zlib_inflate.inflateInit2(
6160     this.strm,
6161     opt.windowBits
6162   );
6163
6164   if (status !== c.Z_OK) {
6165     throw new Error(msg[status]);
6166   }
6167
6168   this.header = new GZheader();
6169
6170   zlib_inflate.inflateGetHeader(this.strm, this.header);
6171
6172   // Setup dictionary
6173   if (opt.dictionary) {
6174     // Convert data if needed
6175     if (typeof opt.dictionary === 'string') {
6176       opt.dictionary = strings.string2buf(opt.dictionary);
6177     } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
6178       opt.dictionary = new Uint8Array(opt.dictionary);
6179     }
6180     if (opt.raw) { //In raw mode we need to set the dictionary early
6181       status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
6182       if (status !== c.Z_OK) {
6183         throw new Error(msg[status]);
6184       }
6185     }
6186   }
6187 }
6188
6189 /**
6190  * Inflate#push(data[, mode]) -> Boolean
6191  * - data (Uint8Array|Array|ArrayBuffer|String): input data
6192  * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
6193  *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
6194  *
6195  * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
6196  * new output chunks. Returns `true` on success. The last data block must have
6197  * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
6198  * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
6199  * can use mode Z_SYNC_FLUSH, keeping the decompression context.
6200  *
6201  * On fail call [[Inflate#onEnd]] with error code and return false.
6202  *
6203  * We strongly recommend to use `Uint8Array` on input for best speed (output
6204  * format is detected automatically). Also, don't skip last param and always
6205  * use the same type in your code (boolean or number). That will improve JS speed.
6206  *
6207  * For regular `Array`-s make sure all elements are [0..255].
6208  *
6209  * ##### Example
6210  *
6211  * ```javascript
6212  * push(chunk, false); // push one of data chunks
6213  * ...
6214  * push(chunk, true);  // push last chunk
6215  * ```
6216  **/
6217 Inflate.prototype.push = function (data, mode) {
6218   var strm = this.strm;
6219   var chunkSize = this.options.chunkSize;
6220   var dictionary = this.options.dictionary;
6221   var status, _mode;
6222   var next_out_utf8, tail, utf8str;
6223
6224   // Flag to properly process Z_BUF_ERROR on testing inflate call
6225   // when we check that all output data was flushed.
6226   var allowBufError = false;
6227
6228   if (this.ended) { return false; }
6229   _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
6230
6231   // Convert data if needed
6232   if (typeof data === 'string') {
6233     // Only binary strings can be decompressed on practice
6234     strm.input = strings.binstring2buf(data);
6235   } else if (toString.call(data) === '[object ArrayBuffer]') {
6236     strm.input = new Uint8Array(data);
6237   } else {
6238     strm.input = data;
6239   }
6240
6241   strm.next_in = 0;
6242   strm.avail_in = strm.input.length;
6243
6244   do {
6245     if (strm.avail_out === 0) {
6246       strm.output = new utils.Buf8(chunkSize);
6247       strm.next_out = 0;
6248       strm.avail_out = chunkSize;
6249     }
6250
6251     status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);    /* no bad return value */
6252
6253     if (status === c.Z_NEED_DICT && dictionary) {
6254       status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
6255     }
6256
6257     if (status === c.Z_BUF_ERROR && allowBufError === true) {
6258       status = c.Z_OK;
6259       allowBufError = false;
6260     }
6261
6262     if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
6263       this.onEnd(status);
6264       this.ended = true;
6265       return false;
6266     }
6267
6268     if (strm.next_out) {
6269       if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
6270
6271         if (this.options.to === 'string') {
6272
6273           next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
6274
6275           tail = strm.next_out - next_out_utf8;
6276           utf8str = strings.buf2string(strm.output, next_out_utf8);
6277
6278           // move tail
6279           strm.next_out = tail;
6280           strm.avail_out = chunkSize - tail;
6281           if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
6282
6283           this.onData(utf8str);
6284
6285         } else {
6286           this.onData(utils.shrinkBuf(strm.output, strm.next_out));
6287         }
6288       }
6289     }
6290
6291     // When no more input data, we should check that internal inflate buffers
6292     // are flushed. The only way to do it when avail_out = 0 - run one more
6293     // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
6294     // Here we set flag to process this error properly.
6295     //
6296     // NOTE. Deflate does not return error in this case and does not needs such
6297     // logic.
6298     if (strm.avail_in === 0 && strm.avail_out === 0) {
6299       allowBufError = true;
6300     }
6301
6302   } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
6303
6304   if (status === c.Z_STREAM_END) {
6305     _mode = c.Z_FINISH;
6306   }
6307
6308   // Finalize on the last chunk.
6309   if (_mode === c.Z_FINISH) {
6310     status = zlib_inflate.inflateEnd(this.strm);
6311     this.onEnd(status);
6312     this.ended = true;
6313     return status === c.Z_OK;
6314   }
6315
6316   // callback interim results if Z_SYNC_FLUSH.
6317   if (_mode === c.Z_SYNC_FLUSH) {
6318     this.onEnd(c.Z_OK);
6319     strm.avail_out = 0;
6320     return true;
6321   }
6322
6323   return true;
6324 };
6325
6326
6327 /**
6328  * Inflate#onData(chunk) -> Void
6329  * - chunk (Uint8Array|Array|String): output data. Type of array depends
6330  *   on js engine support. When string output requested, each chunk
6331  *   will be string.
6332  *
6333  * By default, stores data blocks in `chunks[]` property and glue
6334  * those in `onEnd`. Override this handler, if you need another behaviour.
6335  **/
6336 Inflate.prototype.onData = function (chunk) {
6337   this.chunks.push(chunk);
6338 };
6339
6340
6341 /**
6342  * Inflate#onEnd(status) -> Void
6343  * - status (Number): inflate status. 0 (Z_OK) on success,
6344  *   other if not.
6345  *
6346  * Called either after you tell inflate that the input stream is
6347  * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
6348  * or if an error happened. By default - join collected chunks,
6349  * free memory and fill `results` / `err` properties.
6350  **/
6351 Inflate.prototype.onEnd = function (status) {
6352   // On success - join
6353   if (status === c.Z_OK) {
6354     if (this.options.to === 'string') {
6355       // Glue & convert here, until we teach pako to send
6356       // utf8 aligned strings to onData
6357       this.result = this.chunks.join('');
6358     } else {
6359       this.result = utils.flattenChunks(this.chunks);
6360     }
6361   }
6362   this.chunks = [];
6363   this.err = status;
6364   this.msg = this.strm.msg;
6365 };
6366
6367
6368 /**
6369  * inflate(data[, options]) -> Uint8Array|Array|String
6370  * - data (Uint8Array|Array|String): input data to decompress.
6371  * - options (Object): zlib inflate options.
6372  *
6373  * Decompress `data` with inflate/ungzip and `options`. Autodetect
6374  * format via wrapper header by default. That's why we don't provide
6375  * separate `ungzip` method.
6376  *
6377  * Supported options are:
6378  *
6379  * - windowBits
6380  *
6381  * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
6382  * for more information.
6383  *
6384  * Sugar (options):
6385  *
6386  * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
6387  *   negative windowBits implicitly.
6388  * - `to` (String) - if equal to 'string', then result will be converted
6389  *   from utf8 to utf16 (javascript) string. When string output requested,
6390  *   chunk length can differ from `chunkSize`, depending on content.
6391  *
6392  *
6393  * ##### Example:
6394  *
6395  * ```javascript
6396  * var pako = require('pako')
6397  *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
6398  *   , output;
6399  *
6400  * try {
6401  *   output = pako.inflate(input);
6402  * } catch (err)
6403  *   console.log(err);
6404  * }
6405  * ```
6406  **/
6407 function inflate(input, options) {
6408   var inflator = new Inflate(options);
6409
6410   inflator.push(input, true);
6411
6412   // That will never happens, if you don't cheat with options :)
6413   if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
6414
6415   return inflator.result;
6416 }
6417
6418
6419 /**
6420  * inflateRaw(data[, options]) -> Uint8Array|Array|String
6421  * - data (Uint8Array|Array|String): input data to decompress.
6422  * - options (Object): zlib inflate options.
6423  *
6424  * The same as [[inflate]], but creates raw data, without wrapper
6425  * (header and adler32 crc).
6426  **/
6427 function inflateRaw(input, options) {
6428   options = options || {};
6429   options.raw = true;
6430   return inflate(input, options);
6431 }
6432
6433
6434 /**
6435  * ungzip(data[, options]) -> Uint8Array|Array|String
6436  * - data (Uint8Array|Array|String): input data to decompress.
6437  * - options (Object): zlib inflate options.
6438  *
6439  * Just shortcut to [[inflate]], because it autodetects format
6440  * by header.content. Done for convenience.
6441  **/
6442
6443
6444 exports.Inflate = Inflate;
6445 exports.inflate = inflate;
6446 exports.inflateRaw = inflateRaw;
6447 exports.ungzip  = inflate;
6448
6449 },{"./utils/common":26,"./utils/strings":27,"./zlib/constants":29,"./zlib/gzheader":32,"./zlib/inflate":34,"./zlib/messages":36,"./zlib/zstream":38}],26:[function(require,module,exports){
6450 'use strict';
6451
6452
6453 var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
6454                 (typeof Uint16Array !== 'undefined') &&
6455                 (typeof Int32Array !== 'undefined');
6456
6457 function _has(obj, key) {
6458   return Object.prototype.hasOwnProperty.call(obj, key);
6459 }
6460
6461 exports.assign = function (obj /*from1, from2, from3, ...*/) {
6462   var sources = Array.prototype.slice.call(arguments, 1);
6463   while (sources.length) {
6464     var source = sources.shift();
6465     if (!source) { continue; }
6466
6467     if (typeof source !== 'object') {
6468       throw new TypeError(source + 'must be non-object');
6469     }
6470
6471     for (var p in source) {
6472       if (_has(source, p)) {
6473         obj[p] = source[p];
6474       }
6475     }
6476   }
6477
6478   return obj;
6479 };
6480
6481
6482 // reduce buffer size, avoiding mem copy
6483 exports.shrinkBuf = function (buf, size) {
6484   if (buf.length === size) { return buf; }
6485   if (buf.subarray) { return buf.subarray(0, size); }
6486   buf.length = size;
6487   return buf;
6488 };
6489
6490
6491 var fnTyped = {
6492   arraySet: function (dest, src, src_offs, len, dest_offs) {
6493     if (src.subarray && dest.subarray) {
6494       dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
6495       return;
6496     }
6497     // Fallback to ordinary array
6498     for (var i = 0; i < len; i++) {
6499       dest[dest_offs + i] = src[src_offs + i];
6500     }
6501   },
6502   // Join array of chunks to single array.
6503   flattenChunks: function (chunks) {
6504     var i, l, len, pos, chunk, result;
6505
6506     // calculate data length
6507     len = 0;
6508     for (i = 0, l = chunks.length; i < l; i++) {
6509       len += chunks[i].length;
6510     }
6511
6512     // join chunks
6513     result = new Uint8Array(len);
6514     pos = 0;
6515     for (i = 0, l = chunks.length; i < l; i++) {
6516       chunk = chunks[i];
6517       result.set(chunk, pos);
6518       pos += chunk.length;
6519     }
6520
6521     return result;
6522   }
6523 };
6524
6525 var fnUntyped = {
6526   arraySet: function (dest, src, src_offs, len, dest_offs) {
6527     for (var i = 0; i < len; i++) {
6528       dest[dest_offs + i] = src[src_offs + i];
6529     }
6530   },
6531   // Join array of chunks to single array.
6532   flattenChunks: function (chunks) {
6533     return [].concat.apply([], chunks);
6534   }
6535 };
6536
6537
6538 // Enable/Disable typed arrays use, for testing
6539 //
6540 exports.setTyped = function (on) {
6541   if (on) {
6542     exports.Buf8  = Uint8Array;
6543     exports.Buf16 = Uint16Array;
6544     exports.Buf32 = Int32Array;
6545     exports.assign(exports, fnTyped);
6546   } else {
6547     exports.Buf8  = Array;
6548     exports.Buf16 = Array;
6549     exports.Buf32 = Array;
6550     exports.assign(exports, fnUntyped);
6551   }
6552 };
6553
6554 exports.setTyped(TYPED_OK);
6555
6556 },{}],27:[function(require,module,exports){
6557 // String encode/decode helpers
6558 'use strict';
6559
6560
6561 var utils = require('./common');
6562
6563
6564 // Quick check if we can use fast array to bin string conversion
6565 //
6566 // - apply(Array) can fail on Android 2.2
6567 // - apply(Uint8Array) can fail on iOS 5.1 Safari
6568 //
6569 var STR_APPLY_OK = true;
6570 var STR_APPLY_UIA_OK = true;
6571
6572 try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
6573 try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
6574
6575
6576 // Table with utf8 lengths (calculated by first byte of sequence)
6577 // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
6578 // because max possible codepoint is 0x10ffff
6579 var _utf8len = new utils.Buf8(256);
6580 for (var q = 0; q < 256; q++) {
6581   _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
6582 }
6583 _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
6584
6585
6586 // convert string to array (typed, when possible)
6587 exports.string2buf = function (str) {
6588   var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
6589
6590   // count binary size
6591   for (m_pos = 0; m_pos < str_len; m_pos++) {
6592     c = str.charCodeAt(m_pos);
6593     if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
6594       c2 = str.charCodeAt(m_pos + 1);
6595       if ((c2 & 0xfc00) === 0xdc00) {
6596         c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
6597         m_pos++;
6598       }
6599     }
6600     buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
6601   }
6602
6603   // allocate buffer
6604   buf = new utils.Buf8(buf_len);
6605
6606   // convert
6607   for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
6608     c = str.charCodeAt(m_pos);
6609     if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
6610       c2 = str.charCodeAt(m_pos + 1);
6611       if ((c2 & 0xfc00) === 0xdc00) {
6612         c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
6613         m_pos++;
6614       }
6615     }
6616     if (c < 0x80) {
6617       /* one byte */
6618       buf[i++] = c;
6619     } else if (c < 0x800) {
6620       /* two bytes */
6621       buf[i++] = 0xC0 | (c >>> 6);
6622       buf[i++] = 0x80 | (c & 0x3f);
6623     } else if (c < 0x10000) {
6624       /* three bytes */
6625       buf[i++] = 0xE0 | (c >>> 12);
6626       buf[i++] = 0x80 | (c >>> 6 & 0x3f);
6627       buf[i++] = 0x80 | (c & 0x3f);
6628     } else {
6629       /* four bytes */
6630       buf[i++] = 0xf0 | (c >>> 18);
6631       buf[i++] = 0x80 | (c >>> 12 & 0x3f);
6632       buf[i++] = 0x80 | (c >>> 6 & 0x3f);
6633       buf[i++] = 0x80 | (c & 0x3f);
6634     }
6635   }
6636
6637   return buf;
6638 };
6639
6640 // Helper (used in 2 places)
6641 function buf2binstring(buf, len) {
6642   // On Chrome, the arguments in a function call that are allowed is `65534`.
6643   // If the length of the buffer is smaller than that, we can use this optimization,
6644   // otherwise we will take a slower path.
6645   if (len < 65534) {
6646     if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
6647       return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
6648     }
6649   }
6650
6651   var result = '';
6652   for (var i = 0; i < len; i++) {
6653     result += String.fromCharCode(buf[i]);
6654   }
6655   return result;
6656 }
6657
6658
6659 // Convert byte array to binary string
6660 exports.buf2binstring = function (buf) {
6661   return buf2binstring(buf, buf.length);
6662 };
6663
6664
6665 // Convert binary string (typed, when possible)
6666 exports.binstring2buf = function (str) {
6667   var buf = new utils.Buf8(str.length);
6668   for (var i = 0, len = buf.length; i < len; i++) {
6669     buf[i] = str.charCodeAt(i);
6670   }
6671   return buf;
6672 };
6673
6674
6675 // convert array to string
6676 exports.buf2string = function (buf, max) {
6677   var i, out, c, c_len;
6678   var len = max || buf.length;
6679
6680   // Reserve max possible length (2 words per char)
6681   // NB: by unknown reasons, Array is significantly faster for
6682   //     String.fromCharCode.apply than Uint16Array.
6683   var utf16buf = new Array(len * 2);
6684
6685   for (out = 0, i = 0; i < len;) {
6686     c = buf[i++];
6687     // quick process ascii
6688     if (c < 0x80) { utf16buf[out++] = c; continue; }
6689
6690     c_len = _utf8len[c];
6691     // skip 5 & 6 byte codes
6692     if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
6693
6694     // apply mask on first byte
6695     c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
6696     // join the rest
6697     while (c_len > 1 && i < len) {
6698       c = (c << 6) | (buf[i++] & 0x3f);
6699       c_len--;
6700     }
6701
6702     // terminated by end of string?
6703     if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
6704
6705     if (c < 0x10000) {
6706       utf16buf[out++] = c;
6707     } else {
6708       c -= 0x10000;
6709       utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
6710       utf16buf[out++] = 0xdc00 | (c & 0x3ff);
6711     }
6712   }
6713
6714   return buf2binstring(utf16buf, out);
6715 };
6716
6717
6718 // Calculate max possible position in utf8 buffer,
6719 // that will not break sequence. If that's not possible
6720 // - (very small limits) return max size as is.
6721 //
6722 // buf[] - utf8 bytes array
6723 // max   - length limit (mandatory);
6724 exports.utf8border = function (buf, max) {
6725   var pos;
6726
6727   max = max || buf.length;
6728   if (max > buf.length) { max = buf.length; }
6729
6730   // go back from last position, until start of sequence found
6731   pos = max - 1;
6732   while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
6733
6734   // Very small and broken sequence,
6735   // return max, because we should return something anyway.
6736   if (pos < 0) { return max; }
6737
6738   // If we came to start of buffer - that means buffer is too small,
6739   // return max too.
6740   if (pos === 0) { return max; }
6741
6742   return (pos + _utf8len[buf[pos]] > max) ? pos : max;
6743 };
6744
6745 },{"./common":26}],28:[function(require,module,exports){
6746 'use strict';
6747
6748 // Note: adler32 takes 12% for level 0 and 2% for level 6.
6749 // It isn't worth it to make additional optimizations as in original.
6750 // Small size is preferable.
6751
6752 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
6753 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
6754 //
6755 // This software is provided 'as-is', without any express or implied
6756 // warranty. In no event will the authors be held liable for any damages
6757 // arising from the use of this software.
6758 //
6759 // Permission is granted to anyone to use this software for any purpose,
6760 // including commercial applications, and to alter it and redistribute it
6761 // freely, subject to the following restrictions:
6762 //
6763 // 1. The origin of this software must not be misrepresented; you must not
6764 //   claim that you wrote the original software. If you use this software
6765 //   in a product, an acknowledgment in the product documentation would be
6766 //   appreciated but is not required.
6767 // 2. Altered source versions must be plainly marked as such, and must not be
6768 //   misrepresented as being the original software.
6769 // 3. This notice may not be removed or altered from any source distribution.
6770
6771 function adler32(adler, buf, len, pos) {
6772   var s1 = (adler & 0xffff) |0,
6773       s2 = ((adler >>> 16) & 0xffff) |0,
6774       n = 0;
6775
6776   while (len !== 0) {
6777     // Set limit ~ twice less than 5552, to keep
6778     // s2 in 31-bits, because we force signed ints.
6779     // in other case %= will fail.
6780     n = len > 2000 ? 2000 : len;
6781     len -= n;
6782
6783     do {
6784       s1 = (s1 + buf[pos++]) |0;
6785       s2 = (s2 + s1) |0;
6786     } while (--n);
6787
6788     s1 %= 65521;
6789     s2 %= 65521;
6790   }
6791
6792   return (s1 | (s2 << 16)) |0;
6793 }
6794
6795
6796 module.exports = adler32;
6797
6798 },{}],29:[function(require,module,exports){
6799 'use strict';
6800
6801 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
6802 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
6803 //
6804 // This software is provided 'as-is', without any express or implied
6805 // warranty. In no event will the authors be held liable for any damages
6806 // arising from the use of this software.
6807 //
6808 // Permission is granted to anyone to use this software for any purpose,
6809 // including commercial applications, and to alter it and redistribute it
6810 // freely, subject to the following restrictions:
6811 //
6812 // 1. The origin of this software must not be misrepresented; you must not
6813 //   claim that you wrote the original software. If you use this software
6814 //   in a product, an acknowledgment in the product documentation would be
6815 //   appreciated but is not required.
6816 // 2. Altered source versions must be plainly marked as such, and must not be
6817 //   misrepresented as being the original software.
6818 // 3. This notice may not be removed or altered from any source distribution.
6819
6820 module.exports = {
6821
6822   /* Allowed flush values; see deflate() and inflate() below for details */
6823   Z_NO_FLUSH:         0,
6824   Z_PARTIAL_FLUSH:    1,
6825   Z_SYNC_FLUSH:       2,
6826   Z_FULL_FLUSH:       3,
6827   Z_FINISH:           4,
6828   Z_BLOCK:            5,
6829   Z_TREES:            6,
6830
6831   /* Return codes for the compression/decompression functions. Negative values
6832   * are errors, positive values are used for special but normal events.
6833   */
6834   Z_OK:               0,
6835   Z_STREAM_END:       1,
6836   Z_NEED_DICT:        2,
6837   Z_ERRNO:           -1,
6838   Z_STREAM_ERROR:    -2,
6839   Z_DATA_ERROR:      -3,
6840   //Z_MEM_ERROR:     -4,
6841   Z_BUF_ERROR:       -5,
6842   //Z_VERSION_ERROR: -6,
6843
6844   /* compression levels */
6845   Z_NO_COMPRESSION:         0,
6846   Z_BEST_SPEED:             1,
6847   Z_BEST_COMPRESSION:       9,
6848   Z_DEFAULT_COMPRESSION:   -1,
6849
6850
6851   Z_FILTERED:               1,
6852   Z_HUFFMAN_ONLY:           2,
6853   Z_RLE:                    3,
6854   Z_FIXED:                  4,
6855   Z_DEFAULT_STRATEGY:       0,
6856
6857   /* Possible values of the data_type field (though see inflate()) */
6858   Z_BINARY:                 0,
6859   Z_TEXT:                   1,
6860   //Z_ASCII:                1, // = Z_TEXT (deprecated)
6861   Z_UNKNOWN:                2,
6862
6863   /* The deflate compression method */
6864   Z_DEFLATED:               8
6865   //Z_NULL:                 null // Use -1 or null inline, depending on var type
6866 };
6867
6868 },{}],30:[function(require,module,exports){
6869 'use strict';
6870
6871 // Note: we can't get significant speed boost here.
6872 // So write code to minimize size - no pregenerated tables
6873 // and array tools dependencies.
6874
6875 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
6876 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
6877 //
6878 // This software is provided 'as-is', without any express or implied
6879 // warranty. In no event will the authors be held liable for any damages
6880 // arising from the use of this software.
6881 //
6882 // Permission is granted to anyone to use this software for any purpose,
6883 // including commercial applications, and to alter it and redistribute it
6884 // freely, subject to the following restrictions:
6885 //
6886 // 1. The origin of this software must not be misrepresented; you must not
6887 //   claim that you wrote the original software. If you use this software
6888 //   in a product, an acknowledgment in the product documentation would be
6889 //   appreciated but is not required.
6890 // 2. Altered source versions must be plainly marked as such, and must not be
6891 //   misrepresented as being the original software.
6892 // 3. This notice may not be removed or altered from any source distribution.
6893
6894 // Use ordinary array, since untyped makes no boost here
6895 function makeTable() {
6896   var c, table = [];
6897
6898   for (var n = 0; n < 256; n++) {
6899     c = n;
6900     for (var k = 0; k < 8; k++) {
6901       c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
6902     }
6903     table[n] = c;
6904   }
6905
6906   return table;
6907 }
6908
6909 // Create table on load. Just 255 signed longs. Not a problem.
6910 var crcTable = makeTable();
6911
6912
6913 function crc32(crc, buf, len, pos) {
6914   var t = crcTable,
6915       end = pos + len;
6916
6917   crc ^= -1;
6918
6919   for (var i = pos; i < end; i++) {
6920     crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
6921   }
6922
6923   return (crc ^ (-1)); // >>> 0;
6924 }
6925
6926
6927 module.exports = crc32;
6928
6929 },{}],31:[function(require,module,exports){
6930 'use strict';
6931
6932 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
6933 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
6934 //
6935 // This software is provided 'as-is', without any express or implied
6936 // warranty. In no event will the authors be held liable for any damages
6937 // arising from the use of this software.
6938 //
6939 // Permission is granted to anyone to use this software for any purpose,
6940 // including commercial applications, and to alter it and redistribute it
6941 // freely, subject to the following restrictions:
6942 //
6943 // 1. The origin of this software must not be misrepresented; you must not
6944 //   claim that you wrote the original software. If you use this software
6945 //   in a product, an acknowledgment in the product documentation would be
6946 //   appreciated but is not required.
6947 // 2. Altered source versions must be plainly marked as such, and must not be
6948 //   misrepresented as being the original software.
6949 // 3. This notice may not be removed or altered from any source distribution.
6950
6951 var utils   = require('../utils/common');
6952 var trees   = require('./trees');
6953 var adler32 = require('./adler32');
6954 var crc32   = require('./crc32');
6955 var msg     = require('./messages');
6956
6957 /* Public constants ==========================================================*/
6958 /* ===========================================================================*/
6959
6960
6961 /* Allowed flush values; see deflate() and inflate() below for details */
6962 var Z_NO_FLUSH      = 0;
6963 var Z_PARTIAL_FLUSH = 1;
6964 //var Z_SYNC_FLUSH    = 2;
6965 var Z_FULL_FLUSH    = 3;
6966 var Z_FINISH        = 4;
6967 var Z_BLOCK         = 5;
6968 //var Z_TREES         = 6;
6969
6970
6971 /* Return codes for the compression/decompression functions. Negative values
6972  * are errors, positive values are used for special but normal events.
6973  */
6974 var Z_OK            = 0;
6975 var Z_STREAM_END    = 1;
6976 //var Z_NEED_DICT     = 2;
6977 //var Z_ERRNO         = -1;
6978 var Z_STREAM_ERROR  = -2;
6979 var Z_DATA_ERROR    = -3;
6980 //var Z_MEM_ERROR     = -4;
6981 var Z_BUF_ERROR     = -5;
6982 //var Z_VERSION_ERROR = -6;
6983
6984
6985 /* compression levels */
6986 //var Z_NO_COMPRESSION      = 0;
6987 //var Z_BEST_SPEED          = 1;
6988 //var Z_BEST_COMPRESSION    = 9;
6989 var Z_DEFAULT_COMPRESSION = -1;
6990
6991
6992 var Z_FILTERED            = 1;
6993 var Z_HUFFMAN_ONLY        = 2;
6994 var Z_RLE                 = 3;
6995 var Z_FIXED               = 4;
6996 var Z_DEFAULT_STRATEGY    = 0;
6997
6998 /* Possible values of the data_type field (though see inflate()) */
6999 //var Z_BINARY              = 0;
7000 //var Z_TEXT                = 1;
7001 //var Z_ASCII               = 1; // = Z_TEXT
7002 var Z_UNKNOWN             = 2;
7003
7004
7005 /* The deflate compression method */
7006 var Z_DEFLATED  = 8;
7007
7008 /*============================================================================*/
7009
7010
7011 var MAX_MEM_LEVEL = 9;
7012 /* Maximum value for memLevel in deflateInit2 */
7013 var MAX_WBITS = 15;
7014 /* 32K LZ77 window */
7015 var DEF_MEM_LEVEL = 8;
7016
7017
7018 var LENGTH_CODES  = 29;
7019 /* number of length codes, not counting the special END_BLOCK code */
7020 var LITERALS      = 256;
7021 /* number of literal bytes 0..255 */
7022 var L_CODES       = LITERALS + 1 + LENGTH_CODES;
7023 /* number of Literal or Length codes, including the END_BLOCK code */
7024 var D_CODES       = 30;
7025 /* number of distance codes */
7026 var BL_CODES      = 19;
7027 /* number of codes used to transfer the bit lengths */
7028 var HEAP_SIZE     = 2 * L_CODES + 1;
7029 /* maximum heap size */
7030 var MAX_BITS  = 15;
7031 /* All codes must not exceed MAX_BITS bits */
7032
7033 var MIN_MATCH = 3;
7034 var MAX_MATCH = 258;
7035 var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
7036
7037 var PRESET_DICT = 0x20;
7038
7039 var INIT_STATE = 42;
7040 var EXTRA_STATE = 69;
7041 var NAME_STATE = 73;
7042 var COMMENT_STATE = 91;
7043 var HCRC_STATE = 103;
7044 var BUSY_STATE = 113;
7045 var FINISH_STATE = 666;
7046
7047 var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
7048 var BS_BLOCK_DONE     = 2; /* block flush performed */
7049 var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
7050 var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
7051
7052 var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
7053
7054 function err(strm, errorCode) {
7055   strm.msg = msg[errorCode];
7056   return errorCode;
7057 }
7058
7059 function rank(f) {
7060   return ((f) << 1) - ((f) > 4 ? 9 : 0);
7061 }
7062
7063 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
7064
7065
7066 /* =========================================================================
7067  * Flush as much pending output as possible. All deflate() output goes
7068  * through this function so some applications may wish to modify it
7069  * to avoid allocating a large strm->output buffer and copying into it.
7070  * (See also read_buf()).
7071  */
7072 function flush_pending(strm) {
7073   var s = strm.state;
7074
7075   //_tr_flush_bits(s);
7076   var len = s.pending;
7077   if (len > strm.avail_out) {
7078     len = strm.avail_out;
7079   }
7080   if (len === 0) { return; }
7081
7082   utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
7083   strm.next_out += len;
7084   s.pending_out += len;
7085   strm.total_out += len;
7086   strm.avail_out -= len;
7087   s.pending -= len;
7088   if (s.pending === 0) {
7089     s.pending_out = 0;
7090   }
7091 }
7092
7093
7094 function flush_block_only(s, last) {
7095   trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
7096   s.block_start = s.strstart;
7097   flush_pending(s.strm);
7098 }
7099
7100
7101 function put_byte(s, b) {
7102   s.pending_buf[s.pending++] = b;
7103 }
7104
7105
7106 /* =========================================================================
7107  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
7108  * IN assertion: the stream state is correct and there is enough room in
7109  * pending_buf.
7110  */
7111 function putShortMSB(s, b) {
7112 //  put_byte(s, (Byte)(b >> 8));
7113 //  put_byte(s, (Byte)(b & 0xff));
7114   s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
7115   s.pending_buf[s.pending++] = b & 0xff;
7116 }
7117
7118
7119 /* ===========================================================================
7120  * Read a new buffer from the current input stream, update the adler32
7121  * and total number of bytes read.  All deflate() input goes through
7122  * this function so some applications may wish to modify it to avoid
7123  * allocating a large strm->input buffer and copying from it.
7124  * (See also flush_pending()).
7125  */
7126 function read_buf(strm, buf, start, size) {
7127   var len = strm.avail_in;
7128
7129   if (len > size) { len = size; }
7130   if (len === 0) { return 0; }
7131
7132   strm.avail_in -= len;
7133
7134   // zmemcpy(buf, strm->next_in, len);
7135   utils.arraySet(buf, strm.input, strm.next_in, len, start);
7136   if (strm.state.wrap === 1) {
7137     strm.adler = adler32(strm.adler, buf, len, start);
7138   }
7139
7140   else if (strm.state.wrap === 2) {
7141     strm.adler = crc32(strm.adler, buf, len, start);
7142   }
7143
7144   strm.next_in += len;
7145   strm.total_in += len;
7146
7147   return len;
7148 }
7149
7150
7151 /* ===========================================================================
7152  * Set match_start to the longest match starting at the given string and
7153  * return its length. Matches shorter or equal to prev_length are discarded,
7154  * in which case the result is equal to prev_length and match_start is
7155  * garbage.
7156  * IN assertions: cur_match is the head of the hash chain for the current
7157  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
7158  * OUT assertion: the match length is not greater than s->lookahead.
7159  */
7160 function longest_match(s, cur_match) {
7161   var chain_length = s.max_chain_length;      /* max hash chain length */
7162   var scan = s.strstart; /* current string */
7163   var match;                       /* matched string */
7164   var len;                           /* length of current match */
7165   var best_len = s.prev_length;              /* best match length so far */
7166   var nice_match = s.nice_match;             /* stop if match long enough */
7167   var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
7168       s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
7169
7170   var _win = s.window; // shortcut
7171
7172   var wmask = s.w_mask;
7173   var prev  = s.prev;
7174
7175   /* Stop when cur_match becomes <= limit. To simplify the code,
7176    * we prevent matches with the string of window index 0.
7177    */
7178
7179   var strend = s.strstart + MAX_MATCH;
7180   var scan_end1  = _win[scan + best_len - 1];
7181   var scan_end   = _win[scan + best_len];
7182
7183   /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
7184    * It is easy to get rid of this optimization if necessary.
7185    */
7186   // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
7187
7188   /* Do not waste too much time if we already have a good match: */
7189   if (s.prev_length >= s.good_match) {
7190     chain_length >>= 2;
7191   }
7192   /* Do not look for matches beyond the end of the input. This is necessary
7193    * to make deflate deterministic.
7194    */
7195   if (nice_match > s.lookahead) { nice_match = s.lookahead; }
7196
7197   // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
7198
7199   do {
7200     // Assert(cur_match < s->strstart, "no future");
7201     match = cur_match;
7202
7203     /* Skip to next match if the match length cannot increase
7204      * or if the match length is less than 2.  Note that the checks below
7205      * for insufficient lookahead only occur occasionally for performance
7206      * reasons.  Therefore uninitialized memory will be accessed, and
7207      * conditional jumps will be made that depend on those values.
7208      * However the length of the match is limited to the lookahead, so
7209      * the output of deflate is not affected by the uninitialized values.
7210      */
7211
7212     if (_win[match + best_len]     !== scan_end  ||
7213         _win[match + best_len - 1] !== scan_end1 ||
7214         _win[match]                !== _win[scan] ||
7215         _win[++match]              !== _win[scan + 1]) {
7216       continue;
7217     }
7218
7219     /* The check at best_len-1 can be removed because it will be made
7220      * again later. (This heuristic is not always a win.)
7221      * It is not necessary to compare scan[2] and match[2] since they
7222      * are always equal when the other bytes match, given that
7223      * the hash keys are equal and that HASH_BITS >= 8.
7224      */
7225     scan += 2;
7226     match++;
7227     // Assert(*scan == *match, "match[2]?");
7228
7229     /* We check for insufficient lookahead only every 8th comparison;
7230      * the 256th check will be made at strstart+258.
7231      */
7232     do {
7233       /*jshint noempty:false*/
7234     } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
7235              _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
7236              _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
7237              _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
7238              scan < strend);
7239
7240     // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
7241
7242     len = MAX_MATCH - (strend - scan);
7243     scan = strend - MAX_MATCH;
7244
7245     if (len > best_len) {
7246       s.match_start = cur_match;
7247       best_len = len;
7248       if (len >= nice_match) {
7249         break;
7250       }
7251       scan_end1  = _win[scan + best_len - 1];
7252       scan_end   = _win[scan + best_len];
7253     }
7254   } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
7255
7256   if (best_len <= s.lookahead) {
7257     return best_len;
7258   }
7259   return s.lookahead;
7260 }
7261
7262
7263 /* ===========================================================================
7264  * Fill the window when the lookahead becomes insufficient.
7265  * Updates strstart and lookahead.
7266  *
7267  * IN assertion: lookahead < MIN_LOOKAHEAD
7268  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
7269  *    At least one byte has been read, or avail_in == 0; reads are
7270  *    performed for at least two bytes (required for the zip translate_eol
7271  *    option -- not supported here).
7272  */
7273 function fill_window(s) {
7274   var _w_size = s.w_size;
7275   var p, n, m, more, str;
7276
7277   //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
7278
7279   do {
7280     more = s.window_size - s.lookahead - s.strstart;
7281
7282     // JS ints have 32 bit, block below not needed
7283     /* Deal with !@#$% 64K limit: */
7284     //if (sizeof(int) <= 2) {
7285     //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
7286     //        more = wsize;
7287     //
7288     //  } else if (more == (unsigned)(-1)) {
7289     //        /* Very unlikely, but possible on 16 bit machine if
7290     //         * strstart == 0 && lookahead == 1 (input done a byte at time)
7291     //         */
7292     //        more--;
7293     //    }
7294     //}
7295
7296
7297     /* If the window is almost full and there is insufficient lookahead,
7298      * move the upper half to the lower one to make room in the upper half.
7299      */
7300     if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
7301
7302       utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
7303       s.match_start -= _w_size;
7304       s.strstart -= _w_size;
7305       /* we now have strstart >= MAX_DIST */
7306       s.block_start -= _w_size;
7307
7308       /* Slide the hash table (could be avoided with 32 bit values
7309        at the expense of memory usage). We slide even when level == 0
7310        to keep the hash table consistent if we switch back to level > 0
7311        later. (Using level 0 permanently is not an optimal usage of
7312        zlib, so we don't care about this pathological case.)
7313        */
7314
7315       n = s.hash_size;
7316       p = n;
7317       do {
7318         m = s.head[--p];
7319         s.head[p] = (m >= _w_size ? m - _w_size : 0);
7320       } while (--n);
7321
7322       n = _w_size;
7323       p = n;
7324       do {
7325         m = s.prev[--p];
7326         s.prev[p] = (m >= _w_size ? m - _w_size : 0);
7327         /* If n is not on any hash chain, prev[n] is garbage but
7328          * its value will never be used.
7329          */
7330       } while (--n);
7331
7332       more += _w_size;
7333     }
7334     if (s.strm.avail_in === 0) {
7335       break;
7336     }
7337
7338     /* If there was no sliding:
7339      *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
7340      *    more == window_size - lookahead - strstart
7341      * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
7342      * => more >= window_size - 2*WSIZE + 2
7343      * In the BIG_MEM or MMAP case (not yet supported),
7344      *   window_size == input_size + MIN_LOOKAHEAD  &&
7345      *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
7346      * Otherwise, window_size == 2*WSIZE so more >= 2.
7347      * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
7348      */
7349     //Assert(more >= 2, "more < 2");
7350     n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
7351     s.lookahead += n;
7352
7353     /* Initialize the hash value now that we have some input: */
7354     if (s.lookahead + s.insert >= MIN_MATCH) {
7355       str = s.strstart - s.insert;
7356       s.ins_h = s.window[str];
7357
7358       /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
7359       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
7360 //#if MIN_MATCH != 3
7361 //        Call update_hash() MIN_MATCH-3 more times
7362 //#endif
7363       while (s.insert) {
7364         /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
7365         s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
7366
7367         s.prev[str & s.w_mask] = s.head[s.ins_h];
7368         s.head[s.ins_h] = str;
7369         str++;
7370         s.insert--;
7371         if (s.lookahead + s.insert < MIN_MATCH) {
7372           break;
7373         }
7374       }
7375     }
7376     /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
7377      * but this is not important since only literal bytes will be emitted.
7378      */
7379
7380   } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
7381
7382   /* If the WIN_INIT bytes after the end of the current data have never been
7383    * written, then zero those bytes in order to avoid memory check reports of
7384    * the use of uninitialized (or uninitialised as Julian writes) bytes by
7385    * the longest match routines.  Update the high water mark for the next
7386    * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
7387    * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
7388    */
7389 //  if (s.high_water < s.window_size) {
7390 //    var curr = s.strstart + s.lookahead;
7391 //    var init = 0;
7392 //
7393 //    if (s.high_water < curr) {
7394 //      /* Previous high water mark below current data -- zero WIN_INIT
7395 //       * bytes or up to end of window, whichever is less.
7396 //       */
7397 //      init = s.window_size - curr;
7398 //      if (init > WIN_INIT)
7399 //        init = WIN_INIT;
7400 //      zmemzero(s->window + curr, (unsigned)init);
7401 //      s->high_water = curr + init;
7402 //    }
7403 //    else if (s->high_water < (ulg)curr + WIN_INIT) {
7404 //      /* High water mark at or above current data, but below current data
7405 //       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
7406 //       * to end of window, whichever is less.
7407 //       */
7408 //      init = (ulg)curr + WIN_INIT - s->high_water;
7409 //      if (init > s->window_size - s->high_water)
7410 //        init = s->window_size - s->high_water;
7411 //      zmemzero(s->window + s->high_water, (unsigned)init);
7412 //      s->high_water += init;
7413 //    }
7414 //  }
7415 //
7416 //  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
7417 //    "not enough room for search");
7418 }
7419
7420 /* ===========================================================================
7421  * Copy without compression as much as possible from the input stream, return
7422  * the current block state.
7423  * This function does not insert new strings in the dictionary since
7424  * uncompressible data is probably not useful. This function is used
7425  * only for the level=0 compression option.
7426  * NOTE: this function should be optimized to avoid extra copying from
7427  * window to pending_buf.
7428  */
7429 function deflate_stored(s, flush) {
7430   /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
7431    * to pending_buf_size, and each stored block has a 5 byte header:
7432    */
7433   var max_block_size = 0xffff;
7434
7435   if (max_block_size > s.pending_buf_size - 5) {
7436     max_block_size = s.pending_buf_size - 5;
7437   }
7438
7439   /* Copy as much as possible from input to output: */
7440   for (;;) {
7441     /* Fill the window as much as possible: */
7442     if (s.lookahead <= 1) {
7443
7444       //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
7445       //  s->block_start >= (long)s->w_size, "slide too late");
7446 //      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
7447 //        s.block_start >= s.w_size)) {
7448 //        throw  new Error("slide too late");
7449 //      }
7450
7451       fill_window(s);
7452       if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
7453         return BS_NEED_MORE;
7454       }
7455
7456       if (s.lookahead === 0) {
7457         break;
7458       }
7459       /* flush the current block */
7460     }
7461     //Assert(s->block_start >= 0L, "block gone");
7462 //    if (s.block_start < 0) throw new Error("block gone");
7463
7464     s.strstart += s.lookahead;
7465     s.lookahead = 0;
7466
7467     /* Emit a stored block if pending_buf will be full: */
7468     var max_start = s.block_start + max_block_size;
7469
7470     if (s.strstart === 0 || s.strstart >= max_start) {
7471       /* strstart == 0 is possible when wraparound on 16-bit machine */
7472       s.lookahead = s.strstart - max_start;
7473       s.strstart = max_start;
7474       /*** FLUSH_BLOCK(s, 0); ***/
7475       flush_block_only(s, false);
7476       if (s.strm.avail_out === 0) {
7477         return BS_NEED_MORE;
7478       }
7479       /***/
7480
7481
7482     }
7483     /* Flush if we may have to slide, otherwise block_start may become
7484      * negative and the data will be gone:
7485      */
7486     if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
7487       /*** FLUSH_BLOCK(s, 0); ***/
7488       flush_block_only(s, false);
7489       if (s.strm.avail_out === 0) {
7490         return BS_NEED_MORE;
7491       }
7492       /***/
7493     }
7494   }
7495
7496   s.insert = 0;
7497
7498   if (flush === Z_FINISH) {
7499     /*** FLUSH_BLOCK(s, 1); ***/
7500     flush_block_only(s, true);
7501     if (s.strm.avail_out === 0) {
7502       return BS_FINISH_STARTED;
7503     }
7504     /***/
7505     return BS_FINISH_DONE;
7506   }
7507
7508   if (s.strstart > s.block_start) {
7509     /*** FLUSH_BLOCK(s, 0); ***/
7510     flush_block_only(s, false);
7511     if (s.strm.avail_out === 0) {
7512       return BS_NEED_MORE;
7513     }
7514     /***/
7515   }
7516
7517   return BS_NEED_MORE;
7518 }
7519
7520 /* ===========================================================================
7521  * Compress as much as possible from the input stream, return the current
7522  * block state.
7523  * This function does not perform lazy evaluation of matches and inserts
7524  * new strings in the dictionary only for unmatched strings or for short
7525  * matches. It is used only for the fast compression options.
7526  */
7527 function deflate_fast(s, flush) {
7528   var hash_head;        /* head of the hash chain */
7529   var bflush;           /* set if current block must be flushed */
7530
7531   for (;;) {
7532     /* Make sure that we always have enough lookahead, except
7533      * at the end of the input file. We need MAX_MATCH bytes
7534      * for the next match, plus MIN_MATCH bytes to insert the
7535      * string following the next match.
7536      */
7537     if (s.lookahead < MIN_LOOKAHEAD) {
7538       fill_window(s);
7539       if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
7540         return BS_NEED_MORE;
7541       }
7542       if (s.lookahead === 0) {
7543         break; /* flush the current block */
7544       }
7545     }
7546
7547     /* Insert the string window[strstart .. strstart+2] in the
7548      * dictionary, and set hash_head to the head of the hash chain:
7549      */
7550     hash_head = 0/*NIL*/;
7551     if (s.lookahead >= MIN_MATCH) {
7552       /*** INSERT_STRING(s, s.strstart, hash_head); ***/
7553       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
7554       hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
7555       s.head[s.ins_h] = s.strstart;
7556       /***/
7557     }
7558
7559     /* Find the longest match, discarding those <= prev_length.
7560      * At this point we have always match_length < MIN_MATCH
7561      */
7562     if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
7563       /* To simplify the code, we prevent matches with the string
7564        * of window index 0 (in particular we have to avoid a match
7565        * of the string with itself at the start of the input file).
7566        */
7567       s.match_length = longest_match(s, hash_head);
7568       /* longest_match() sets match_start */
7569     }
7570     if (s.match_length >= MIN_MATCH) {
7571       // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
7572
7573       /*** _tr_tally_dist(s, s.strstart - s.match_start,
7574                      s.match_length - MIN_MATCH, bflush); ***/
7575       bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
7576
7577       s.lookahead -= s.match_length;
7578
7579       /* Insert new strings in the hash table only if the match length
7580        * is not too large. This saves time but degrades compression.
7581        */
7582       if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
7583         s.match_length--; /* string at strstart already in table */
7584         do {
7585           s.strstart++;
7586           /*** INSERT_STRING(s, s.strstart, hash_head); ***/
7587           s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
7588           hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
7589           s.head[s.ins_h] = s.strstart;
7590           /***/
7591           /* strstart never exceeds WSIZE-MAX_MATCH, so there are
7592            * always MIN_MATCH bytes ahead.
7593            */
7594         } while (--s.match_length !== 0);
7595         s.strstart++;
7596       } else
7597       {
7598         s.strstart += s.match_length;
7599         s.match_length = 0;
7600         s.ins_h = s.window[s.strstart];
7601         /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
7602         s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
7603
7604 //#if MIN_MATCH != 3
7605 //                Call UPDATE_HASH() MIN_MATCH-3 more times
7606 //#endif
7607         /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
7608          * matter since it will be recomputed at next deflate call.
7609          */
7610       }
7611     } else {
7612       /* No match, output a literal byte */
7613       //Tracevv((stderr,"%c", s.window[s.strstart]));
7614       /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
7615       bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
7616
7617       s.lookahead--;
7618       s.strstart++;
7619     }
7620     if (bflush) {
7621       /*** FLUSH_BLOCK(s, 0); ***/
7622       flush_block_only(s, false);
7623       if (s.strm.avail_out === 0) {
7624         return BS_NEED_MORE;
7625       }
7626       /***/
7627     }
7628   }
7629   s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
7630   if (flush === Z_FINISH) {
7631     /*** FLUSH_BLOCK(s, 1); ***/
7632     flush_block_only(s, true);
7633     if (s.strm.avail_out === 0) {
7634       return BS_FINISH_STARTED;
7635     }
7636     /***/
7637     return BS_FINISH_DONE;
7638   }
7639   if (s.last_lit) {
7640     /*** FLUSH_BLOCK(s, 0); ***/
7641     flush_block_only(s, false);
7642     if (s.strm.avail_out === 0) {
7643       return BS_NEED_MORE;
7644     }
7645     /***/
7646   }
7647   return BS_BLOCK_DONE;
7648 }
7649
7650 /* ===========================================================================
7651  * Same as above, but achieves better compression. We use a lazy
7652  * evaluation for matches: a match is finally adopted only if there is
7653  * no better match at the next window position.
7654  */
7655 function deflate_slow(s, flush) {
7656   var hash_head;          /* head of hash chain */
7657   var bflush;              /* set if current block must be flushed */
7658
7659   var max_insert;
7660
7661   /* Process the input block. */
7662   for (;;) {
7663     /* Make sure that we always have enough lookahead, except
7664      * at the end of the input file. We need MAX_MATCH bytes
7665      * for the next match, plus MIN_MATCH bytes to insert the
7666      * string following the next match.
7667      */
7668     if (s.lookahead < MIN_LOOKAHEAD) {
7669       fill_window(s);
7670       if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
7671         return BS_NEED_MORE;
7672       }
7673       if (s.lookahead === 0) { break; } /* flush the current block */
7674     }
7675
7676     /* Insert the string window[strstart .. strstart+2] in the
7677      * dictionary, and set hash_head to the head of the hash chain:
7678      */
7679     hash_head = 0/*NIL*/;
7680     if (s.lookahead >= MIN_MATCH) {
7681       /*** INSERT_STRING(s, s.strstart, hash_head); ***/
7682       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
7683       hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
7684       s.head[s.ins_h] = s.strstart;
7685       /***/
7686     }
7687
7688     /* Find the longest match, discarding those <= prev_length.
7689      */
7690     s.prev_length = s.match_length;
7691     s.prev_match = s.match_start;
7692     s.match_length = MIN_MATCH - 1;
7693
7694     if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
7695         s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
7696       /* To simplify the code, we prevent matches with the string
7697        * of window index 0 (in particular we have to avoid a match
7698        * of the string with itself at the start of the input file).
7699        */
7700       s.match_length = longest_match(s, hash_head);
7701       /* longest_match() sets match_start */
7702
7703       if (s.match_length <= 5 &&
7704          (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
7705
7706         /* If prev_match is also MIN_MATCH, match_start is garbage
7707          * but we will ignore the current match anyway.
7708          */
7709         s.match_length = MIN_MATCH - 1;
7710       }
7711     }
7712     /* If there was a match at the previous step and the current
7713      * match is not better, output the previous match:
7714      */
7715     if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
7716       max_insert = s.strstart + s.lookahead - MIN_MATCH;
7717       /* Do not insert strings in hash table beyond this. */
7718
7719       //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
7720
7721       /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
7722                      s.prev_length - MIN_MATCH, bflush);***/
7723       bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
7724       /* Insert in hash table all strings up to the end of the match.
7725        * strstart-1 and strstart are already inserted. If there is not
7726        * enough lookahead, the last two strings are not inserted in
7727        * the hash table.
7728        */
7729       s.lookahead -= s.prev_length - 1;
7730       s.prev_length -= 2;
7731       do {
7732         if (++s.strstart <= max_insert) {
7733           /*** INSERT_STRING(s, s.strstart, hash_head); ***/
7734           s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
7735           hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
7736           s.head[s.ins_h] = s.strstart;
7737           /***/
7738         }
7739       } while (--s.prev_length !== 0);
7740       s.match_available = 0;
7741       s.match_length = MIN_MATCH - 1;
7742       s.strstart++;
7743
7744       if (bflush) {
7745         /*** FLUSH_BLOCK(s, 0); ***/
7746         flush_block_only(s, false);
7747         if (s.strm.avail_out === 0) {
7748           return BS_NEED_MORE;
7749         }
7750         /***/
7751       }
7752
7753     } else if (s.match_available) {
7754       /* If there was no match at the previous position, output a
7755        * single literal. If there was a match but the current match
7756        * is longer, truncate the previous match to a single literal.
7757        */
7758       //Tracevv((stderr,"%c", s->window[s->strstart-1]));
7759       /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
7760       bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
7761
7762       if (bflush) {
7763         /*** FLUSH_BLOCK_ONLY(s, 0) ***/
7764         flush_block_only(s, false);
7765         /***/
7766       }
7767       s.strstart++;
7768       s.lookahead--;
7769       if (s.strm.avail_out === 0) {
7770         return BS_NEED_MORE;
7771       }
7772     } else {
7773       /* There is no previous match to compare with, wait for
7774        * the next step to decide.
7775        */
7776       s.match_available = 1;
7777       s.strstart++;
7778       s.lookahead--;
7779     }
7780   }
7781   //Assert (flush != Z_NO_FLUSH, "no flush?");
7782   if (s.match_available) {
7783     //Tracevv((stderr,"%c", s->window[s->strstart-1]));
7784     /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
7785     bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
7786
7787     s.match_available = 0;
7788   }
7789   s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
7790   if (flush === Z_FINISH) {
7791     /*** FLUSH_BLOCK(s, 1); ***/
7792     flush_block_only(s, true);
7793     if (s.strm.avail_out === 0) {
7794       return BS_FINISH_STARTED;
7795     }
7796     /***/
7797     return BS_FINISH_DONE;
7798   }
7799   if (s.last_lit) {
7800     /*** FLUSH_BLOCK(s, 0); ***/
7801     flush_block_only(s, false);
7802     if (s.strm.avail_out === 0) {
7803       return BS_NEED_MORE;
7804     }
7805     /***/
7806   }
7807
7808   return BS_BLOCK_DONE;
7809 }
7810
7811
7812 /* ===========================================================================
7813  * For Z_RLE, simply look for runs of bytes, generate matches only of distance
7814  * one.  Do not maintain a hash table.  (It will be regenerated if this run of
7815  * deflate switches away from Z_RLE.)
7816  */
7817 function deflate_rle(s, flush) {
7818   var bflush;            /* set if current block must be flushed */
7819   var prev;              /* byte at distance one to match */
7820   var scan, strend;      /* scan goes up to strend for length of run */
7821
7822   var _win = s.window;
7823
7824   for (;;) {
7825     /* Make sure that we always have enough lookahead, except
7826      * at the end of the input file. We need MAX_MATCH bytes
7827      * for the longest run, plus one for the unrolled loop.
7828      */
7829     if (s.lookahead <= MAX_MATCH) {
7830       fill_window(s);
7831       if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
7832         return BS_NEED_MORE;
7833       }
7834       if (s.lookahead === 0) { break; } /* flush the current block */
7835     }
7836
7837     /* See how many times the previous byte repeats */
7838     s.match_length = 0;
7839     if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
7840       scan = s.strstart - 1;
7841       prev = _win[scan];
7842       if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
7843         strend = s.strstart + MAX_MATCH;
7844         do {
7845           /*jshint noempty:false*/
7846         } while (prev === _win[++scan] && prev === _win[++scan] &&
7847                  prev === _win[++scan] && prev === _win[++scan] &&
7848                  prev === _win[++scan] && prev === _win[++scan] &&
7849                  prev === _win[++scan] && prev === _win[++scan] &&
7850                  scan < strend);
7851         s.match_length = MAX_MATCH - (strend - scan);
7852         if (s.match_length > s.lookahead) {
7853           s.match_length = s.lookahead;
7854         }
7855       }
7856       //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
7857     }
7858
7859     /* Emit match if have run of MIN_MATCH or longer, else emit literal */
7860     if (s.match_length >= MIN_MATCH) {
7861       //check_match(s, s.strstart, s.strstart - 1, s.match_length);
7862
7863       /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
7864       bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
7865
7866       s.lookahead -= s.match_length;
7867       s.strstart += s.match_length;
7868       s.match_length = 0;
7869     } else {
7870       /* No match, output a literal byte */
7871       //Tracevv((stderr,"%c", s->window[s->strstart]));
7872       /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
7873       bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
7874
7875       s.lookahead--;
7876       s.strstart++;
7877     }
7878     if (bflush) {
7879       /*** FLUSH_BLOCK(s, 0); ***/
7880       flush_block_only(s, false);
7881       if (s.strm.avail_out === 0) {
7882         return BS_NEED_MORE;
7883       }
7884       /***/
7885     }
7886   }
7887   s.insert = 0;
7888   if (flush === Z_FINISH) {
7889     /*** FLUSH_BLOCK(s, 1); ***/
7890     flush_block_only(s, true);
7891     if (s.strm.avail_out === 0) {
7892       return BS_FINISH_STARTED;
7893     }
7894     /***/
7895     return BS_FINISH_DONE;
7896   }
7897   if (s.last_lit) {
7898     /*** FLUSH_BLOCK(s, 0); ***/
7899     flush_block_only(s, false);
7900     if (s.strm.avail_out === 0) {
7901       return BS_NEED_MORE;
7902     }
7903     /***/
7904   }
7905   return BS_BLOCK_DONE;
7906 }
7907
7908 /* ===========================================================================
7909  * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
7910  * (It will be regenerated if this run of deflate switches away from Huffman.)
7911  */
7912 function deflate_huff(s, flush) {
7913   var bflush;             /* set if current block must be flushed */
7914
7915   for (;;) {
7916     /* Make sure that we have a literal to write. */
7917     if (s.lookahead === 0) {
7918       fill_window(s);
7919       if (s.lookahead === 0) {
7920         if (flush === Z_NO_FLUSH) {
7921           return BS_NEED_MORE;
7922         }
7923         break;      /* flush the current block */
7924       }
7925     }
7926
7927     /* Output a literal byte */
7928     s.match_length = 0;
7929     //Tracevv((stderr,"%c", s->window[s->strstart]));
7930     /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
7931     bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
7932     s.lookahead--;
7933     s.strstart++;
7934     if (bflush) {
7935       /*** FLUSH_BLOCK(s, 0); ***/
7936       flush_block_only(s, false);
7937       if (s.strm.avail_out === 0) {
7938         return BS_NEED_MORE;
7939       }
7940       /***/
7941     }
7942   }
7943   s.insert = 0;
7944   if (flush === Z_FINISH) {
7945     /*** FLUSH_BLOCK(s, 1); ***/
7946     flush_block_only(s, true);
7947     if (s.strm.avail_out === 0) {
7948       return BS_FINISH_STARTED;
7949     }
7950     /***/
7951     return BS_FINISH_DONE;
7952   }
7953   if (s.last_lit) {
7954     /*** FLUSH_BLOCK(s, 0); ***/
7955     flush_block_only(s, false);
7956     if (s.strm.avail_out === 0) {
7957       return BS_NEED_MORE;
7958     }
7959     /***/
7960   }
7961   return BS_BLOCK_DONE;
7962 }
7963
7964 /* Values for max_lazy_match, good_match and max_chain_length, depending on
7965  * the desired pack level (0..9). The values given below have been tuned to
7966  * exclude worst case performance for pathological files. Better values may be
7967  * found for specific files.
7968  */
7969 function Config(good_length, max_lazy, nice_length, max_chain, func) {
7970   this.good_length = good_length;
7971   this.max_lazy = max_lazy;
7972   this.nice_length = nice_length;
7973   this.max_chain = max_chain;
7974   this.func = func;
7975 }
7976
7977 var configuration_table;
7978
7979 configuration_table = [
7980   /*      good lazy nice chain */
7981   new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
7982   new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
7983   new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
7984   new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
7985
7986   new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
7987   new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
7988   new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
7989   new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
7990   new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
7991   new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
7992 ];
7993
7994
7995 /* ===========================================================================
7996  * Initialize the "longest match" routines for a new zlib stream
7997  */
7998 function lm_init(s) {
7999   s.window_size = 2 * s.w_size;
8000
8001   /*** CLEAR_HASH(s); ***/
8002   zero(s.head); // Fill with NIL (= 0);
8003
8004   /* Set the default configuration parameters:
8005    */
8006   s.max_lazy_match = configuration_table[s.level].max_lazy;
8007   s.good_match = configuration_table[s.level].good_length;
8008   s.nice_match = configuration_table[s.level].nice_length;
8009   s.max_chain_length = configuration_table[s.level].max_chain;
8010
8011   s.strstart = 0;
8012   s.block_start = 0;
8013   s.lookahead = 0;
8014   s.insert = 0;
8015   s.match_length = s.prev_length = MIN_MATCH - 1;
8016   s.match_available = 0;
8017   s.ins_h = 0;
8018 }
8019
8020
8021 function DeflateState() {
8022   this.strm = null;            /* pointer back to this zlib stream */
8023   this.status = 0;            /* as the name implies */
8024   this.pending_buf = null;      /* output still pending */
8025   this.pending_buf_size = 0;  /* size of pending_buf */
8026   this.pending_out = 0;       /* next pending byte to output to the stream */
8027   this.pending = 0;           /* nb of bytes in the pending buffer */
8028   this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
8029   this.gzhead = null;         /* gzip header information to write */
8030   this.gzindex = 0;           /* where in extra, name, or comment */
8031   this.method = Z_DEFLATED; /* can only be DEFLATED */
8032   this.last_flush = -1;   /* value of flush param for previous deflate call */
8033
8034   this.w_size = 0;  /* LZ77 window size (32K by default) */
8035   this.w_bits = 0;  /* log2(w_size)  (8..16) */
8036   this.w_mask = 0;  /* w_size - 1 */
8037
8038   this.window = null;
8039   /* Sliding window. Input bytes are read into the second half of the window,
8040    * and move to the first half later to keep a dictionary of at least wSize
8041    * bytes. With this organization, matches are limited to a distance of
8042    * wSize-MAX_MATCH bytes, but this ensures that IO is always
8043    * performed with a length multiple of the block size.
8044    */
8045
8046   this.window_size = 0;
8047   /* Actual size of window: 2*wSize, except when the user input buffer
8048    * is directly used as sliding window.
8049    */
8050
8051   this.prev = null;
8052   /* Link to older string with same hash index. To limit the size of this
8053    * array to 64K, this link is maintained only for the last 32K strings.
8054    * An index in this array is thus a window index modulo 32K.
8055    */
8056
8057   this.head = null;   /* Heads of the hash chains or NIL. */
8058
8059   this.ins_h = 0;       /* hash index of string to be inserted */
8060   this.hash_size = 0;   /* number of elements in hash table */
8061   this.hash_bits = 0;   /* log2(hash_size) */
8062   this.hash_mask = 0;   /* hash_size-1 */
8063
8064   this.hash_shift = 0;
8065   /* Number of bits by which ins_h must be shifted at each input
8066    * step. It must be such that after MIN_MATCH steps, the oldest
8067    * byte no longer takes part in the hash key, that is:
8068    *   hash_shift * MIN_MATCH >= hash_bits
8069    */
8070
8071   this.block_start = 0;
8072   /* Window position at the beginning of the current output block. Gets
8073    * negative when the window is moved backwards.
8074    */
8075
8076   this.match_length = 0;      /* length of best match */
8077   this.prev_match = 0;        /* previous match */
8078   this.match_available = 0;   /* set if previous match exists */
8079   this.strstart = 0;          /* start of string to insert */
8080   this.match_start = 0;       /* start of matching string */
8081   this.lookahead = 0;         /* number of valid bytes ahead in window */
8082
8083   this.prev_length = 0;
8084   /* Length of the best match at previous step. Matches not greater than this
8085    * are discarded. This is used in the lazy match evaluation.
8086    */
8087
8088   this.max_chain_length = 0;
8089   /* To speed up deflation, hash chains are never searched beyond this
8090    * length.  A higher limit improves compression ratio but degrades the
8091    * speed.
8092    */
8093
8094   this.max_lazy_match = 0;
8095   /* Attempt to find a better match only when the current match is strictly
8096    * smaller than this value. This mechanism is used only for compression
8097    * levels >= 4.
8098    */
8099   // That's alias to max_lazy_match, don't use directly
8100   //this.max_insert_length = 0;
8101   /* Insert new strings in the hash table only if the match length is not
8102    * greater than this length. This saves time but degrades compression.
8103    * max_insert_length is used only for compression levels <= 3.
8104    */
8105
8106   this.level = 0;     /* compression level (1..9) */
8107   this.strategy = 0;  /* favor or force Huffman coding*/
8108
8109   this.good_match = 0;
8110   /* Use a faster search when the previous match is longer than this */
8111
8112   this.nice_match = 0; /* Stop searching when current match exceeds this */
8113
8114               /* used by trees.c: */
8115
8116   /* Didn't use ct_data typedef below to suppress compiler warning */
8117
8118   // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
8119   // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
8120   // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
8121
8122   // Use flat array of DOUBLE size, with interleaved fata,
8123   // because JS does not support effective
8124   this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
8125   this.dyn_dtree  = new utils.Buf16((2 * D_CODES + 1) * 2);
8126   this.bl_tree    = new utils.Buf16((2 * BL_CODES + 1) * 2);
8127   zero(this.dyn_ltree);
8128   zero(this.dyn_dtree);
8129   zero(this.bl_tree);
8130
8131   this.l_desc   = null;         /* desc. for literal tree */
8132   this.d_desc   = null;         /* desc. for distance tree */
8133   this.bl_desc  = null;         /* desc. for bit length tree */
8134
8135   //ush bl_count[MAX_BITS+1];
8136   this.bl_count = new utils.Buf16(MAX_BITS + 1);
8137   /* number of codes at each bit length for an optimal tree */
8138
8139   //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
8140   this.heap = new utils.Buf16(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
8141   zero(this.heap);
8142
8143   this.heap_len = 0;               /* number of elements in the heap */
8144   this.heap_max = 0;               /* element of largest frequency */
8145   /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
8146    * The same heap array is used to build all trees.
8147    */
8148
8149   this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
8150   zero(this.depth);
8151   /* Depth of each subtree used as tie breaker for trees of equal frequency
8152    */
8153
8154   this.l_buf = 0;          /* buffer index for literals or lengths */
8155
8156   this.lit_bufsize = 0;
8157   /* Size of match buffer for literals/lengths.  There are 4 reasons for
8158    * limiting lit_bufsize to 64K:
8159    *   - frequencies can be kept in 16 bit counters
8160    *   - if compression is not successful for the first block, all input
8161    *     data is still in the window so we can still emit a stored block even
8162    *     when input comes from standard input.  (This can also be done for
8163    *     all blocks if lit_bufsize is not greater than 32K.)
8164    *   - if compression is not successful for a file smaller than 64K, we can
8165    *     even emit a stored file instead of a stored block (saving 5 bytes).
8166    *     This is applicable only for zip (not gzip or zlib).
8167    *   - creating new Huffman trees less frequently may not provide fast
8168    *     adaptation to changes in the input data statistics. (Take for
8169    *     example a binary file with poorly compressible code followed by
8170    *     a highly compressible string table.) Smaller buffer sizes give
8171    *     fast adaptation but have of course the overhead of transmitting
8172    *     trees more frequently.
8173    *   - I can't count above 4
8174    */
8175
8176   this.last_lit = 0;      /* running index in l_buf */
8177
8178   this.d_buf = 0;
8179   /* Buffer index for distances. To simplify the code, d_buf and l_buf have
8180    * the same number of elements. To use different lengths, an extra flag
8181    * array would be necessary.
8182    */
8183
8184   this.opt_len = 0;       /* bit length of current block with optimal trees */
8185   this.static_len = 0;    /* bit length of current block with static trees */
8186   this.matches = 0;       /* number of string matches in current block */
8187   this.insert = 0;        /* bytes at end of window left to insert */
8188
8189
8190   this.bi_buf = 0;
8191   /* Output buffer. bits are inserted starting at the bottom (least
8192    * significant bits).
8193    */
8194   this.bi_valid = 0;
8195   /* Number of valid bits in bi_buf.  All bits above the last valid bit
8196    * are always zero.
8197    */
8198
8199   // Used for window memory init. We safely ignore it for JS. That makes
8200   // sense only for pointers and memory check tools.
8201   //this.high_water = 0;
8202   /* High water mark offset in window for initialized bytes -- bytes above
8203    * this are set to zero in order to avoid memory check warnings when
8204    * longest match routines access bytes past the input.  This is then
8205    * updated to the new high water mark.
8206    */
8207 }
8208
8209
8210 function deflateResetKeep(strm) {
8211   var s;
8212
8213   if (!strm || !strm.state) {
8214     return err(strm, Z_STREAM_ERROR);
8215   }
8216
8217   strm.total_in = strm.total_out = 0;
8218   strm.data_type = Z_UNKNOWN;
8219
8220   s = strm.state;
8221   s.pending = 0;
8222   s.pending_out = 0;
8223
8224   if (s.wrap < 0) {
8225     s.wrap = -s.wrap;
8226     /* was made negative by deflate(..., Z_FINISH); */
8227   }
8228   s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
8229   strm.adler = (s.wrap === 2) ?
8230     0  // crc32(0, Z_NULL, 0)
8231   :
8232     1; // adler32(0, Z_NULL, 0)
8233   s.last_flush = Z_NO_FLUSH;
8234   trees._tr_init(s);
8235   return Z_OK;
8236 }
8237
8238
8239 function deflateReset(strm) {
8240   var ret = deflateResetKeep(strm);
8241   if (ret === Z_OK) {
8242     lm_init(strm.state);
8243   }
8244   return ret;
8245 }
8246
8247
8248 function deflateSetHeader(strm, head) {
8249   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8250   if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
8251   strm.state.gzhead = head;
8252   return Z_OK;
8253 }
8254
8255
8256 function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
8257   if (!strm) { // === Z_NULL
8258     return Z_STREAM_ERROR;
8259   }
8260   var wrap = 1;
8261
8262   if (level === Z_DEFAULT_COMPRESSION) {
8263     level = 6;
8264   }
8265
8266   if (windowBits < 0) { /* suppress zlib wrapper */
8267     wrap = 0;
8268     windowBits = -windowBits;
8269   }
8270
8271   else if (windowBits > 15) {
8272     wrap = 2;           /* write gzip wrapper instead */
8273     windowBits -= 16;
8274   }
8275
8276
8277   if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
8278     windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
8279     strategy < 0 || strategy > Z_FIXED) {
8280     return err(strm, Z_STREAM_ERROR);
8281   }
8282
8283
8284   if (windowBits === 8) {
8285     windowBits = 9;
8286   }
8287   /* until 256-byte window bug fixed */
8288
8289   var s = new DeflateState();
8290
8291   strm.state = s;
8292   s.strm = strm;
8293
8294   s.wrap = wrap;
8295   s.gzhead = null;
8296   s.w_bits = windowBits;
8297   s.w_size = 1 << s.w_bits;
8298   s.w_mask = s.w_size - 1;
8299
8300   s.hash_bits = memLevel + 7;
8301   s.hash_size = 1 << s.hash_bits;
8302   s.hash_mask = s.hash_size - 1;
8303   s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
8304
8305   s.window = new utils.Buf8(s.w_size * 2);
8306   s.head = new utils.Buf16(s.hash_size);
8307   s.prev = new utils.Buf16(s.w_size);
8308
8309   // Don't need mem init magic for JS.
8310   //s.high_water = 0;  /* nothing written to s->window yet */
8311
8312   s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
8313
8314   s.pending_buf_size = s.lit_bufsize * 4;
8315
8316   //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
8317   //s->pending_buf = (uchf *) overlay;
8318   s.pending_buf = new utils.Buf8(s.pending_buf_size);
8319
8320   // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
8321   //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
8322   s.d_buf = 1 * s.lit_bufsize;
8323
8324   //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
8325   s.l_buf = (1 + 2) * s.lit_bufsize;
8326
8327   s.level = level;
8328   s.strategy = strategy;
8329   s.method = method;
8330
8331   return deflateReset(strm);
8332 }
8333
8334 function deflateInit(strm, level) {
8335   return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
8336 }
8337
8338
8339 function deflate(strm, flush) {
8340   var old_flush, s;
8341   var beg, val; // for gzip header write only
8342
8343   if (!strm || !strm.state ||
8344     flush > Z_BLOCK || flush < 0) {
8345     return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
8346   }
8347
8348   s = strm.state;
8349
8350   if (!strm.output ||
8351       (!strm.input && strm.avail_in !== 0) ||
8352       (s.status === FINISH_STATE && flush !== Z_FINISH)) {
8353     return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
8354   }
8355
8356   s.strm = strm; /* just in case */
8357   old_flush = s.last_flush;
8358   s.last_flush = flush;
8359
8360   /* Write the header */
8361   if (s.status === INIT_STATE) {
8362
8363     if (s.wrap === 2) { // GZIP header
8364       strm.adler = 0;  //crc32(0L, Z_NULL, 0);
8365       put_byte(s, 31);
8366       put_byte(s, 139);
8367       put_byte(s, 8);
8368       if (!s.gzhead) { // s->gzhead == Z_NULL
8369         put_byte(s, 0);
8370         put_byte(s, 0);
8371         put_byte(s, 0);
8372         put_byte(s, 0);
8373         put_byte(s, 0);
8374         put_byte(s, s.level === 9 ? 2 :
8375                     (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
8376                      4 : 0));
8377         put_byte(s, OS_CODE);
8378         s.status = BUSY_STATE;
8379       }
8380       else {
8381         put_byte(s, (s.gzhead.text ? 1 : 0) +
8382                     (s.gzhead.hcrc ? 2 : 0) +
8383                     (!s.gzhead.extra ? 0 : 4) +
8384                     (!s.gzhead.name ? 0 : 8) +
8385                     (!s.gzhead.comment ? 0 : 16)
8386         );
8387         put_byte(s, s.gzhead.time & 0xff);
8388         put_byte(s, (s.gzhead.time >> 8) & 0xff);
8389         put_byte(s, (s.gzhead.time >> 16) & 0xff);
8390         put_byte(s, (s.gzhead.time >> 24) & 0xff);
8391         put_byte(s, s.level === 9 ? 2 :
8392                     (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
8393                      4 : 0));
8394         put_byte(s, s.gzhead.os & 0xff);
8395         if (s.gzhead.extra && s.gzhead.extra.length) {
8396           put_byte(s, s.gzhead.extra.length & 0xff);
8397           put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
8398         }
8399         if (s.gzhead.hcrc) {
8400           strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
8401         }
8402         s.gzindex = 0;
8403         s.status = EXTRA_STATE;
8404       }
8405     }
8406     else // DEFLATE header
8407     {
8408       var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
8409       var level_flags = -1;
8410
8411       if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
8412         level_flags = 0;
8413       } else if (s.level < 6) {
8414         level_flags = 1;
8415       } else if (s.level === 6) {
8416         level_flags = 2;
8417       } else {
8418         level_flags = 3;
8419       }
8420       header |= (level_flags << 6);
8421       if (s.strstart !== 0) { header |= PRESET_DICT; }
8422       header += 31 - (header % 31);
8423
8424       s.status = BUSY_STATE;
8425       putShortMSB(s, header);
8426
8427       /* Save the adler32 of the preset dictionary: */
8428       if (s.strstart !== 0) {
8429         putShortMSB(s, strm.adler >>> 16);
8430         putShortMSB(s, strm.adler & 0xffff);
8431       }
8432       strm.adler = 1; // adler32(0L, Z_NULL, 0);
8433     }
8434   }
8435
8436 //#ifdef GZIP
8437   if (s.status === EXTRA_STATE) {
8438     if (s.gzhead.extra/* != Z_NULL*/) {
8439       beg = s.pending;  /* start of bytes to update crc */
8440
8441       while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
8442         if (s.pending === s.pending_buf_size) {
8443           if (s.gzhead.hcrc && s.pending > beg) {
8444             strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
8445           }
8446           flush_pending(strm);
8447           beg = s.pending;
8448           if (s.pending === s.pending_buf_size) {
8449             break;
8450           }
8451         }
8452         put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
8453         s.gzindex++;
8454       }
8455       if (s.gzhead.hcrc && s.pending > beg) {
8456         strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
8457       }
8458       if (s.gzindex === s.gzhead.extra.length) {
8459         s.gzindex = 0;
8460         s.status = NAME_STATE;
8461       }
8462     }
8463     else {
8464       s.status = NAME_STATE;
8465     }
8466   }
8467   if (s.status === NAME_STATE) {
8468     if (s.gzhead.name/* != Z_NULL*/) {
8469       beg = s.pending;  /* start of bytes to update crc */
8470       //int val;
8471
8472       do {
8473         if (s.pending === s.pending_buf_size) {
8474           if (s.gzhead.hcrc && s.pending > beg) {
8475             strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
8476           }
8477           flush_pending(strm);
8478           beg = s.pending;
8479           if (s.pending === s.pending_buf_size) {
8480             val = 1;
8481             break;
8482           }
8483         }
8484         // JS specific: little magic to add zero terminator to end of string
8485         if (s.gzindex < s.gzhead.name.length) {
8486           val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
8487         } else {
8488           val = 0;
8489         }
8490         put_byte(s, val);
8491       } while (val !== 0);
8492
8493       if (s.gzhead.hcrc && s.pending > beg) {
8494         strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
8495       }
8496       if (val === 0) {
8497         s.gzindex = 0;
8498         s.status = COMMENT_STATE;
8499       }
8500     }
8501     else {
8502       s.status = COMMENT_STATE;
8503     }
8504   }
8505   if (s.status === COMMENT_STATE) {
8506     if (s.gzhead.comment/* != Z_NULL*/) {
8507       beg = s.pending;  /* start of bytes to update crc */
8508       //int val;
8509
8510       do {
8511         if (s.pending === s.pending_buf_size) {
8512           if (s.gzhead.hcrc && s.pending > beg) {
8513             strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
8514           }
8515           flush_pending(strm);
8516           beg = s.pending;
8517           if (s.pending === s.pending_buf_size) {
8518             val = 1;
8519             break;
8520           }
8521         }
8522         // JS specific: little magic to add zero terminator to end of string
8523         if (s.gzindex < s.gzhead.comment.length) {
8524           val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
8525         } else {
8526           val = 0;
8527         }
8528         put_byte(s, val);
8529       } while (val !== 0);
8530
8531       if (s.gzhead.hcrc && s.pending > beg) {
8532         strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
8533       }
8534       if (val === 0) {
8535         s.status = HCRC_STATE;
8536       }
8537     }
8538     else {
8539       s.status = HCRC_STATE;
8540     }
8541   }
8542   if (s.status === HCRC_STATE) {
8543     if (s.gzhead.hcrc) {
8544       if (s.pending + 2 > s.pending_buf_size) {
8545         flush_pending(strm);
8546       }
8547       if (s.pending + 2 <= s.pending_buf_size) {
8548         put_byte(s, strm.adler & 0xff);
8549         put_byte(s, (strm.adler >> 8) & 0xff);
8550         strm.adler = 0; //crc32(0L, Z_NULL, 0);
8551         s.status = BUSY_STATE;
8552       }
8553     }
8554     else {
8555       s.status = BUSY_STATE;
8556     }
8557   }
8558 //#endif
8559
8560   /* Flush as much pending output as possible */
8561   if (s.pending !== 0) {
8562     flush_pending(strm);
8563     if (strm.avail_out === 0) {
8564       /* Since avail_out is 0, deflate will be called again with
8565        * more output space, but possibly with both pending and
8566        * avail_in equal to zero. There won't be anything to do,
8567        * but this is not an error situation so make sure we
8568        * return OK instead of BUF_ERROR at next call of deflate:
8569        */
8570       s.last_flush = -1;
8571       return Z_OK;
8572     }
8573
8574     /* Make sure there is something to do and avoid duplicate consecutive
8575      * flushes. For repeated and useless calls with Z_FINISH, we keep
8576      * returning Z_STREAM_END instead of Z_BUF_ERROR.
8577      */
8578   } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
8579     flush !== Z_FINISH) {
8580     return err(strm, Z_BUF_ERROR);
8581   }
8582
8583   /* User must not provide more input after the first FINISH: */
8584   if (s.status === FINISH_STATE && strm.avail_in !== 0) {
8585     return err(strm, Z_BUF_ERROR);
8586   }
8587
8588   /* Start a new block or continue the current one.
8589    */
8590   if (strm.avail_in !== 0 || s.lookahead !== 0 ||
8591     (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
8592     var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
8593       (s.strategy === Z_RLE ? deflate_rle(s, flush) :
8594         configuration_table[s.level].func(s, flush));
8595
8596     if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
8597       s.status = FINISH_STATE;
8598     }
8599     if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
8600       if (strm.avail_out === 0) {
8601         s.last_flush = -1;
8602         /* avoid BUF_ERROR next call, see above */
8603       }
8604       return Z_OK;
8605       /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
8606        * of deflate should use the same flush parameter to make sure
8607        * that the flush is complete. So we don't have to output an
8608        * empty block here, this will be done at next call. This also
8609        * ensures that for a very small output buffer, we emit at most
8610        * one empty block.
8611        */
8612     }
8613     if (bstate === BS_BLOCK_DONE) {
8614       if (flush === Z_PARTIAL_FLUSH) {
8615         trees._tr_align(s);
8616       }
8617       else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
8618
8619         trees._tr_stored_block(s, 0, 0, false);
8620         /* For a full flush, this empty block will be recognized
8621          * as a special marker by inflate_sync().
8622          */
8623         if (flush === Z_FULL_FLUSH) {
8624           /*** CLEAR_HASH(s); ***/             /* forget history */
8625           zero(s.head); // Fill with NIL (= 0);
8626
8627           if (s.lookahead === 0) {
8628             s.strstart = 0;
8629             s.block_start = 0;
8630             s.insert = 0;
8631           }
8632         }
8633       }
8634       flush_pending(strm);
8635       if (strm.avail_out === 0) {
8636         s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
8637         return Z_OK;
8638       }
8639     }
8640   }
8641   //Assert(strm->avail_out > 0, "bug2");
8642   //if (strm.avail_out <= 0) { throw new Error("bug2");}
8643
8644   if (flush !== Z_FINISH) { return Z_OK; }
8645   if (s.wrap <= 0) { return Z_STREAM_END; }
8646
8647   /* Write the trailer */
8648   if (s.wrap === 2) {
8649     put_byte(s, strm.adler & 0xff);
8650     put_byte(s, (strm.adler >> 8) & 0xff);
8651     put_byte(s, (strm.adler >> 16) & 0xff);
8652     put_byte(s, (strm.adler >> 24) & 0xff);
8653     put_byte(s, strm.total_in & 0xff);
8654     put_byte(s, (strm.total_in >> 8) & 0xff);
8655     put_byte(s, (strm.total_in >> 16) & 0xff);
8656     put_byte(s, (strm.total_in >> 24) & 0xff);
8657   }
8658   else
8659   {
8660     putShortMSB(s, strm.adler >>> 16);
8661     putShortMSB(s, strm.adler & 0xffff);
8662   }
8663
8664   flush_pending(strm);
8665   /* If avail_out is zero, the application will call deflate again
8666    * to flush the rest.
8667    */
8668   if (s.wrap > 0) { s.wrap = -s.wrap; }
8669   /* write the trailer only once! */
8670   return s.pending !== 0 ? Z_OK : Z_STREAM_END;
8671 }
8672
8673 function deflateEnd(strm) {
8674   var status;
8675
8676   if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
8677     return Z_STREAM_ERROR;
8678   }
8679
8680   status = strm.state.status;
8681   if (status !== INIT_STATE &&
8682     status !== EXTRA_STATE &&
8683     status !== NAME_STATE &&
8684     status !== COMMENT_STATE &&
8685     status !== HCRC_STATE &&
8686     status !== BUSY_STATE &&
8687     status !== FINISH_STATE
8688   ) {
8689     return err(strm, Z_STREAM_ERROR);
8690   }
8691
8692   strm.state = null;
8693
8694   return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
8695 }
8696
8697
8698 /* =========================================================================
8699  * Initializes the compression dictionary from the given byte
8700  * sequence without producing any compressed output.
8701  */
8702 function deflateSetDictionary(strm, dictionary) {
8703   var dictLength = dictionary.length;
8704
8705   var s;
8706   var str, n;
8707   var wrap;
8708   var avail;
8709   var next;
8710   var input;
8711   var tmpDict;
8712
8713   if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
8714     return Z_STREAM_ERROR;
8715   }
8716
8717   s = strm.state;
8718   wrap = s.wrap;
8719
8720   if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
8721     return Z_STREAM_ERROR;
8722   }
8723
8724   /* when using zlib wrappers, compute Adler-32 for provided dictionary */
8725   if (wrap === 1) {
8726     /* adler32(strm->adler, dictionary, dictLength); */
8727     strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
8728   }
8729
8730   s.wrap = 0;   /* avoid computing Adler-32 in read_buf */
8731
8732   /* if dictionary would fill window, just replace the history */
8733   if (dictLength >= s.w_size) {
8734     if (wrap === 0) {            /* already empty otherwise */
8735       /*** CLEAR_HASH(s); ***/
8736       zero(s.head); // Fill with NIL (= 0);
8737       s.strstart = 0;
8738       s.block_start = 0;
8739       s.insert = 0;
8740     }
8741     /* use the tail */
8742     // dictionary = dictionary.slice(dictLength - s.w_size);
8743     tmpDict = new utils.Buf8(s.w_size);
8744     utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
8745     dictionary = tmpDict;
8746     dictLength = s.w_size;
8747   }
8748   /* insert dictionary into window and hash */
8749   avail = strm.avail_in;
8750   next = strm.next_in;
8751   input = strm.input;
8752   strm.avail_in = dictLength;
8753   strm.next_in = 0;
8754   strm.input = dictionary;
8755   fill_window(s);
8756   while (s.lookahead >= MIN_MATCH) {
8757     str = s.strstart;
8758     n = s.lookahead - (MIN_MATCH - 1);
8759     do {
8760       /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
8761       s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
8762
8763       s.prev[str & s.w_mask] = s.head[s.ins_h];
8764
8765       s.head[s.ins_h] = str;
8766       str++;
8767     } while (--n);
8768     s.strstart = str;
8769     s.lookahead = MIN_MATCH - 1;
8770     fill_window(s);
8771   }
8772   s.strstart += s.lookahead;
8773   s.block_start = s.strstart;
8774   s.insert = s.lookahead;
8775   s.lookahead = 0;
8776   s.match_length = s.prev_length = MIN_MATCH - 1;
8777   s.match_available = 0;
8778   strm.next_in = next;
8779   strm.input = input;
8780   strm.avail_in = avail;
8781   s.wrap = wrap;
8782   return Z_OK;
8783 }
8784
8785
8786 exports.deflateInit = deflateInit;
8787 exports.deflateInit2 = deflateInit2;
8788 exports.deflateReset = deflateReset;
8789 exports.deflateResetKeep = deflateResetKeep;
8790 exports.deflateSetHeader = deflateSetHeader;
8791 exports.deflate = deflate;
8792 exports.deflateEnd = deflateEnd;
8793 exports.deflateSetDictionary = deflateSetDictionary;
8794 exports.deflateInfo = 'pako deflate (from Nodeca project)';
8795
8796 /* Not implemented
8797 exports.deflateBound = deflateBound;
8798 exports.deflateCopy = deflateCopy;
8799 exports.deflateParams = deflateParams;
8800 exports.deflatePending = deflatePending;
8801 exports.deflatePrime = deflatePrime;
8802 exports.deflateTune = deflateTune;
8803 */
8804
8805 },{"../utils/common":26,"./adler32":28,"./crc32":30,"./messages":36,"./trees":37}],32:[function(require,module,exports){
8806 'use strict';
8807
8808 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
8809 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
8810 //
8811 // This software is provided 'as-is', without any express or implied
8812 // warranty. In no event will the authors be held liable for any damages
8813 // arising from the use of this software.
8814 //
8815 // Permission is granted to anyone to use this software for any purpose,
8816 // including commercial applications, and to alter it and redistribute it
8817 // freely, subject to the following restrictions:
8818 //
8819 // 1. The origin of this software must not be misrepresented; you must not
8820 //   claim that you wrote the original software. If you use this software
8821 //   in a product, an acknowledgment in the product documentation would be
8822 //   appreciated but is not required.
8823 // 2. Altered source versions must be plainly marked as such, and must not be
8824 //   misrepresented as being the original software.
8825 // 3. This notice may not be removed or altered from any source distribution.
8826
8827 function GZheader() {
8828   /* true if compressed data believed to be text */
8829   this.text       = 0;
8830   /* modification time */
8831   this.time       = 0;
8832   /* extra flags (not used when writing a gzip file) */
8833   this.xflags     = 0;
8834   /* operating system */
8835   this.os         = 0;
8836   /* pointer to extra field or Z_NULL if none */
8837   this.extra      = null;
8838   /* extra field length (valid if extra != Z_NULL) */
8839   this.extra_len  = 0; // Actually, we don't need it in JS,
8840                        // but leave for few code modifications
8841
8842   //
8843   // Setup limits is not necessary because in js we should not preallocate memory
8844   // for inflate use constant limit in 65536 bytes
8845   //
8846
8847   /* space at extra (only when reading header) */
8848   // this.extra_max  = 0;
8849   /* pointer to zero-terminated file name or Z_NULL */
8850   this.name       = '';
8851   /* space at name (only when reading header) */
8852   // this.name_max   = 0;
8853   /* pointer to zero-terminated comment or Z_NULL */
8854   this.comment    = '';
8855   /* space at comment (only when reading header) */
8856   // this.comm_max   = 0;
8857   /* true if there was or will be a header crc */
8858   this.hcrc       = 0;
8859   /* true when done reading gzip header (not used when writing a gzip file) */
8860   this.done       = false;
8861 }
8862
8863 module.exports = GZheader;
8864
8865 },{}],33:[function(require,module,exports){
8866 'use strict';
8867
8868 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
8869 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
8870 //
8871 // This software is provided 'as-is', without any express or implied
8872 // warranty. In no event will the authors be held liable for any damages
8873 // arising from the use of this software.
8874 //
8875 // Permission is granted to anyone to use this software for any purpose,
8876 // including commercial applications, and to alter it and redistribute it
8877 // freely, subject to the following restrictions:
8878 //
8879 // 1. The origin of this software must not be misrepresented; you must not
8880 //   claim that you wrote the original software. If you use this software
8881 //   in a product, an acknowledgment in the product documentation would be
8882 //   appreciated but is not required.
8883 // 2. Altered source versions must be plainly marked as such, and must not be
8884 //   misrepresented as being the original software.
8885 // 3. This notice may not be removed or altered from any source distribution.
8886
8887 // See state defs from inflate.js
8888 var BAD = 30;       /* got a data error -- remain here until reset */
8889 var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
8890
8891 /*
8892    Decode literal, length, and distance codes and write out the resulting
8893    literal and match bytes until either not enough input or output is
8894    available, an end-of-block is encountered, or a data error is encountered.
8895    When large enough input and output buffers are supplied to inflate(), for
8896    example, a 16K input buffer and a 64K output buffer, more than 95% of the
8897    inflate execution time is spent in this routine.
8898
8899    Entry assumptions:
8900
8901         state.mode === LEN
8902         strm.avail_in >= 6
8903         strm.avail_out >= 258
8904         start >= strm.avail_out
8905         state.bits < 8
8906
8907    On return, state.mode is one of:
8908
8909         LEN -- ran out of enough output space or enough available input
8910         TYPE -- reached end of block code, inflate() to interpret next block
8911         BAD -- error in block data
8912
8913    Notes:
8914
8915     - The maximum input bits used by a length/distance pair is 15 bits for the
8916       length code, 5 bits for the length extra, 15 bits for the distance code,
8917       and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
8918       Therefore if strm.avail_in >= 6, then there is enough input to avoid
8919       checking for available input while decoding.
8920
8921     - The maximum bytes that a single length/distance pair can output is 258
8922       bytes, which is the maximum length that can be coded.  inflate_fast()
8923       requires strm.avail_out >= 258 for each loop to avoid checking for
8924       output space.
8925  */
8926 module.exports = function inflate_fast(strm, start) {
8927   var state;
8928   var _in;                    /* local strm.input */
8929   var last;                   /* have enough input while in < last */
8930   var _out;                   /* local strm.output */
8931   var beg;                    /* inflate()'s initial strm.output */
8932   var end;                    /* while out < end, enough space available */
8933 //#ifdef INFLATE_STRICT
8934   var dmax;                   /* maximum distance from zlib header */
8935 //#endif
8936   var wsize;                  /* window size or zero if not using window */
8937   var whave;                  /* valid bytes in the window */
8938   var wnext;                  /* window write index */
8939   // Use `s_window` instead `window`, avoid conflict with instrumentation tools
8940   var s_window;               /* allocated sliding window, if wsize != 0 */
8941   var hold;                   /* local strm.hold */
8942   var bits;                   /* local strm.bits */
8943   var lcode;                  /* local strm.lencode */
8944   var dcode;                  /* local strm.distcode */
8945   var lmask;                  /* mask for first level of length codes */
8946   var dmask;                  /* mask for first level of distance codes */
8947   var here;                   /* retrieved table entry */
8948   var op;                     /* code bits, operation, extra bits, or */
8949                               /*  window position, window bytes to copy */
8950   var len;                    /* match length, unused bytes */
8951   var dist;                   /* match distance */
8952   var from;                   /* where to copy match from */
8953   var from_source;
8954
8955
8956   var input, output; // JS specific, because we have no pointers
8957
8958   /* copy state to local variables */
8959   state = strm.state;
8960   //here = state.here;
8961   _in = strm.next_in;
8962   input = strm.input;
8963   last = _in + (strm.avail_in - 5);
8964   _out = strm.next_out;
8965   output = strm.output;
8966   beg = _out - (start - strm.avail_out);
8967   end = _out + (strm.avail_out - 257);
8968 //#ifdef INFLATE_STRICT
8969   dmax = state.dmax;
8970 //#endif
8971   wsize = state.wsize;
8972   whave = state.whave;
8973   wnext = state.wnext;
8974   s_window = state.window;
8975   hold = state.hold;
8976   bits = state.bits;
8977   lcode = state.lencode;
8978   dcode = state.distcode;
8979   lmask = (1 << state.lenbits) - 1;
8980   dmask = (1 << state.distbits) - 1;
8981
8982
8983   /* decode literals and length/distances until end-of-block or not enough
8984      input data or output space */
8985
8986   top:
8987   do {
8988     if (bits < 15) {
8989       hold += input[_in++] << bits;
8990       bits += 8;
8991       hold += input[_in++] << bits;
8992       bits += 8;
8993     }
8994
8995     here = lcode[hold & lmask];
8996
8997     dolen:
8998     for (;;) { // Goto emulation
8999       op = here >>> 24/*here.bits*/;
9000       hold >>>= op;
9001       bits -= op;
9002       op = (here >>> 16) & 0xff/*here.op*/;
9003       if (op === 0) {                          /* literal */
9004         //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
9005         //        "inflate:         literal '%c'\n" :
9006         //        "inflate:         literal 0x%02x\n", here.val));
9007         output[_out++] = here & 0xffff/*here.val*/;
9008       }
9009       else if (op & 16) {                     /* length base */
9010         len = here & 0xffff/*here.val*/;
9011         op &= 15;                           /* number of extra bits */
9012         if (op) {
9013           if (bits < op) {
9014             hold += input[_in++] << bits;
9015             bits += 8;
9016           }
9017           len += hold & ((1 << op) - 1);
9018           hold >>>= op;
9019           bits -= op;
9020         }
9021         //Tracevv((stderr, "inflate:         length %u\n", len));
9022         if (bits < 15) {
9023           hold += input[_in++] << bits;
9024           bits += 8;
9025           hold += input[_in++] << bits;
9026           bits += 8;
9027         }
9028         here = dcode[hold & dmask];
9029
9030         dodist:
9031         for (;;) { // goto emulation
9032           op = here >>> 24/*here.bits*/;
9033           hold >>>= op;
9034           bits -= op;
9035           op = (here >>> 16) & 0xff/*here.op*/;
9036
9037           if (op & 16) {                      /* distance base */
9038             dist = here & 0xffff/*here.val*/;
9039             op &= 15;                       /* number of extra bits */
9040             if (bits < op) {
9041               hold += input[_in++] << bits;
9042               bits += 8;
9043               if (bits < op) {
9044                 hold += input[_in++] << bits;
9045                 bits += 8;
9046               }
9047             }
9048             dist += hold & ((1 << op) - 1);
9049 //#ifdef INFLATE_STRICT
9050             if (dist > dmax) {
9051               strm.msg = 'invalid distance too far back';
9052               state.mode = BAD;
9053               break top;
9054             }
9055 //#endif
9056             hold >>>= op;
9057             bits -= op;
9058             //Tracevv((stderr, "inflate:         distance %u\n", dist));
9059             op = _out - beg;                /* max distance in output */
9060             if (dist > op) {                /* see if copy from window */
9061               op = dist - op;               /* distance back in window */
9062               if (op > whave) {
9063                 if (state.sane) {
9064                   strm.msg = 'invalid distance too far back';
9065                   state.mode = BAD;
9066                   break top;
9067                 }
9068
9069 // (!) This block is disabled in zlib defaults,
9070 // don't enable it for binary compatibility
9071 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
9072 //                if (len <= op - whave) {
9073 //                  do {
9074 //                    output[_out++] = 0;
9075 //                  } while (--len);
9076 //                  continue top;
9077 //                }
9078 //                len -= op - whave;
9079 //                do {
9080 //                  output[_out++] = 0;
9081 //                } while (--op > whave);
9082 //                if (op === 0) {
9083 //                  from = _out - dist;
9084 //                  do {
9085 //                    output[_out++] = output[from++];
9086 //                  } while (--len);
9087 //                  continue top;
9088 //                }
9089 //#endif
9090               }
9091               from = 0; // window index
9092               from_source = s_window;
9093               if (wnext === 0) {           /* very common case */
9094                 from += wsize - op;
9095                 if (op < len) {         /* some from window */
9096                   len -= op;
9097                   do {
9098                     output[_out++] = s_window[from++];
9099                   } while (--op);
9100                   from = _out - dist;  /* rest from output */
9101                   from_source = output;
9102                 }
9103               }
9104               else if (wnext < op) {      /* wrap around window */
9105                 from += wsize + wnext - op;
9106                 op -= wnext;
9107                 if (op < len) {         /* some from end of window */
9108                   len -= op;
9109                   do {
9110                     output[_out++] = s_window[from++];
9111                   } while (--op);
9112                   from = 0;
9113                   if (wnext < len) {  /* some from start of window */
9114                     op = wnext;
9115                     len -= op;
9116                     do {
9117                       output[_out++] = s_window[from++];
9118                     } while (--op);
9119                     from = _out - dist;      /* rest from output */
9120                     from_source = output;
9121                   }
9122                 }
9123               }
9124               else {                      /* contiguous in window */
9125                 from += wnext - op;
9126                 if (op < len) {         /* some from window */
9127                   len -= op;
9128                   do {
9129                     output[_out++] = s_window[from++];
9130                   } while (--op);
9131                   from = _out - dist;  /* rest from output */
9132                   from_source = output;
9133                 }
9134               }
9135               while (len > 2) {
9136                 output[_out++] = from_source[from++];
9137                 output[_out++] = from_source[from++];
9138                 output[_out++] = from_source[from++];
9139                 len -= 3;
9140               }
9141               if (len) {
9142                 output[_out++] = from_source[from++];
9143                 if (len > 1) {
9144                   output[_out++] = from_source[from++];
9145                 }
9146               }
9147             }
9148             else {
9149               from = _out - dist;          /* copy direct from output */
9150               do {                        /* minimum length is three */
9151                 output[_out++] = output[from++];
9152                 output[_out++] = output[from++];
9153                 output[_out++] = output[from++];
9154                 len -= 3;
9155               } while (len > 2);
9156               if (len) {
9157                 output[_out++] = output[from++];
9158                 if (len > 1) {
9159                   output[_out++] = output[from++];
9160                 }
9161               }
9162             }
9163           }
9164           else if ((op & 64) === 0) {          /* 2nd level distance code */
9165             here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
9166             continue dodist;
9167           }
9168           else {
9169             strm.msg = 'invalid distance code';
9170             state.mode = BAD;
9171             break top;
9172           }
9173
9174           break; // need to emulate goto via "continue"
9175         }
9176       }
9177       else if ((op & 64) === 0) {              /* 2nd level length code */
9178         here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
9179         continue dolen;
9180       }
9181       else if (op & 32) {                     /* end-of-block */
9182         //Tracevv((stderr, "inflate:         end of block\n"));
9183         state.mode = TYPE;
9184         break top;
9185       }
9186       else {
9187         strm.msg = 'invalid literal/length code';
9188         state.mode = BAD;
9189         break top;
9190       }
9191
9192       break; // need to emulate goto via "continue"
9193     }
9194   } while (_in < last && _out < end);
9195
9196   /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
9197   len = bits >> 3;
9198   _in -= len;
9199   bits -= len << 3;
9200   hold &= (1 << bits) - 1;
9201
9202   /* update state and return */
9203   strm.next_in = _in;
9204   strm.next_out = _out;
9205   strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
9206   strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
9207   state.hold = hold;
9208   state.bits = bits;
9209   return;
9210 };
9211
9212 },{}],34:[function(require,module,exports){
9213 'use strict';
9214
9215 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
9216 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
9217 //
9218 // This software is provided 'as-is', without any express or implied
9219 // warranty. In no event will the authors be held liable for any damages
9220 // arising from the use of this software.
9221 //
9222 // Permission is granted to anyone to use this software for any purpose,
9223 // including commercial applications, and to alter it and redistribute it
9224 // freely, subject to the following restrictions:
9225 //
9226 // 1. The origin of this software must not be misrepresented; you must not
9227 //   claim that you wrote the original software. If you use this software
9228 //   in a product, an acknowledgment in the product documentation would be
9229 //   appreciated but is not required.
9230 // 2. Altered source versions must be plainly marked as such, and must not be
9231 //   misrepresented as being the original software.
9232 // 3. This notice may not be removed or altered from any source distribution.
9233
9234 var utils         = require('../utils/common');
9235 var adler32       = require('./adler32');
9236 var crc32         = require('./crc32');
9237 var inflate_fast  = require('./inffast');
9238 var inflate_table = require('./inftrees');
9239
9240 var CODES = 0;
9241 var LENS = 1;
9242 var DISTS = 2;
9243
9244 /* Public constants ==========================================================*/
9245 /* ===========================================================================*/
9246
9247
9248 /* Allowed flush values; see deflate() and inflate() below for details */
9249 //var Z_NO_FLUSH      = 0;
9250 //var Z_PARTIAL_FLUSH = 1;
9251 //var Z_SYNC_FLUSH    = 2;
9252 //var Z_FULL_FLUSH    = 3;
9253 var Z_FINISH        = 4;
9254 var Z_BLOCK         = 5;
9255 var Z_TREES         = 6;
9256
9257
9258 /* Return codes for the compression/decompression functions. Negative values
9259  * are errors, positive values are used for special but normal events.
9260  */
9261 var Z_OK            = 0;
9262 var Z_STREAM_END    = 1;
9263 var Z_NEED_DICT     = 2;
9264 //var Z_ERRNO         = -1;
9265 var Z_STREAM_ERROR  = -2;
9266 var Z_DATA_ERROR    = -3;
9267 var Z_MEM_ERROR     = -4;
9268 var Z_BUF_ERROR     = -5;
9269 //var Z_VERSION_ERROR = -6;
9270
9271 /* The deflate compression method */
9272 var Z_DEFLATED  = 8;
9273
9274
9275 /* STATES ====================================================================*/
9276 /* ===========================================================================*/
9277
9278
9279 var    HEAD = 1;       /* i: waiting for magic header */
9280 var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
9281 var    TIME = 3;       /* i: waiting for modification time (gzip) */
9282 var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
9283 var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
9284 var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
9285 var    NAME = 7;       /* i: waiting for end of file name (gzip) */
9286 var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
9287 var    HCRC = 9;       /* i: waiting for header crc (gzip) */
9288 var    DICTID = 10;    /* i: waiting for dictionary check value */
9289 var    DICT = 11;      /* waiting for inflateSetDictionary() call */
9290 var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
9291 var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
9292 var        STORED = 14;    /* i: waiting for stored size (length and complement) */
9293 var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
9294 var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
9295 var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
9296 var        LENLENS = 18;   /* i: waiting for code length code lengths */
9297 var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
9298 var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
9299 var            LEN = 21;       /* i: waiting for length/lit/eob code */
9300 var            LENEXT = 22;    /* i: waiting for length extra bits */
9301 var            DIST = 23;      /* i: waiting for distance code */
9302 var            DISTEXT = 24;   /* i: waiting for distance extra bits */
9303 var            MATCH = 25;     /* o: waiting for output space to copy string */
9304 var            LIT = 26;       /* o: waiting for output space to write literal */
9305 var    CHECK = 27;     /* i: waiting for 32-bit check value */
9306 var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
9307 var    DONE = 29;      /* finished check, done -- remain here until reset */
9308 var    BAD = 30;       /* got a data error -- remain here until reset */
9309 var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
9310 var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */
9311
9312 /* ===========================================================================*/
9313
9314
9315
9316 var ENOUGH_LENS = 852;
9317 var ENOUGH_DISTS = 592;
9318 //var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
9319
9320 var MAX_WBITS = 15;
9321 /* 32K LZ77 window */
9322 var DEF_WBITS = MAX_WBITS;
9323
9324
9325 function zswap32(q) {
9326   return  (((q >>> 24) & 0xff) +
9327           ((q >>> 8) & 0xff00) +
9328           ((q & 0xff00) << 8) +
9329           ((q & 0xff) << 24));
9330 }
9331
9332
9333 function InflateState() {
9334   this.mode = 0;             /* current inflate mode */
9335   this.last = false;          /* true if processing last block */
9336   this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
9337   this.havedict = false;      /* true if dictionary provided */
9338   this.flags = 0;             /* gzip header method and flags (0 if zlib) */
9339   this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
9340   this.check = 0;             /* protected copy of check value */
9341   this.total = 0;             /* protected copy of output count */
9342   // TODO: may be {}
9343   this.head = null;           /* where to save gzip header information */
9344
9345   /* sliding window */
9346   this.wbits = 0;             /* log base 2 of requested window size */
9347   this.wsize = 0;             /* window size or zero if not using window */
9348   this.whave = 0;             /* valid bytes in the window */
9349   this.wnext = 0;             /* window write index */
9350   this.window = null;         /* allocated sliding window, if needed */
9351
9352   /* bit accumulator */
9353   this.hold = 0;              /* input bit accumulator */
9354   this.bits = 0;              /* number of bits in "in" */
9355
9356   /* for string and stored block copying */
9357   this.length = 0;            /* literal or length of data to copy */
9358   this.offset = 0;            /* distance back to copy string from */
9359
9360   /* for table and code decoding */
9361   this.extra = 0;             /* extra bits needed */
9362
9363   /* fixed and dynamic code tables */
9364   this.lencode = null;          /* starting table for length/literal codes */
9365   this.distcode = null;         /* starting table for distance codes */
9366   this.lenbits = 0;           /* index bits for lencode */
9367   this.distbits = 0;          /* index bits for distcode */
9368
9369   /* dynamic table building */
9370   this.ncode = 0;             /* number of code length code lengths */
9371   this.nlen = 0;              /* number of length code lengths */
9372   this.ndist = 0;             /* number of distance code lengths */
9373   this.have = 0;              /* number of code lengths in lens[] */
9374   this.next = null;              /* next available space in codes[] */
9375
9376   this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
9377   this.work = new utils.Buf16(288); /* work area for code table building */
9378
9379   /*
9380    because we don't have pointers in js, we use lencode and distcode directly
9381    as buffers so we don't need codes
9382   */
9383   //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
9384   this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
9385   this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
9386   this.sane = 0;                   /* if false, allow invalid distance too far */
9387   this.back = 0;                   /* bits back of last unprocessed length/lit */
9388   this.was = 0;                    /* initial length of match */
9389 }
9390
9391 function inflateResetKeep(strm) {
9392   var state;
9393
9394   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9395   state = strm.state;
9396   strm.total_in = strm.total_out = state.total = 0;
9397   strm.msg = ''; /*Z_NULL*/
9398   if (state.wrap) {       /* to support ill-conceived Java test suite */
9399     strm.adler = state.wrap & 1;
9400   }
9401   state.mode = HEAD;
9402   state.last = 0;
9403   state.havedict = 0;
9404   state.dmax = 32768;
9405   state.head = null/*Z_NULL*/;
9406   state.hold = 0;
9407   state.bits = 0;
9408   //state.lencode = state.distcode = state.next = state.codes;
9409   state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
9410   state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
9411
9412   state.sane = 1;
9413   state.back = -1;
9414   //Tracev((stderr, "inflate: reset\n"));
9415   return Z_OK;
9416 }
9417
9418 function inflateReset(strm) {
9419   var state;
9420
9421   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9422   state = strm.state;
9423   state.wsize = 0;
9424   state.whave = 0;
9425   state.wnext = 0;
9426   return inflateResetKeep(strm);
9427
9428 }
9429
9430 function inflateReset2(strm, windowBits) {
9431   var wrap;
9432   var state;
9433
9434   /* get the state */
9435   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9436   state = strm.state;
9437
9438   /* extract wrap request from windowBits parameter */
9439   if (windowBits < 0) {
9440     wrap = 0;
9441     windowBits = -windowBits;
9442   }
9443   else {
9444     wrap = (windowBits >> 4) + 1;
9445     if (windowBits < 48) {
9446       windowBits &= 15;
9447     }
9448   }
9449
9450   /* set number of window bits, free window if different */
9451   if (windowBits && (windowBits < 8 || windowBits > 15)) {
9452     return Z_STREAM_ERROR;
9453   }
9454   if (state.window !== null && state.wbits !== windowBits) {
9455     state.window = null;
9456   }
9457
9458   /* update state and reset the rest of it */
9459   state.wrap = wrap;
9460   state.wbits = windowBits;
9461   return inflateReset(strm);
9462 }
9463
9464 function inflateInit2(strm, windowBits) {
9465   var ret;
9466   var state;
9467
9468   if (!strm) { return Z_STREAM_ERROR; }
9469   //strm.msg = Z_NULL;                 /* in case we return an error */
9470
9471   state = new InflateState();
9472
9473   //if (state === Z_NULL) return Z_MEM_ERROR;
9474   //Tracev((stderr, "inflate: allocated\n"));
9475   strm.state = state;
9476   state.window = null/*Z_NULL*/;
9477   ret = inflateReset2(strm, windowBits);
9478   if (ret !== Z_OK) {
9479     strm.state = null/*Z_NULL*/;
9480   }
9481   return ret;
9482 }
9483
9484 function inflateInit(strm) {
9485   return inflateInit2(strm, DEF_WBITS);
9486 }
9487
9488
9489 /*
9490  Return state with length and distance decoding tables and index sizes set to
9491  fixed code decoding.  Normally this returns fixed tables from inffixed.h.
9492  If BUILDFIXED is defined, then instead this routine builds the tables the
9493  first time it's called, and returns those tables the first time and
9494  thereafter.  This reduces the size of the code by about 2K bytes, in
9495  exchange for a little execution time.  However, BUILDFIXED should not be
9496  used for threaded applications, since the rewriting of the tables and virgin
9497  may not be thread-safe.
9498  */
9499 var virgin = true;
9500
9501 var lenfix, distfix; // We have no pointers in JS, so keep tables separate
9502
9503 function fixedtables(state) {
9504   /* build fixed huffman tables if first call (may not be thread safe) */
9505   if (virgin) {
9506     var sym;
9507
9508     lenfix = new utils.Buf32(512);
9509     distfix = new utils.Buf32(32);
9510
9511     /* literal/length table */
9512     sym = 0;
9513     while (sym < 144) { state.lens[sym++] = 8; }
9514     while (sym < 256) { state.lens[sym++] = 9; }
9515     while (sym < 280) { state.lens[sym++] = 7; }
9516     while (sym < 288) { state.lens[sym++] = 8; }
9517
9518     inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });
9519
9520     /* distance table */
9521     sym = 0;
9522     while (sym < 32) { state.lens[sym++] = 5; }
9523
9524     inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });
9525
9526     /* do this just once */
9527     virgin = false;
9528   }
9529
9530   state.lencode = lenfix;
9531   state.lenbits = 9;
9532   state.distcode = distfix;
9533   state.distbits = 5;
9534 }
9535
9536
9537 /*
9538  Update the window with the last wsize (normally 32K) bytes written before
9539  returning.  If window does not exist yet, create it.  This is only called
9540  when a window is already in use, or when output has been written during this
9541  inflate call, but the end of the deflate stream has not been reached yet.
9542  It is also called to create a window for dictionary data when a dictionary
9543  is loaded.
9544
9545  Providing output buffers larger than 32K to inflate() should provide a speed
9546  advantage, since only the last 32K of output is copied to the sliding window
9547  upon return from inflate(), and since all distances after the first 32K of
9548  output will fall in the output data, making match copies simpler and faster.
9549  The advantage may be dependent on the size of the processor's data caches.
9550  */
9551 function updatewindow(strm, src, end, copy) {
9552   var dist;
9553   var state = strm.state;
9554
9555   /* if it hasn't been done already, allocate space for the window */
9556   if (state.window === null) {
9557     state.wsize = 1 << state.wbits;
9558     state.wnext = 0;
9559     state.whave = 0;
9560
9561     state.window = new utils.Buf8(state.wsize);
9562   }
9563
9564   /* copy state->wsize or less output bytes into the circular window */
9565   if (copy >= state.wsize) {
9566     utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
9567     state.wnext = 0;
9568     state.whave = state.wsize;
9569   }
9570   else {
9571     dist = state.wsize - state.wnext;
9572     if (dist > copy) {
9573       dist = copy;
9574     }
9575     //zmemcpy(state->window + state->wnext, end - copy, dist);
9576     utils.arraySet(state.window, src, end - copy, dist, state.wnext);
9577     copy -= dist;
9578     if (copy) {
9579       //zmemcpy(state->window, end - copy, copy);
9580       utils.arraySet(state.window, src, end - copy, copy, 0);
9581       state.wnext = copy;
9582       state.whave = state.wsize;
9583     }
9584     else {
9585       state.wnext += dist;
9586       if (state.wnext === state.wsize) { state.wnext = 0; }
9587       if (state.whave < state.wsize) { state.whave += dist; }
9588     }
9589   }
9590   return 0;
9591 }
9592
9593 function inflate(strm, flush) {
9594   var state;
9595   var input, output;          // input/output buffers
9596   var next;                   /* next input INDEX */
9597   var put;                    /* next output INDEX */
9598   var have, left;             /* available input and output */
9599   var hold;                   /* bit buffer */
9600   var bits;                   /* bits in bit buffer */
9601   var _in, _out;              /* save starting available input and output */
9602   var copy;                   /* number of stored or match bytes to copy */
9603   var from;                   /* where to copy match bytes from */
9604   var from_source;
9605   var here = 0;               /* current decoding table entry */
9606   var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
9607   //var last;                   /* parent table entry */
9608   var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
9609   var len;                    /* length to copy for repeats, bits to drop */
9610   var ret;                    /* return code */
9611   var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
9612   var opts;
9613
9614   var n; // temporary var for NEED_BITS
9615
9616   var order = /* permutation of code lengths */
9617     [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
9618
9619
9620   if (!strm || !strm.state || !strm.output ||
9621       (!strm.input && strm.avail_in !== 0)) {
9622     return Z_STREAM_ERROR;
9623   }
9624
9625   state = strm.state;
9626   if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
9627
9628
9629   //--- LOAD() ---
9630   put = strm.next_out;
9631   output = strm.output;
9632   left = strm.avail_out;
9633   next = strm.next_in;
9634   input = strm.input;
9635   have = strm.avail_in;
9636   hold = state.hold;
9637   bits = state.bits;
9638   //---
9639
9640   _in = have;
9641   _out = left;
9642   ret = Z_OK;
9643
9644   inf_leave: // goto emulation
9645   for (;;) {
9646     switch (state.mode) {
9647       case HEAD:
9648         if (state.wrap === 0) {
9649           state.mode = TYPEDO;
9650           break;
9651         }
9652         //=== NEEDBITS(16);
9653         while (bits < 16) {
9654           if (have === 0) { break inf_leave; }
9655           have--;
9656           hold += input[next++] << bits;
9657           bits += 8;
9658         }
9659         //===//
9660         if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
9661           state.check = 0/*crc32(0L, Z_NULL, 0)*/;
9662           //=== CRC2(state.check, hold);
9663           hbuf[0] = hold & 0xff;
9664           hbuf[1] = (hold >>> 8) & 0xff;
9665           state.check = crc32(state.check, hbuf, 2, 0);
9666           //===//
9667
9668           //=== INITBITS();
9669           hold = 0;
9670           bits = 0;
9671           //===//
9672           state.mode = FLAGS;
9673           break;
9674         }
9675         state.flags = 0;           /* expect zlib header */
9676         if (state.head) {
9677           state.head.done = false;
9678         }
9679         if (!(state.wrap & 1) ||   /* check if zlib header allowed */
9680           (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
9681           strm.msg = 'incorrect header check';
9682           state.mode = BAD;
9683           break;
9684         }
9685         if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
9686           strm.msg = 'unknown compression method';
9687           state.mode = BAD;
9688           break;
9689         }
9690         //--- DROPBITS(4) ---//
9691         hold >>>= 4;
9692         bits -= 4;
9693         //---//
9694         len = (hold & 0x0f)/*BITS(4)*/ + 8;
9695         if (state.wbits === 0) {
9696           state.wbits = len;
9697         }
9698         else if (len > state.wbits) {
9699           strm.msg = 'invalid window size';
9700           state.mode = BAD;
9701           break;
9702         }
9703         state.dmax = 1 << len;
9704         //Tracev((stderr, "inflate:   zlib header ok\n"));
9705         strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
9706         state.mode = hold & 0x200 ? DICTID : TYPE;
9707         //=== INITBITS();
9708         hold = 0;
9709         bits = 0;
9710         //===//
9711         break;
9712       case FLAGS:
9713         //=== NEEDBITS(16); */
9714         while (bits < 16) {
9715           if (have === 0) { break inf_leave; }
9716           have--;
9717           hold += input[next++] << bits;
9718           bits += 8;
9719         }
9720         //===//
9721         state.flags = hold;
9722         if ((state.flags & 0xff) !== Z_DEFLATED) {
9723           strm.msg = 'unknown compression method';
9724           state.mode = BAD;
9725           break;
9726         }
9727         if (state.flags & 0xe000) {
9728           strm.msg = 'unknown header flags set';
9729           state.mode = BAD;
9730           break;
9731         }
9732         if (state.head) {
9733           state.head.text = ((hold >> 8) & 1);
9734         }
9735         if (state.flags & 0x0200) {
9736           //=== CRC2(state.check, hold);
9737           hbuf[0] = hold & 0xff;
9738           hbuf[1] = (hold >>> 8) & 0xff;
9739           state.check = crc32(state.check, hbuf, 2, 0);
9740           //===//
9741         }
9742         //=== INITBITS();
9743         hold = 0;
9744         bits = 0;
9745         //===//
9746         state.mode = TIME;
9747         /* falls through */
9748       case TIME:
9749         //=== NEEDBITS(32); */
9750         while (bits < 32) {
9751           if (have === 0) { break inf_leave; }
9752           have--;
9753           hold += input[next++] << bits;
9754           bits += 8;
9755         }
9756         //===//
9757         if (state.head) {
9758           state.head.time = hold;
9759         }
9760         if (state.flags & 0x0200) {
9761           //=== CRC4(state.check, hold)
9762           hbuf[0] = hold & 0xff;
9763           hbuf[1] = (hold >>> 8) & 0xff;
9764           hbuf[2] = (hold >>> 16) & 0xff;
9765           hbuf[3] = (hold >>> 24) & 0xff;
9766           state.check = crc32(state.check, hbuf, 4, 0);
9767           //===
9768         }
9769         //=== INITBITS();
9770         hold = 0;
9771         bits = 0;
9772         //===//
9773         state.mode = OS;
9774         /* falls through */
9775       case OS:
9776         //=== NEEDBITS(16); */
9777         while (bits < 16) {
9778           if (have === 0) { break inf_leave; }
9779           have--;
9780           hold += input[next++] << bits;
9781           bits += 8;
9782         }
9783         //===//
9784         if (state.head) {
9785           state.head.xflags = (hold & 0xff);
9786           state.head.os = (hold >> 8);
9787         }
9788         if (state.flags & 0x0200) {
9789           //=== CRC2(state.check, hold);
9790           hbuf[0] = hold & 0xff;
9791           hbuf[1] = (hold >>> 8) & 0xff;
9792           state.check = crc32(state.check, hbuf, 2, 0);
9793           //===//
9794         }
9795         //=== INITBITS();
9796         hold = 0;
9797         bits = 0;
9798         //===//
9799         state.mode = EXLEN;
9800         /* falls through */
9801       case EXLEN:
9802         if (state.flags & 0x0400) {
9803           //=== NEEDBITS(16); */
9804           while (bits < 16) {
9805             if (have === 0) { break inf_leave; }
9806             have--;
9807             hold += input[next++] << bits;
9808             bits += 8;
9809           }
9810           //===//
9811           state.length = hold;
9812           if (state.head) {
9813             state.head.extra_len = hold;
9814           }
9815           if (state.flags & 0x0200) {
9816             //=== CRC2(state.check, hold);
9817             hbuf[0] = hold & 0xff;
9818             hbuf[1] = (hold >>> 8) & 0xff;
9819             state.check = crc32(state.check, hbuf, 2, 0);
9820             //===//
9821           }
9822           //=== INITBITS();
9823           hold = 0;
9824           bits = 0;
9825           //===//
9826         }
9827         else if (state.head) {
9828           state.head.extra = null/*Z_NULL*/;
9829         }
9830         state.mode = EXTRA;
9831         /* falls through */
9832       case EXTRA:
9833         if (state.flags & 0x0400) {
9834           copy = state.length;
9835           if (copy > have) { copy = have; }
9836           if (copy) {
9837             if (state.head) {
9838               len = state.head.extra_len - state.length;
9839               if (!state.head.extra) {
9840                 // Use untyped array for more convenient processing later
9841                 state.head.extra = new Array(state.head.extra_len);
9842               }
9843               utils.arraySet(
9844                 state.head.extra,
9845                 input,
9846                 next,
9847                 // extra field is limited to 65536 bytes
9848                 // - no need for additional size check
9849                 copy,
9850                 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
9851                 len
9852               );
9853               //zmemcpy(state.head.extra + len, next,
9854               //        len + copy > state.head.extra_max ?
9855               //        state.head.extra_max - len : copy);
9856             }
9857             if (state.flags & 0x0200) {
9858               state.check = crc32(state.check, input, copy, next);
9859             }
9860             have -= copy;
9861             next += copy;
9862             state.length -= copy;
9863           }
9864           if (state.length) { break inf_leave; }
9865         }
9866         state.length = 0;
9867         state.mode = NAME;
9868         /* falls through */
9869       case NAME:
9870         if (state.flags & 0x0800) {
9871           if (have === 0) { break inf_leave; }
9872           copy = 0;
9873           do {
9874             // TODO: 2 or 1 bytes?
9875             len = input[next + copy++];
9876             /* use constant limit because in js we should not preallocate memory */
9877             if (state.head && len &&
9878                 (state.length < 65536 /*state.head.name_max*/)) {
9879               state.head.name += String.fromCharCode(len);
9880             }
9881           } while (len && copy < have);
9882
9883           if (state.flags & 0x0200) {
9884             state.check = crc32(state.check, input, copy, next);
9885           }
9886           have -= copy;
9887           next += copy;
9888           if (len) { break inf_leave; }
9889         }
9890         else if (state.head) {
9891           state.head.name = null;
9892         }
9893         state.length = 0;
9894         state.mode = COMMENT;
9895         /* falls through */
9896       case COMMENT:
9897         if (state.flags & 0x1000) {
9898           if (have === 0) { break inf_leave; }
9899           copy = 0;
9900           do {
9901             len = input[next + copy++];
9902             /* use constant limit because in js we should not preallocate memory */
9903             if (state.head && len &&
9904                 (state.length < 65536 /*state.head.comm_max*/)) {
9905               state.head.comment += String.fromCharCode(len);
9906             }
9907           } while (len && copy < have);
9908           if (state.flags & 0x0200) {
9909             state.check = crc32(state.check, input, copy, next);
9910           }
9911           have -= copy;
9912           next += copy;
9913           if (len) { break inf_leave; }
9914         }
9915         else if (state.head) {
9916           state.head.comment = null;
9917         }
9918         state.mode = HCRC;
9919         /* falls through */
9920       case HCRC:
9921         if (state.flags & 0x0200) {
9922           //=== NEEDBITS(16); */
9923           while (bits < 16) {
9924             if (have === 0) { break inf_leave; }
9925             have--;
9926             hold += input[next++] << bits;
9927             bits += 8;
9928           }
9929           //===//
9930           if (hold !== (state.check & 0xffff)) {
9931             strm.msg = 'header crc mismatch';
9932             state.mode = BAD;
9933             break;
9934           }
9935           //=== INITBITS();
9936           hold = 0;
9937           bits = 0;
9938           //===//
9939         }
9940         if (state.head) {
9941           state.head.hcrc = ((state.flags >> 9) & 1);
9942           state.head.done = true;
9943         }
9944         strm.adler = state.check = 0;
9945         state.mode = TYPE;
9946         break;
9947       case DICTID:
9948         //=== NEEDBITS(32); */
9949         while (bits < 32) {
9950           if (have === 0) { break inf_leave; }
9951           have--;
9952           hold += input[next++] << bits;
9953           bits += 8;
9954         }
9955         //===//
9956         strm.adler = state.check = zswap32(hold);
9957         //=== INITBITS();
9958         hold = 0;
9959         bits = 0;
9960         //===//
9961         state.mode = DICT;
9962         /* falls through */
9963       case DICT:
9964         if (state.havedict === 0) {
9965           //--- RESTORE() ---
9966           strm.next_out = put;
9967           strm.avail_out = left;
9968           strm.next_in = next;
9969           strm.avail_in = have;
9970           state.hold = hold;
9971           state.bits = bits;
9972           //---
9973           return Z_NEED_DICT;
9974         }
9975         strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
9976         state.mode = TYPE;
9977         /* falls through */
9978       case TYPE:
9979         if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
9980         /* falls through */
9981       case TYPEDO:
9982         if (state.last) {
9983           //--- BYTEBITS() ---//
9984           hold >>>= bits & 7;
9985           bits -= bits & 7;
9986           //---//
9987           state.mode = CHECK;
9988           break;
9989         }
9990         //=== NEEDBITS(3); */
9991         while (bits < 3) {
9992           if (have === 0) { break inf_leave; }
9993           have--;
9994           hold += input[next++] << bits;
9995           bits += 8;
9996         }
9997         //===//
9998         state.last = (hold & 0x01)/*BITS(1)*/;
9999         //--- DROPBITS(1) ---//
10000         hold >>>= 1;
10001         bits -= 1;
10002         //---//
10003
10004         switch ((hold & 0x03)/*BITS(2)*/) {
10005           case 0:                             /* stored block */
10006             //Tracev((stderr, "inflate:     stored block%s\n",
10007             //        state.last ? " (last)" : ""));
10008             state.mode = STORED;
10009             break;
10010           case 1:                             /* fixed block */
10011             fixedtables(state);
10012             //Tracev((stderr, "inflate:     fixed codes block%s\n",
10013             //        state.last ? " (last)" : ""));
10014             state.mode = LEN_;             /* decode codes */
10015             if (flush === Z_TREES) {
10016               //--- DROPBITS(2) ---//
10017               hold >>>= 2;
10018               bits -= 2;
10019               //---//
10020               break inf_leave;
10021             }
10022             break;
10023           case 2:                             /* dynamic block */
10024             //Tracev((stderr, "inflate:     dynamic codes block%s\n",
10025             //        state.last ? " (last)" : ""));
10026             state.mode = TABLE;
10027             break;
10028           case 3:
10029             strm.msg = 'invalid block type';
10030             state.mode = BAD;
10031         }
10032         //--- DROPBITS(2) ---//
10033         hold >>>= 2;
10034         bits -= 2;
10035         //---//
10036         break;
10037       case STORED:
10038         //--- BYTEBITS() ---// /* go to byte boundary */
10039         hold >>>= bits & 7;
10040         bits -= bits & 7;
10041         //---//
10042         //=== NEEDBITS(32); */
10043         while (bits < 32) {
10044           if (have === 0) { break inf_leave; }
10045           have--;
10046           hold += input[next++] << bits;
10047           bits += 8;
10048         }
10049         //===//
10050         if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
10051           strm.msg = 'invalid stored block lengths';
10052           state.mode = BAD;
10053           break;
10054         }
10055         state.length = hold & 0xffff;
10056         //Tracev((stderr, "inflate:       stored length %u\n",
10057         //        state.length));
10058         //=== INITBITS();
10059         hold = 0;
10060         bits = 0;
10061         //===//
10062         state.mode = COPY_;
10063         if (flush === Z_TREES) { break inf_leave; }
10064         /* falls through */
10065       case COPY_:
10066         state.mode = COPY;
10067         /* falls through */
10068       case COPY:
10069         copy = state.length;
10070         if (copy) {
10071           if (copy > have) { copy = have; }
10072           if (copy > left) { copy = left; }
10073           if (copy === 0) { break inf_leave; }
10074           //--- zmemcpy(put, next, copy); ---
10075           utils.arraySet(output, input, next, copy, put);
10076           //---//
10077           have -= copy;
10078           next += copy;
10079           left -= copy;
10080           put += copy;
10081           state.length -= copy;
10082           break;
10083         }
10084         //Tracev((stderr, "inflate:       stored end\n"));
10085         state.mode = TYPE;
10086         break;
10087       case TABLE:
10088         //=== NEEDBITS(14); */
10089         while (bits < 14) {
10090           if (have === 0) { break inf_leave; }
10091           have--;
10092           hold += input[next++] << bits;
10093           bits += 8;
10094         }
10095         //===//
10096         state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
10097         //--- DROPBITS(5) ---//
10098         hold >>>= 5;
10099         bits -= 5;
10100         //---//
10101         state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
10102         //--- DROPBITS(5) ---//
10103         hold >>>= 5;
10104         bits -= 5;
10105         //---//
10106         state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
10107         //--- DROPBITS(4) ---//
10108         hold >>>= 4;
10109         bits -= 4;
10110         //---//
10111 //#ifndef PKZIP_BUG_WORKAROUND
10112         if (state.nlen > 286 || state.ndist > 30) {
10113           strm.msg = 'too many length or distance symbols';
10114           state.mode = BAD;
10115           break;
10116         }
10117 //#endif
10118         //Tracev((stderr, "inflate:       table sizes ok\n"));
10119         state.have = 0;
10120         state.mode = LENLENS;
10121         /* falls through */
10122       case LENLENS:
10123         while (state.have < state.ncode) {
10124           //=== NEEDBITS(3);
10125           while (bits < 3) {
10126             if (have === 0) { break inf_leave; }
10127             have--;
10128             hold += input[next++] << bits;
10129             bits += 8;
10130           }
10131           //===//
10132           state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
10133           //--- DROPBITS(3) ---//
10134           hold >>>= 3;
10135           bits -= 3;
10136           //---//
10137         }
10138         while (state.have < 19) {
10139           state.lens[order[state.have++]] = 0;
10140         }
10141         // We have separate tables & no pointers. 2 commented lines below not needed.
10142         //state.next = state.codes;
10143         //state.lencode = state.next;
10144         // Switch to use dynamic table
10145         state.lencode = state.lendyn;
10146         state.lenbits = 7;
10147
10148         opts = { bits: state.lenbits };
10149         ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
10150         state.lenbits = opts.bits;
10151
10152         if (ret) {
10153           strm.msg = 'invalid code lengths set';
10154           state.mode = BAD;
10155           break;
10156         }
10157         //Tracev((stderr, "inflate:       code lengths ok\n"));
10158         state.have = 0;
10159         state.mode = CODELENS;
10160         /* falls through */
10161       case CODELENS:
10162         while (state.have < state.nlen + state.ndist) {
10163           for (;;) {
10164             here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
10165             here_bits = here >>> 24;
10166             here_op = (here >>> 16) & 0xff;
10167             here_val = here & 0xffff;
10168
10169             if ((here_bits) <= bits) { break; }
10170             //--- PULLBYTE() ---//
10171             if (have === 0) { break inf_leave; }
10172             have--;
10173             hold += input[next++] << bits;
10174             bits += 8;
10175             //---//
10176           }
10177           if (here_val < 16) {
10178             //--- DROPBITS(here.bits) ---//
10179             hold >>>= here_bits;
10180             bits -= here_bits;
10181             //---//
10182             state.lens[state.have++] = here_val;
10183           }
10184           else {
10185             if (here_val === 16) {
10186               //=== NEEDBITS(here.bits + 2);
10187               n = here_bits + 2;
10188               while (bits < n) {
10189                 if (have === 0) { break inf_leave; }
10190                 have--;
10191                 hold += input[next++] << bits;
10192                 bits += 8;
10193               }
10194               //===//
10195               //--- DROPBITS(here.bits) ---//
10196               hold >>>= here_bits;
10197               bits -= here_bits;
10198               //---//
10199               if (state.have === 0) {
10200                 strm.msg = 'invalid bit length repeat';
10201                 state.mode = BAD;
10202                 break;
10203               }
10204               len = state.lens[state.have - 1];
10205               copy = 3 + (hold & 0x03);//BITS(2);
10206               //--- DROPBITS(2) ---//
10207               hold >>>= 2;
10208               bits -= 2;
10209               //---//
10210             }
10211             else if (here_val === 17) {
10212               //=== NEEDBITS(here.bits + 3);
10213               n = here_bits + 3;
10214               while (bits < n) {
10215                 if (have === 0) { break inf_leave; }
10216                 have--;
10217                 hold += input[next++] << bits;
10218                 bits += 8;
10219               }
10220               //===//
10221               //--- DROPBITS(here.bits) ---//
10222               hold >>>= here_bits;
10223               bits -= here_bits;
10224               //---//
10225               len = 0;
10226               copy = 3 + (hold & 0x07);//BITS(3);
10227               //--- DROPBITS(3) ---//
10228               hold >>>= 3;
10229               bits -= 3;
10230               //---//
10231             }
10232             else {
10233               //=== NEEDBITS(here.bits + 7);
10234               n = here_bits + 7;
10235               while (bits < n) {
10236                 if (have === 0) { break inf_leave; }
10237                 have--;
10238                 hold += input[next++] << bits;
10239                 bits += 8;
10240               }
10241               //===//
10242               //--- DROPBITS(here.bits) ---//
10243               hold >>>= here_bits;
10244               bits -= here_bits;
10245               //---//
10246               len = 0;
10247               copy = 11 + (hold & 0x7f);//BITS(7);
10248               //--- DROPBITS(7) ---//
10249               hold >>>= 7;
10250               bits -= 7;
10251               //---//
10252             }
10253             if (state.have + copy > state.nlen + state.ndist) {
10254               strm.msg = 'invalid bit length repeat';
10255               state.mode = BAD;
10256               break;
10257             }
10258             while (copy--) {
10259               state.lens[state.have++] = len;
10260             }
10261           }
10262         }
10263
10264         /* handle error breaks in while */
10265         if (state.mode === BAD) { break; }
10266
10267         /* check for end-of-block code (better have one) */
10268         if (state.lens[256] === 0) {
10269           strm.msg = 'invalid code -- missing end-of-block';
10270           state.mode = BAD;
10271           break;
10272         }
10273
10274         /* build code tables -- note: do not change the lenbits or distbits
10275            values here (9 and 6) without reading the comments in inftrees.h
10276            concerning the ENOUGH constants, which depend on those values */
10277         state.lenbits = 9;
10278
10279         opts = { bits: state.lenbits };
10280         ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
10281         // We have separate tables & no pointers. 2 commented lines below not needed.
10282         // state.next_index = opts.table_index;
10283         state.lenbits = opts.bits;
10284         // state.lencode = state.next;
10285
10286         if (ret) {
10287           strm.msg = 'invalid literal/lengths set';
10288           state.mode = BAD;
10289           break;
10290         }
10291
10292         state.distbits = 6;
10293         //state.distcode.copy(state.codes);
10294         // Switch to use dynamic table
10295         state.distcode = state.distdyn;
10296         opts = { bits: state.distbits };
10297         ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
10298         // We have separate tables & no pointers. 2 commented lines below not needed.
10299         // state.next_index = opts.table_index;
10300         state.distbits = opts.bits;
10301         // state.distcode = state.next;
10302
10303         if (ret) {
10304           strm.msg = 'invalid distances set';
10305           state.mode = BAD;
10306           break;
10307         }
10308         //Tracev((stderr, 'inflate:       codes ok\n'));
10309         state.mode = LEN_;
10310         if (flush === Z_TREES) { break inf_leave; }
10311         /* falls through */
10312       case LEN_:
10313         state.mode = LEN;
10314         /* falls through */
10315       case LEN:
10316         if (have >= 6 && left >= 258) {
10317           //--- RESTORE() ---
10318           strm.next_out = put;
10319           strm.avail_out = left;
10320           strm.next_in = next;
10321           strm.avail_in = have;
10322           state.hold = hold;
10323           state.bits = bits;
10324           //---
10325           inflate_fast(strm, _out);
10326           //--- LOAD() ---
10327           put = strm.next_out;
10328           output = strm.output;
10329           left = strm.avail_out;
10330           next = strm.next_in;
10331           input = strm.input;
10332           have = strm.avail_in;
10333           hold = state.hold;
10334           bits = state.bits;
10335           //---
10336
10337           if (state.mode === TYPE) {
10338             state.back = -1;
10339           }
10340           break;
10341         }
10342         state.back = 0;
10343         for (;;) {
10344           here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
10345           here_bits = here >>> 24;
10346           here_op = (here >>> 16) & 0xff;
10347           here_val = here & 0xffff;
10348
10349           if (here_bits <= bits) { break; }
10350           //--- PULLBYTE() ---//
10351           if (have === 0) { break inf_leave; }
10352           have--;
10353           hold += input[next++] << bits;
10354           bits += 8;
10355           //---//
10356         }
10357         if (here_op && (here_op & 0xf0) === 0) {
10358           last_bits = here_bits;
10359           last_op = here_op;
10360           last_val = here_val;
10361           for (;;) {
10362             here = state.lencode[last_val +
10363                     ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
10364             here_bits = here >>> 24;
10365             here_op = (here >>> 16) & 0xff;
10366             here_val = here & 0xffff;
10367
10368             if ((last_bits + here_bits) <= bits) { break; }
10369             //--- PULLBYTE() ---//
10370             if (have === 0) { break inf_leave; }
10371             have--;
10372             hold += input[next++] << bits;
10373             bits += 8;
10374             //---//
10375           }
10376           //--- DROPBITS(last.bits) ---//
10377           hold >>>= last_bits;
10378           bits -= last_bits;
10379           //---//
10380           state.back += last_bits;
10381         }
10382         //--- DROPBITS(here.bits) ---//
10383         hold >>>= here_bits;
10384         bits -= here_bits;
10385         //---//
10386         state.back += here_bits;
10387         state.length = here_val;
10388         if (here_op === 0) {
10389           //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
10390           //        "inflate:         literal '%c'\n" :
10391           //        "inflate:         literal 0x%02x\n", here.val));
10392           state.mode = LIT;
10393           break;
10394         }
10395         if (here_op & 32) {
10396           //Tracevv((stderr, "inflate:         end of block\n"));
10397           state.back = -1;
10398           state.mode = TYPE;
10399           break;
10400         }
10401         if (here_op & 64) {
10402           strm.msg = 'invalid literal/length code';
10403           state.mode = BAD;
10404           break;
10405         }
10406         state.extra = here_op & 15;
10407         state.mode = LENEXT;
10408         /* falls through */
10409       case LENEXT:
10410         if (state.extra) {
10411           //=== NEEDBITS(state.extra);
10412           n = state.extra;
10413           while (bits < n) {
10414             if (have === 0) { break inf_leave; }
10415             have--;
10416             hold += input[next++] << bits;
10417             bits += 8;
10418           }
10419           //===//
10420           state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
10421           //--- DROPBITS(state.extra) ---//
10422           hold >>>= state.extra;
10423           bits -= state.extra;
10424           //---//
10425           state.back += state.extra;
10426         }
10427         //Tracevv((stderr, "inflate:         length %u\n", state.length));
10428         state.was = state.length;
10429         state.mode = DIST;
10430         /* falls through */
10431       case DIST:
10432         for (;;) {
10433           here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
10434           here_bits = here >>> 24;
10435           here_op = (here >>> 16) & 0xff;
10436           here_val = here & 0xffff;
10437
10438           if ((here_bits) <= bits) { break; }
10439           //--- PULLBYTE() ---//
10440           if (have === 0) { break inf_leave; }
10441           have--;
10442           hold += input[next++] << bits;
10443           bits += 8;
10444           //---//
10445         }
10446         if ((here_op & 0xf0) === 0) {
10447           last_bits = here_bits;
10448           last_op = here_op;
10449           last_val = here_val;
10450           for (;;) {
10451             here = state.distcode[last_val +
10452                     ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
10453             here_bits = here >>> 24;
10454             here_op = (here >>> 16) & 0xff;
10455             here_val = here & 0xffff;
10456
10457             if ((last_bits + here_bits) <= bits) { break; }
10458             //--- PULLBYTE() ---//
10459             if (have === 0) { break inf_leave; }
10460             have--;
10461             hold += input[next++] << bits;
10462             bits += 8;
10463             //---//
10464           }
10465           //--- DROPBITS(last.bits) ---//
10466           hold >>>= last_bits;
10467           bits -= last_bits;
10468           //---//
10469           state.back += last_bits;
10470         }
10471         //--- DROPBITS(here.bits) ---//
10472         hold >>>= here_bits;
10473         bits -= here_bits;
10474         //---//
10475         state.back += here_bits;
10476         if (here_op & 64) {
10477           strm.msg = 'invalid distance code';
10478           state.mode = BAD;
10479           break;
10480         }
10481         state.offset = here_val;
10482         state.extra = (here_op) & 15;
10483         state.mode = DISTEXT;
10484         /* falls through */
10485       case DISTEXT:
10486         if (state.extra) {
10487           //=== NEEDBITS(state.extra);
10488           n = state.extra;
10489           while (bits < n) {
10490             if (have === 0) { break inf_leave; }
10491             have--;
10492             hold += input[next++] << bits;
10493             bits += 8;
10494           }
10495           //===//
10496           state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
10497           //--- DROPBITS(state.extra) ---//
10498           hold >>>= state.extra;
10499           bits -= state.extra;
10500           //---//
10501           state.back += state.extra;
10502         }
10503 //#ifdef INFLATE_STRICT
10504         if (state.offset > state.dmax) {
10505           strm.msg = 'invalid distance too far back';
10506           state.mode = BAD;
10507           break;
10508         }
10509 //#endif
10510         //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
10511         state.mode = MATCH;
10512         /* falls through */
10513       case MATCH:
10514         if (left === 0) { break inf_leave; }
10515         copy = _out - left;
10516         if (state.offset > copy) {         /* copy from window */
10517           copy = state.offset - copy;
10518           if (copy > state.whave) {
10519             if (state.sane) {
10520               strm.msg = 'invalid distance too far back';
10521               state.mode = BAD;
10522               break;
10523             }
10524 // (!) This block is disabled in zlib defaults,
10525 // don't enable it for binary compatibility
10526 //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
10527 //          Trace((stderr, "inflate.c too far\n"));
10528 //          copy -= state.whave;
10529 //          if (copy > state.length) { copy = state.length; }
10530 //          if (copy > left) { copy = left; }
10531 //          left -= copy;
10532 //          state.length -= copy;
10533 //          do {
10534 //            output[put++] = 0;
10535 //          } while (--copy);
10536 //          if (state.length === 0) { state.mode = LEN; }
10537 //          break;
10538 //#endif
10539           }
10540           if (copy > state.wnext) {
10541             copy -= state.wnext;
10542             from = state.wsize - copy;
10543           }
10544           else {
10545             from = state.wnext - copy;
10546           }
10547           if (copy > state.length) { copy = state.length; }
10548           from_source = state.window;
10549         }
10550         else {                              /* copy from output */
10551           from_source = output;
10552           from = put - state.offset;
10553           copy = state.length;
10554         }
10555         if (copy > left) { copy = left; }
10556         left -= copy;
10557         state.length -= copy;
10558         do {
10559           output[put++] = from_source[from++];
10560         } while (--copy);
10561         if (state.length === 0) { state.mode = LEN; }
10562         break;
10563       case LIT:
10564         if (left === 0) { break inf_leave; }
10565         output[put++] = state.length;
10566         left--;
10567         state.mode = LEN;
10568         break;
10569       case CHECK:
10570         if (state.wrap) {
10571           //=== NEEDBITS(32);
10572           while (bits < 32) {
10573             if (have === 0) { break inf_leave; }
10574             have--;
10575             // Use '|' instead of '+' to make sure that result is signed
10576             hold |= input[next++] << bits;
10577             bits += 8;
10578           }
10579           //===//
10580           _out -= left;
10581           strm.total_out += _out;
10582           state.total += _out;
10583           if (_out) {
10584             strm.adler = state.check =
10585                 /*UPDATE(state.check, put - _out, _out);*/
10586                 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
10587
10588           }
10589           _out = left;
10590           // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
10591           if ((state.flags ? hold : zswap32(hold)) !== state.check) {
10592             strm.msg = 'incorrect data check';
10593             state.mode = BAD;
10594             break;
10595           }
10596           //=== INITBITS();
10597           hold = 0;
10598           bits = 0;
10599           //===//
10600           //Tracev((stderr, "inflate:   check matches trailer\n"));
10601         }
10602         state.mode = LENGTH;
10603         /* falls through */
10604       case LENGTH:
10605         if (state.wrap && state.flags) {
10606           //=== NEEDBITS(32);
10607           while (bits < 32) {
10608             if (have === 0) { break inf_leave; }
10609             have--;
10610             hold += input[next++] << bits;
10611             bits += 8;
10612           }
10613           //===//
10614           if (hold !== (state.total & 0xffffffff)) {
10615             strm.msg = 'incorrect length check';
10616             state.mode = BAD;
10617             break;
10618           }
10619           //=== INITBITS();
10620           hold = 0;
10621           bits = 0;
10622           //===//
10623           //Tracev((stderr, "inflate:   length matches trailer\n"));
10624         }
10625         state.mode = DONE;
10626         /* falls through */
10627       case DONE:
10628         ret = Z_STREAM_END;
10629         break inf_leave;
10630       case BAD:
10631         ret = Z_DATA_ERROR;
10632         break inf_leave;
10633       case MEM:
10634         return Z_MEM_ERROR;
10635       case SYNC:
10636         /* falls through */
10637       default:
10638         return Z_STREAM_ERROR;
10639     }
10640   }
10641
10642   // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
10643
10644   /*
10645      Return from inflate(), updating the total counts and the check value.
10646      If there was no progress during the inflate() call, return a buffer
10647      error.  Call updatewindow() to create and/or update the window state.
10648      Note: a memory error from inflate() is non-recoverable.
10649    */
10650
10651   //--- RESTORE() ---
10652   strm.next_out = put;
10653   strm.avail_out = left;
10654   strm.next_in = next;
10655   strm.avail_in = have;
10656   state.hold = hold;
10657   state.bits = bits;
10658   //---
10659
10660   if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
10661                       (state.mode < CHECK || flush !== Z_FINISH))) {
10662     if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
10663       state.mode = MEM;
10664       return Z_MEM_ERROR;
10665     }
10666   }
10667   _in -= strm.avail_in;
10668   _out -= strm.avail_out;
10669   strm.total_in += _in;
10670   strm.total_out += _out;
10671   state.total += _out;
10672   if (state.wrap && _out) {
10673     strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
10674       (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
10675   }
10676   strm.data_type = state.bits + (state.last ? 64 : 0) +
10677                     (state.mode === TYPE ? 128 : 0) +
10678                     (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
10679   if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
10680     ret = Z_BUF_ERROR;
10681   }
10682   return ret;
10683 }
10684
10685 function inflateEnd(strm) {
10686
10687   if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
10688     return Z_STREAM_ERROR;
10689   }
10690
10691   var state = strm.state;
10692   if (state.window) {
10693     state.window = null;
10694   }
10695   strm.state = null;
10696   return Z_OK;
10697 }
10698
10699 function inflateGetHeader(strm, head) {
10700   var state;
10701
10702   /* check state */
10703   if (!strm || !strm.state) { return Z_STREAM_ERROR; }
10704   state = strm.state;
10705   if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
10706
10707   /* save header structure */
10708   state.head = head;
10709   head.done = false;
10710   return Z_OK;
10711 }
10712
10713 function inflateSetDictionary(strm, dictionary) {
10714   var dictLength = dictionary.length;
10715
10716   var state;
10717   var dictid;
10718   var ret;
10719
10720   /* check state */
10721   if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
10722   state = strm.state;
10723
10724   if (state.wrap !== 0 && state.mode !== DICT) {
10725     return Z_STREAM_ERROR;
10726   }
10727
10728   /* check for correct dictionary identifier */
10729   if (state.mode === DICT) {
10730     dictid = 1; /* adler32(0, null, 0)*/
10731     /* dictid = adler32(dictid, dictionary, dictLength); */
10732     dictid = adler32(dictid, dictionary, dictLength, 0);
10733     if (dictid !== state.check) {
10734       return Z_DATA_ERROR;
10735     }
10736   }
10737   /* copy dictionary to window using updatewindow(), which will amend the
10738    existing dictionary if appropriate */
10739   ret = updatewindow(strm, dictionary, dictLength, dictLength);
10740   if (ret) {
10741     state.mode = MEM;
10742     return Z_MEM_ERROR;
10743   }
10744   state.havedict = 1;
10745   // Tracev((stderr, "inflate:   dictionary set\n"));
10746   return Z_OK;
10747 }
10748
10749 exports.inflateReset = inflateReset;
10750 exports.inflateReset2 = inflateReset2;
10751 exports.inflateResetKeep = inflateResetKeep;
10752 exports.inflateInit = inflateInit;
10753 exports.inflateInit2 = inflateInit2;
10754 exports.inflate = inflate;
10755 exports.inflateEnd = inflateEnd;
10756 exports.inflateGetHeader = inflateGetHeader;
10757 exports.inflateSetDictionary = inflateSetDictionary;
10758 exports.inflateInfo = 'pako inflate (from Nodeca project)';
10759
10760 /* Not implemented
10761 exports.inflateCopy = inflateCopy;
10762 exports.inflateGetDictionary = inflateGetDictionary;
10763 exports.inflateMark = inflateMark;
10764 exports.inflatePrime = inflatePrime;
10765 exports.inflateSync = inflateSync;
10766 exports.inflateSyncPoint = inflateSyncPoint;
10767 exports.inflateUndermine = inflateUndermine;
10768 */
10769
10770 },{"../utils/common":26,"./adler32":28,"./crc32":30,"./inffast":33,"./inftrees":35}],35:[function(require,module,exports){
10771 'use strict';
10772
10773 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
10774 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
10775 //
10776 // This software is provided 'as-is', without any express or implied
10777 // warranty. In no event will the authors be held liable for any damages
10778 // arising from the use of this software.
10779 //
10780 // Permission is granted to anyone to use this software for any purpose,
10781 // including commercial applications, and to alter it and redistribute it
10782 // freely, subject to the following restrictions:
10783 //
10784 // 1. The origin of this software must not be misrepresented; you must not
10785 //   claim that you wrote the original software. If you use this software
10786 //   in a product, an acknowledgment in the product documentation would be
10787 //   appreciated but is not required.
10788 // 2. Altered source versions must be plainly marked as such, and must not be
10789 //   misrepresented as being the original software.
10790 // 3. This notice may not be removed or altered from any source distribution.
10791
10792 var utils = require('../utils/common');
10793
10794 var MAXBITS = 15;
10795 var ENOUGH_LENS = 852;
10796 var ENOUGH_DISTS = 592;
10797 //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
10798
10799 var CODES = 0;
10800 var LENS = 1;
10801 var DISTS = 2;
10802
10803 var lbase = [ /* Length codes 257..285 base */
10804   3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
10805   35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
10806 ];
10807
10808 var lext = [ /* Length codes 257..285 extra */
10809   16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
10810   19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
10811 ];
10812
10813 var dbase = [ /* Distance codes 0..29 base */
10814   1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
10815   257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
10816   8193, 12289, 16385, 24577, 0, 0
10817 ];
10818
10819 var dext = [ /* Distance codes 0..29 extra */
10820   16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
10821   23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
10822   28, 28, 29, 29, 64, 64
10823 ];
10824
10825 module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
10826 {
10827   var bits = opts.bits;
10828       //here = opts.here; /* table entry for duplication */
10829
10830   var len = 0;               /* a code's length in bits */
10831   var sym = 0;               /* index of code symbols */
10832   var min = 0, max = 0;          /* minimum and maximum code lengths */
10833   var root = 0;              /* number of index bits for root table */
10834   var curr = 0;              /* number of index bits for current table */
10835   var drop = 0;              /* code bits to drop for sub-table */
10836   var left = 0;                   /* number of prefix codes available */
10837   var used = 0;              /* code entries in table used */
10838   var huff = 0;              /* Huffman code */
10839   var incr;              /* for incrementing code, index */
10840   var fill;              /* index for replicating entries */
10841   var low;               /* low bits for current root entry */
10842   var mask;              /* mask for low root bits */
10843   var next;             /* next available space in table */
10844   var base = null;     /* base value table to use */
10845   var base_index = 0;
10846 //  var shoextra;    /* extra bits table to use */
10847   var end;                    /* use base and extra for symbol > end */
10848   var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
10849   var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
10850   var extra = null;
10851   var extra_index = 0;
10852
10853   var here_bits, here_op, here_val;
10854
10855   /*
10856    Process a set of code lengths to create a canonical Huffman code.  The
10857    code lengths are lens[0..codes-1].  Each length corresponds to the
10858    symbols 0..codes-1.  The Huffman code is generated by first sorting the
10859    symbols by length from short to long, and retaining the symbol order
10860    for codes with equal lengths.  Then the code starts with all zero bits
10861    for the first code of the shortest length, and the codes are integer
10862    increments for the same length, and zeros are appended as the length
10863    increases.  For the deflate format, these bits are stored backwards
10864    from their more natural integer increment ordering, and so when the
10865    decoding tables are built in the large loop below, the integer codes
10866    are incremented backwards.
10867
10868    This routine assumes, but does not check, that all of the entries in
10869    lens[] are in the range 0..MAXBITS.  The caller must assure this.
10870    1..MAXBITS is interpreted as that code length.  zero means that that
10871    symbol does not occur in this code.
10872
10873    The codes are sorted by computing a count of codes for each length,
10874    creating from that a table of starting indices for each length in the
10875    sorted table, and then entering the symbols in order in the sorted
10876    table.  The sorted table is work[], with that space being provided by
10877    the caller.
10878
10879    The length counts are used for other purposes as well, i.e. finding
10880    the minimum and maximum length codes, determining if there are any
10881    codes at all, checking for a valid set of lengths, and looking ahead
10882    at length counts to determine sub-table sizes when building the
10883    decoding tables.
10884    */
10885
10886   /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
10887   for (len = 0; len <= MAXBITS; len++) {
10888     count[len] = 0;
10889   }
10890   for (sym = 0; sym < codes; sym++) {
10891     count[lens[lens_index + sym]]++;
10892   }
10893
10894   /* bound code lengths, force root to be within code lengths */
10895   root = bits;
10896   for (max = MAXBITS; max >= 1; max--) {
10897     if (count[max] !== 0) { break; }
10898   }
10899   if (root > max) {
10900     root = max;
10901   }
10902   if (max === 0) {                     /* no symbols to code at all */
10903     //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
10904     //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
10905     //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
10906     table[table_index++] = (1 << 24) | (64 << 16) | 0;
10907
10908
10909     //table.op[opts.table_index] = 64;
10910     //table.bits[opts.table_index] = 1;
10911     //table.val[opts.table_index++] = 0;
10912     table[table_index++] = (1 << 24) | (64 << 16) | 0;
10913
10914     opts.bits = 1;
10915     return 0;     /* no symbols, but wait for decoding to report error */
10916   }
10917   for (min = 1; min < max; min++) {
10918     if (count[min] !== 0) { break; }
10919   }
10920   if (root < min) {
10921     root = min;
10922   }
10923
10924   /* check for an over-subscribed or incomplete set of lengths */
10925   left = 1;
10926   for (len = 1; len <= MAXBITS; len++) {
10927     left <<= 1;
10928     left -= count[len];
10929     if (left < 0) {
10930       return -1;
10931     }        /* over-subscribed */
10932   }
10933   if (left > 0 && (type === CODES || max !== 1)) {
10934     return -1;                      /* incomplete set */
10935   }
10936
10937   /* generate offsets into symbol table for each length for sorting */
10938   offs[1] = 0;
10939   for (len = 1; len < MAXBITS; len++) {
10940     offs[len + 1] = offs[len] + count[len];
10941   }
10942
10943   /* sort symbols by length, by symbol order within each length */
10944   for (sym = 0; sym < codes; sym++) {
10945     if (lens[lens_index + sym] !== 0) {
10946       work[offs[lens[lens_index + sym]]++] = sym;
10947     }
10948   }
10949
10950   /*
10951    Create and fill in decoding tables.  In this loop, the table being
10952    filled is at next and has curr index bits.  The code being used is huff
10953    with length len.  That code is converted to an index by dropping drop
10954    bits off of the bottom.  For codes where len is less than drop + curr,
10955    those top drop + curr - len bits are incremented through all values to
10956    fill the table with replicated entries.
10957
10958    root is the number of index bits for the root table.  When len exceeds
10959    root, sub-tables are created pointed to by the root entry with an index
10960    of the low root bits of huff.  This is saved in low to check for when a
10961    new sub-table should be started.  drop is zero when the root table is
10962    being filled, and drop is root when sub-tables are being filled.
10963
10964    When a new sub-table is needed, it is necessary to look ahead in the
10965    code lengths to determine what size sub-table is needed.  The length
10966    counts are used for this, and so count[] is decremented as codes are
10967    entered in the tables.
10968
10969    used keeps track of how many table entries have been allocated from the
10970    provided *table space.  It is checked for LENS and DIST tables against
10971    the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
10972    the initial root table size constants.  See the comments in inftrees.h
10973    for more information.
10974
10975    sym increments through all symbols, and the loop terminates when
10976    all codes of length max, i.e. all codes, have been processed.  This
10977    routine permits incomplete codes, so another loop after this one fills
10978    in the rest of the decoding tables with invalid code markers.
10979    */
10980
10981   /* set up for code type */
10982   // poor man optimization - use if-else instead of switch,
10983   // to avoid deopts in old v8
10984   if (type === CODES) {
10985     base = extra = work;    /* dummy value--not used */
10986     end = 19;
10987
10988   } else if (type === LENS) {
10989     base = lbase;
10990     base_index -= 257;
10991     extra = lext;
10992     extra_index -= 257;
10993     end = 256;
10994
10995   } else {                    /* DISTS */
10996     base = dbase;
10997     extra = dext;
10998     end = -1;
10999   }
11000
11001   /* initialize opts for loop */
11002   huff = 0;                   /* starting code */
11003   sym = 0;                    /* starting code symbol */
11004   len = min;                  /* starting code length */
11005   next = table_index;              /* current table to fill in */
11006   curr = root;                /* current table index bits */
11007   drop = 0;                   /* current bits to drop from code for index */
11008   low = -1;                   /* trigger new sub-table when len > root */
11009   used = 1 << root;          /* use root table entries */
11010   mask = used - 1;            /* mask for comparing low */
11011
11012   /* check available table space */
11013   if ((type === LENS && used > ENOUGH_LENS) ||
11014     (type === DISTS && used > ENOUGH_DISTS)) {
11015     return 1;
11016   }
11017
11018   /* process all codes and make table entries */
11019   for (;;) {
11020     /* create table entry */
11021     here_bits = len - drop;
11022     if (work[sym] < end) {
11023       here_op = 0;
11024       here_val = work[sym];
11025     }
11026     else if (work[sym] > end) {
11027       here_op = extra[extra_index + work[sym]];
11028       here_val = base[base_index + work[sym]];
11029     }
11030     else {
11031       here_op = 32 + 64;         /* end of block */
11032       here_val = 0;
11033     }
11034
11035     /* replicate for those indices with low len bits equal to huff */
11036     incr = 1 << (len - drop);
11037     fill = 1 << curr;
11038     min = fill;                 /* save offset to next table */
11039     do {
11040       fill -= incr;
11041       table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
11042     } while (fill !== 0);
11043
11044     /* backwards increment the len-bit code huff */
11045     incr = 1 << (len - 1);
11046     while (huff & incr) {
11047       incr >>= 1;
11048     }
11049     if (incr !== 0) {
11050       huff &= incr - 1;
11051       huff += incr;
11052     } else {
11053       huff = 0;
11054     }
11055
11056     /* go to next symbol, update count, len */
11057     sym++;
11058     if (--count[len] === 0) {
11059       if (len === max) { break; }
11060       len = lens[lens_index + work[sym]];
11061     }
11062
11063     /* create new sub-table if needed */
11064     if (len > root && (huff & mask) !== low) {
11065       /* if first time, transition to sub-tables */
11066       if (drop === 0) {
11067         drop = root;
11068       }
11069
11070       /* increment past last table */
11071       next += min;            /* here min is 1 << curr */
11072
11073       /* determine length of next table */
11074       curr = len - drop;
11075       left = 1 << curr;
11076       while (curr + drop < max) {
11077         left -= count[curr + drop];
11078         if (left <= 0) { break; }
11079         curr++;
11080         left <<= 1;
11081       }
11082
11083       /* check for enough space */
11084       used += 1 << curr;
11085       if ((type === LENS && used > ENOUGH_LENS) ||
11086         (type === DISTS && used > ENOUGH_DISTS)) {
11087         return 1;
11088       }
11089
11090       /* point entry in root table to sub-table */
11091       low = huff & mask;
11092       /*table.op[low] = curr;
11093       table.bits[low] = root;
11094       table.val[low] = next - opts.table_index;*/
11095       table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
11096     }
11097   }
11098
11099   /* fill in remaining table entry if code is incomplete (guaranteed to have
11100    at most one remaining entry, since if the code is incomplete, the
11101    maximum code length that was allowed to get this far is one bit) */
11102   if (huff !== 0) {
11103     //table.op[next + huff] = 64;            /* invalid code marker */
11104     //table.bits[next + huff] = len - drop;
11105     //table.val[next + huff] = 0;
11106     table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
11107   }
11108
11109   /* set return parameters */
11110   //opts.table_index += used;
11111   opts.bits = root;
11112   return 0;
11113 };
11114
11115 },{"../utils/common":26}],36:[function(require,module,exports){
11116 'use strict';
11117
11118 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
11119 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
11120 //
11121 // This software is provided 'as-is', without any express or implied
11122 // warranty. In no event will the authors be held liable for any damages
11123 // arising from the use of this software.
11124 //
11125 // Permission is granted to anyone to use this software for any purpose,
11126 // including commercial applications, and to alter it and redistribute it
11127 // freely, subject to the following restrictions:
11128 //
11129 // 1. The origin of this software must not be misrepresented; you must not
11130 //   claim that you wrote the original software. If you use this software
11131 //   in a product, an acknowledgment in the product documentation would be
11132 //   appreciated but is not required.
11133 // 2. Altered source versions must be plainly marked as such, and must not be
11134 //   misrepresented as being the original software.
11135 // 3. This notice may not be removed or altered from any source distribution.
11136
11137 module.exports = {
11138   2:      'need dictionary',     /* Z_NEED_DICT       2  */
11139   1:      'stream end',          /* Z_STREAM_END      1  */
11140   0:      '',                    /* Z_OK              0  */
11141   '-1':   'file error',          /* Z_ERRNO         (-1) */
11142   '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
11143   '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
11144   '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
11145   '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
11146   '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
11147 };
11148
11149 },{}],37:[function(require,module,exports){
11150 'use strict';
11151
11152 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
11153 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
11154 //
11155 // This software is provided 'as-is', without any express or implied
11156 // warranty. In no event will the authors be held liable for any damages
11157 // arising from the use of this software.
11158 //
11159 // Permission is granted to anyone to use this software for any purpose,
11160 // including commercial applications, and to alter it and redistribute it
11161 // freely, subject to the following restrictions:
11162 //
11163 // 1. The origin of this software must not be misrepresented; you must not
11164 //   claim that you wrote the original software. If you use this software
11165 //   in a product, an acknowledgment in the product documentation would be
11166 //   appreciated but is not required.
11167 // 2. Altered source versions must be plainly marked as such, and must not be
11168 //   misrepresented as being the original software.
11169 // 3. This notice may not be removed or altered from any source distribution.
11170
11171 /* eslint-disable space-unary-ops */
11172
11173 var utils = require('../utils/common');
11174
11175 /* Public constants ==========================================================*/
11176 /* ===========================================================================*/
11177
11178
11179 //var Z_FILTERED          = 1;
11180 //var Z_HUFFMAN_ONLY      = 2;
11181 //var Z_RLE               = 3;
11182 var Z_FIXED               = 4;
11183 //var Z_DEFAULT_STRATEGY  = 0;
11184
11185 /* Possible values of the data_type field (though see inflate()) */
11186 var Z_BINARY              = 0;
11187 var Z_TEXT                = 1;
11188 //var Z_ASCII             = 1; // = Z_TEXT
11189 var Z_UNKNOWN             = 2;
11190
11191 /*============================================================================*/
11192
11193
11194 function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
11195
11196 // From zutil.h
11197
11198 var STORED_BLOCK = 0;
11199 var STATIC_TREES = 1;
11200 var DYN_TREES    = 2;
11201 /* The three kinds of block type */
11202
11203 var MIN_MATCH    = 3;
11204 var MAX_MATCH    = 258;
11205 /* The minimum and maximum match lengths */
11206
11207 // From deflate.h
11208 /* ===========================================================================
11209  * Internal compression state.
11210  */
11211
11212 var LENGTH_CODES  = 29;
11213 /* number of length codes, not counting the special END_BLOCK code */
11214
11215 var LITERALS      = 256;
11216 /* number of literal bytes 0..255 */
11217
11218 var L_CODES       = LITERALS + 1 + LENGTH_CODES;
11219 /* number of Literal or Length codes, including the END_BLOCK code */
11220
11221 var D_CODES       = 30;
11222 /* number of distance codes */
11223
11224 var BL_CODES      = 19;
11225 /* number of codes used to transfer the bit lengths */
11226
11227 var HEAP_SIZE     = 2 * L_CODES + 1;
11228 /* maximum heap size */
11229
11230 var MAX_BITS      = 15;
11231 /* All codes must not exceed MAX_BITS bits */
11232
11233 var Buf_size      = 16;
11234 /* size of bit buffer in bi_buf */
11235
11236
11237 /* ===========================================================================
11238  * Constants
11239  */
11240
11241 var MAX_BL_BITS = 7;
11242 /* Bit length codes must not exceed MAX_BL_BITS bits */
11243
11244 var END_BLOCK   = 256;
11245 /* end of block literal code */
11246
11247 var REP_3_6     = 16;
11248 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
11249
11250 var REPZ_3_10   = 17;
11251 /* repeat a zero length 3-10 times  (3 bits of repeat count) */
11252
11253 var REPZ_11_138 = 18;
11254 /* repeat a zero length 11-138 times  (7 bits of repeat count) */
11255
11256 /* eslint-disable comma-spacing,array-bracket-spacing */
11257 var extra_lbits =   /* extra bits for each length code */
11258   [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
11259
11260 var extra_dbits =   /* extra bits for each distance code */
11261   [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
11262
11263 var extra_blbits =  /* extra bits for each bit length code */
11264   [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
11265
11266 var bl_order =
11267   [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
11268 /* eslint-enable comma-spacing,array-bracket-spacing */
11269
11270 /* The lengths of the bit length codes are sent in order of decreasing
11271  * probability, to avoid transmitting the lengths for unused bit length codes.
11272  */
11273
11274 /* ===========================================================================
11275  * Local data. These are initialized only once.
11276  */
11277
11278 // We pre-fill arrays with 0 to avoid uninitialized gaps
11279
11280 var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
11281
11282 // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
11283 var static_ltree  = new Array((L_CODES + 2) * 2);
11284 zero(static_ltree);
11285 /* The static literal tree. Since the bit lengths are imposed, there is no
11286  * need for the L_CODES extra codes used during heap construction. However
11287  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
11288  * below).
11289  */
11290
11291 var static_dtree  = new Array(D_CODES * 2);
11292 zero(static_dtree);
11293 /* The static distance tree. (Actually a trivial tree since all codes use
11294  * 5 bits.)
11295  */
11296
11297 var _dist_code    = new Array(DIST_CODE_LEN);
11298 zero(_dist_code);
11299 /* Distance codes. The first 256 values correspond to the distances
11300  * 3 .. 258, the last 256 values correspond to the top 8 bits of
11301  * the 15 bit distances.
11302  */
11303
11304 var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
11305 zero(_length_code);
11306 /* length code for each normalized match length (0 == MIN_MATCH) */
11307
11308 var base_length   = new Array(LENGTH_CODES);
11309 zero(base_length);
11310 /* First normalized length for each code (0 = MIN_MATCH) */
11311
11312 var base_dist     = new Array(D_CODES);
11313 zero(base_dist);
11314 /* First normalized distance for each code (0 = distance of 1) */
11315
11316
11317 function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
11318
11319   this.static_tree  = static_tree;  /* static tree or NULL */
11320   this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
11321   this.extra_base   = extra_base;   /* base index for extra_bits */
11322   this.elems        = elems;        /* max number of elements in the tree */
11323   this.max_length   = max_length;   /* max bit length for the codes */
11324
11325   // show if `static_tree` has data or dummy - needed for monomorphic objects
11326   this.has_stree    = static_tree && static_tree.length;
11327 }
11328
11329
11330 var static_l_desc;
11331 var static_d_desc;
11332 var static_bl_desc;
11333
11334
11335 function TreeDesc(dyn_tree, stat_desc) {
11336   this.dyn_tree = dyn_tree;     /* the dynamic tree */
11337   this.max_code = 0;            /* largest code with non zero frequency */
11338   this.stat_desc = stat_desc;   /* the corresponding static tree */
11339 }
11340
11341
11342
11343 function d_code(dist) {
11344   return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
11345 }
11346
11347
11348 /* ===========================================================================
11349  * Output a short LSB first on the stream.
11350  * IN assertion: there is enough room in pendingBuf.
11351  */
11352 function put_short(s, w) {
11353 //    put_byte(s, (uch)((w) & 0xff));
11354 //    put_byte(s, (uch)((ush)(w) >> 8));
11355   s.pending_buf[s.pending++] = (w) & 0xff;
11356   s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
11357 }
11358
11359
11360 /* ===========================================================================
11361  * Send a value on a given number of bits.
11362  * IN assertion: length <= 16 and value fits in length bits.
11363  */
11364 function send_bits(s, value, length) {
11365   if (s.bi_valid > (Buf_size - length)) {
11366     s.bi_buf |= (value << s.bi_valid) & 0xffff;
11367     put_short(s, s.bi_buf);
11368     s.bi_buf = value >> (Buf_size - s.bi_valid);
11369     s.bi_valid += length - Buf_size;
11370   } else {
11371     s.bi_buf |= (value << s.bi_valid) & 0xffff;
11372     s.bi_valid += length;
11373   }
11374 }
11375
11376
11377 function send_code(s, c, tree) {
11378   send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
11379 }
11380
11381
11382 /* ===========================================================================
11383  * Reverse the first len bits of a code, using straightforward code (a faster
11384  * method would use a table)
11385  * IN assertion: 1 <= len <= 15
11386  */
11387 function bi_reverse(code, len) {
11388   var res = 0;
11389   do {
11390     res |= code & 1;
11391     code >>>= 1;
11392     res <<= 1;
11393   } while (--len > 0);
11394   return res >>> 1;
11395 }
11396
11397
11398 /* ===========================================================================
11399  * Flush the bit buffer, keeping at most 7 bits in it.
11400  */
11401 function bi_flush(s) {
11402   if (s.bi_valid === 16) {
11403     put_short(s, s.bi_buf);
11404     s.bi_buf = 0;
11405     s.bi_valid = 0;
11406
11407   } else if (s.bi_valid >= 8) {
11408     s.pending_buf[s.pending++] = s.bi_buf & 0xff;
11409     s.bi_buf >>= 8;
11410     s.bi_valid -= 8;
11411   }
11412 }
11413
11414
11415 /* ===========================================================================
11416  * Compute the optimal bit lengths for a tree and update the total bit length
11417  * for the current block.
11418  * IN assertion: the fields freq and dad are set, heap[heap_max] and
11419  *    above are the tree nodes sorted by increasing frequency.
11420  * OUT assertions: the field len is set to the optimal bit length, the
11421  *     array bl_count contains the frequencies for each bit length.
11422  *     The length opt_len is updated; static_len is also updated if stree is
11423  *     not null.
11424  */
11425 function gen_bitlen(s, desc)
11426 //    deflate_state *s;
11427 //    tree_desc *desc;    /* the tree descriptor */
11428 {
11429   var tree            = desc.dyn_tree;
11430   var max_code        = desc.max_code;
11431   var stree           = desc.stat_desc.static_tree;
11432   var has_stree       = desc.stat_desc.has_stree;
11433   var extra           = desc.stat_desc.extra_bits;
11434   var base            = desc.stat_desc.extra_base;
11435   var max_length      = desc.stat_desc.max_length;
11436   var h;              /* heap index */
11437   var n, m;           /* iterate over the tree elements */
11438   var bits;           /* bit length */
11439   var xbits;          /* extra bits */
11440   var f;              /* frequency */
11441   var overflow = 0;   /* number of elements with bit length too large */
11442
11443   for (bits = 0; bits <= MAX_BITS; bits++) {
11444     s.bl_count[bits] = 0;
11445   }
11446
11447   /* In a first pass, compute the optimal bit lengths (which may
11448    * overflow in the case of the bit length tree).
11449    */
11450   tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
11451
11452   for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
11453     n = s.heap[h];
11454     bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
11455     if (bits > max_length) {
11456       bits = max_length;
11457       overflow++;
11458     }
11459     tree[n * 2 + 1]/*.Len*/ = bits;
11460     /* We overwrite tree[n].Dad which is no longer needed */
11461
11462     if (n > max_code) { continue; } /* not a leaf node */
11463
11464     s.bl_count[bits]++;
11465     xbits = 0;
11466     if (n >= base) {
11467       xbits = extra[n - base];
11468     }
11469     f = tree[n * 2]/*.Freq*/;
11470     s.opt_len += f * (bits + xbits);
11471     if (has_stree) {
11472       s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
11473     }
11474   }
11475   if (overflow === 0) { return; }
11476
11477   // Trace((stderr,"\nbit length overflow\n"));
11478   /* This happens for example on obj2 and pic of the Calgary corpus */
11479
11480   /* Find the first bit length which could increase: */
11481   do {
11482     bits = max_length - 1;
11483     while (s.bl_count[bits] === 0) { bits--; }
11484     s.bl_count[bits]--;      /* move one leaf down the tree */
11485     s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
11486     s.bl_count[max_length]--;
11487     /* The brother of the overflow item also moves one step up,
11488      * but this does not affect bl_count[max_length]
11489      */
11490     overflow -= 2;
11491   } while (overflow > 0);
11492
11493   /* Now recompute all bit lengths, scanning in increasing frequency.
11494    * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
11495    * lengths instead of fixing only the wrong ones. This idea is taken
11496    * from 'ar' written by Haruhiko Okumura.)
11497    */
11498   for (bits = max_length; bits !== 0; bits--) {
11499     n = s.bl_count[bits];
11500     while (n !== 0) {
11501       m = s.heap[--h];
11502       if (m > max_code) { continue; }
11503       if (tree[m * 2 + 1]/*.Len*/ !== bits) {
11504         // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
11505         s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
11506         tree[m * 2 + 1]/*.Len*/ = bits;
11507       }
11508       n--;
11509     }
11510   }
11511 }
11512
11513
11514 /* ===========================================================================
11515  * Generate the codes for a given tree and bit counts (which need not be
11516  * optimal).
11517  * IN assertion: the array bl_count contains the bit length statistics for
11518  * the given tree and the field len is set for all tree elements.
11519  * OUT assertion: the field code is set for all tree elements of non
11520  *     zero code length.
11521  */
11522 function gen_codes(tree, max_code, bl_count)
11523 //    ct_data *tree;             /* the tree to decorate */
11524 //    int max_code;              /* largest code with non zero frequency */
11525 //    ushf *bl_count;            /* number of codes at each bit length */
11526 {
11527   var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
11528   var code = 0;              /* running code value */
11529   var bits;                  /* bit index */
11530   var n;                     /* code index */
11531
11532   /* The distribution counts are first used to generate the code values
11533    * without bit reversal.
11534    */
11535   for (bits = 1; bits <= MAX_BITS; bits++) {
11536     next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
11537   }
11538   /* Check that the bit counts in bl_count are consistent. The last code
11539    * must be all ones.
11540    */
11541   //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
11542   //        "inconsistent bit counts");
11543   //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
11544
11545   for (n = 0;  n <= max_code; n++) {
11546     var len = tree[n * 2 + 1]/*.Len*/;
11547     if (len === 0) { continue; }
11548     /* Now reverse the bits */
11549     tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
11550
11551     //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
11552     //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
11553   }
11554 }
11555
11556
11557 /* ===========================================================================
11558  * Initialize the various 'constant' tables.
11559  */
11560 function tr_static_init() {
11561   var n;        /* iterates over tree elements */
11562   var bits;     /* bit counter */
11563   var length;   /* length value */
11564   var code;     /* code value */
11565   var dist;     /* distance index */
11566   var bl_count = new Array(MAX_BITS + 1);
11567   /* number of codes at each bit length for an optimal tree */
11568
11569   // do check in _tr_init()
11570   //if (static_init_done) return;
11571
11572   /* For some embedded targets, global variables are not initialized: */
11573 /*#ifdef NO_INIT_GLOBAL_POINTERS
11574   static_l_desc.static_tree = static_ltree;
11575   static_l_desc.extra_bits = extra_lbits;
11576   static_d_desc.static_tree = static_dtree;
11577   static_d_desc.extra_bits = extra_dbits;
11578   static_bl_desc.extra_bits = extra_blbits;
11579 #endif*/
11580
11581   /* Initialize the mapping length (0..255) -> length code (0..28) */
11582   length = 0;
11583   for (code = 0; code < LENGTH_CODES - 1; code++) {
11584     base_length[code] = length;
11585     for (n = 0; n < (1 << extra_lbits[code]); n++) {
11586       _length_code[length++] = code;
11587     }
11588   }
11589   //Assert (length == 256, "tr_static_init: length != 256");
11590   /* Note that the length 255 (match length 258) can be represented
11591    * in two different ways: code 284 + 5 bits or code 285, so we
11592    * overwrite length_code[255] to use the best encoding:
11593    */
11594   _length_code[length - 1] = code;
11595
11596   /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
11597   dist = 0;
11598   for (code = 0; code < 16; code++) {
11599     base_dist[code] = dist;
11600     for (n = 0; n < (1 << extra_dbits[code]); n++) {
11601       _dist_code[dist++] = code;
11602     }
11603   }
11604   //Assert (dist == 256, "tr_static_init: dist != 256");
11605   dist >>= 7; /* from now on, all distances are divided by 128 */
11606   for (; code < D_CODES; code++) {
11607     base_dist[code] = dist << 7;
11608     for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
11609       _dist_code[256 + dist++] = code;
11610     }
11611   }
11612   //Assert (dist == 256, "tr_static_init: 256+dist != 512");
11613
11614   /* Construct the codes of the static literal tree */
11615   for (bits = 0; bits <= MAX_BITS; bits++) {
11616     bl_count[bits] = 0;
11617   }
11618
11619   n = 0;
11620   while (n <= 143) {
11621     static_ltree[n * 2 + 1]/*.Len*/ = 8;
11622     n++;
11623     bl_count[8]++;
11624   }
11625   while (n <= 255) {
11626     static_ltree[n * 2 + 1]/*.Len*/ = 9;
11627     n++;
11628     bl_count[9]++;
11629   }
11630   while (n <= 279) {
11631     static_ltree[n * 2 + 1]/*.Len*/ = 7;
11632     n++;
11633     bl_count[7]++;
11634   }
11635   while (n <= 287) {
11636     static_ltree[n * 2 + 1]/*.Len*/ = 8;
11637     n++;
11638     bl_count[8]++;
11639   }
11640   /* Codes 286 and 287 do not exist, but we must include them in the
11641    * tree construction to get a canonical Huffman tree (longest code
11642    * all ones)
11643    */
11644   gen_codes(static_ltree, L_CODES + 1, bl_count);
11645
11646   /* The static distance tree is trivial: */
11647   for (n = 0; n < D_CODES; n++) {
11648     static_dtree[n * 2 + 1]/*.Len*/ = 5;
11649     static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
11650   }
11651
11652   // Now data ready and we can init static trees
11653   static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
11654   static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
11655   static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);
11656
11657   //static_init_done = true;
11658 }
11659
11660
11661 /* ===========================================================================
11662  * Initialize a new block.
11663  */
11664 function init_block(s) {
11665   var n; /* iterates over tree elements */
11666
11667   /* Initialize the trees. */
11668   for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
11669   for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
11670   for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
11671
11672   s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
11673   s.opt_len = s.static_len = 0;
11674   s.last_lit = s.matches = 0;
11675 }
11676
11677
11678 /* ===========================================================================
11679  * Flush the bit buffer and align the output on a byte boundary
11680  */
11681 function bi_windup(s)
11682 {
11683   if (s.bi_valid > 8) {
11684     put_short(s, s.bi_buf);
11685   } else if (s.bi_valid > 0) {
11686     //put_byte(s, (Byte)s->bi_buf);
11687     s.pending_buf[s.pending++] = s.bi_buf;
11688   }
11689   s.bi_buf = 0;
11690   s.bi_valid = 0;
11691 }
11692
11693 /* ===========================================================================
11694  * Copy a stored block, storing first the length and its
11695  * one's complement if requested.
11696  */
11697 function copy_block(s, buf, len, header)
11698 //DeflateState *s;
11699 //charf    *buf;    /* the input data */
11700 //unsigned len;     /* its length */
11701 //int      header;  /* true if block header must be written */
11702 {
11703   bi_windup(s);        /* align on byte boundary */
11704
11705   if (header) {
11706     put_short(s, len);
11707     put_short(s, ~len);
11708   }
11709 //  while (len--) {
11710 //    put_byte(s, *buf++);
11711 //  }
11712   utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
11713   s.pending += len;
11714 }
11715
11716 /* ===========================================================================
11717  * Compares to subtrees, using the tree depth as tie breaker when
11718  * the subtrees have equal frequency. This minimizes the worst case length.
11719  */
11720 function smaller(tree, n, m, depth) {
11721   var _n2 = n * 2;
11722   var _m2 = m * 2;
11723   return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
11724          (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
11725 }
11726
11727 /* ===========================================================================
11728  * Restore the heap property by moving down the tree starting at node k,
11729  * exchanging a node with the smallest of its two sons if necessary, stopping
11730  * when the heap property is re-established (each father smaller than its
11731  * two sons).
11732  */
11733 function pqdownheap(s, tree, k)
11734 //    deflate_state *s;
11735 //    ct_data *tree;  /* the tree to restore */
11736 //    int k;               /* node to move down */
11737 {
11738   var v = s.heap[k];
11739   var j = k << 1;  /* left son of k */
11740   while (j <= s.heap_len) {
11741     /* Set j to the smallest of the two sons: */
11742     if (j < s.heap_len &&
11743       smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
11744       j++;
11745     }
11746     /* Exit if v is smaller than both sons */
11747     if (smaller(tree, v, s.heap[j], s.depth)) { break; }
11748
11749     /* Exchange v with the smallest son */
11750     s.heap[k] = s.heap[j];
11751     k = j;
11752
11753     /* And continue down the tree, setting j to the left son of k */
11754     j <<= 1;
11755   }
11756   s.heap[k] = v;
11757 }
11758
11759
11760 // inlined manually
11761 // var SMALLEST = 1;
11762
11763 /* ===========================================================================
11764  * Send the block data compressed using the given Huffman trees
11765  */
11766 function compress_block(s, ltree, dtree)
11767 //    deflate_state *s;
11768 //    const ct_data *ltree; /* literal tree */
11769 //    const ct_data *dtree; /* distance tree */
11770 {
11771   var dist;           /* distance of matched string */
11772   var lc;             /* match length or unmatched char (if dist == 0) */
11773   var lx = 0;         /* running index in l_buf */
11774   var code;           /* the code to send */
11775   var extra;          /* number of extra bits to send */
11776
11777   if (s.last_lit !== 0) {
11778     do {
11779       dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
11780       lc = s.pending_buf[s.l_buf + lx];
11781       lx++;
11782
11783       if (dist === 0) {
11784         send_code(s, lc, ltree); /* send a literal byte */
11785         //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
11786       } else {
11787         /* Here, lc is the match length - MIN_MATCH */
11788         code = _length_code[lc];
11789         send_code(s, code + LITERALS + 1, ltree); /* send the length code */
11790         extra = extra_lbits[code];
11791         if (extra !== 0) {
11792           lc -= base_length[code];
11793           send_bits(s, lc, extra);       /* send the extra length bits */
11794         }
11795         dist--; /* dist is now the match distance - 1 */
11796         code = d_code(dist);
11797         //Assert (code < D_CODES, "bad d_code");
11798
11799         send_code(s, code, dtree);       /* send the distance code */
11800         extra = extra_dbits[code];
11801         if (extra !== 0) {
11802           dist -= base_dist[code];
11803           send_bits(s, dist, extra);   /* send the extra distance bits */
11804         }
11805       } /* literal or match pair ? */
11806
11807       /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
11808       //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
11809       //       "pendingBuf overflow");
11810
11811     } while (lx < s.last_lit);
11812   }
11813
11814   send_code(s, END_BLOCK, ltree);
11815 }
11816
11817
11818 /* ===========================================================================
11819  * Construct one Huffman tree and assigns the code bit strings and lengths.
11820  * Update the total bit length for the current block.
11821  * IN assertion: the field freq is set for all tree elements.
11822  * OUT assertions: the fields len and code are set to the optimal bit length
11823  *     and corresponding code. The length opt_len is updated; static_len is
11824  *     also updated if stree is not null. The field max_code is set.
11825  */
11826 function build_tree(s, desc)
11827 //    deflate_state *s;
11828 //    tree_desc *desc; /* the tree descriptor */
11829 {
11830   var tree     = desc.dyn_tree;
11831   var stree    = desc.stat_desc.static_tree;
11832   var has_stree = desc.stat_desc.has_stree;
11833   var elems    = desc.stat_desc.elems;
11834   var n, m;          /* iterate over heap elements */
11835   var max_code = -1; /* largest code with non zero frequency */
11836   var node;          /* new node being created */
11837
11838   /* Construct the initial heap, with least frequent element in
11839    * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
11840    * heap[0] is not used.
11841    */
11842   s.heap_len = 0;
11843   s.heap_max = HEAP_SIZE;
11844
11845   for (n = 0; n < elems; n++) {
11846     if (tree[n * 2]/*.Freq*/ !== 0) {
11847       s.heap[++s.heap_len] = max_code = n;
11848       s.depth[n] = 0;
11849
11850     } else {
11851       tree[n * 2 + 1]/*.Len*/ = 0;
11852     }
11853   }
11854
11855   /* The pkzip format requires that at least one distance code exists,
11856    * and that at least one bit should be sent even if there is only one
11857    * possible code. So to avoid special checks later on we force at least
11858    * two codes of non zero frequency.
11859    */
11860   while (s.heap_len < 2) {
11861     node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
11862     tree[node * 2]/*.Freq*/ = 1;
11863     s.depth[node] = 0;
11864     s.opt_len--;
11865
11866     if (has_stree) {
11867       s.static_len -= stree[node * 2 + 1]/*.Len*/;
11868     }
11869     /* node is 0 or 1 so it does not have extra bits */
11870   }
11871   desc.max_code = max_code;
11872
11873   /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
11874    * establish sub-heaps of increasing lengths:
11875    */
11876   for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
11877
11878   /* Construct the Huffman tree by repeatedly combining the least two
11879    * frequent nodes.
11880    */
11881   node = elems;              /* next internal node of the tree */
11882   do {
11883     //pqremove(s, tree, n);  /* n = node of least frequency */
11884     /*** pqremove ***/
11885     n = s.heap[1/*SMALLEST*/];
11886     s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
11887     pqdownheap(s, tree, 1/*SMALLEST*/);
11888     /***/
11889
11890     m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
11891
11892     s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
11893     s.heap[--s.heap_max] = m;
11894
11895     /* Create a new node father of n and m */
11896     tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
11897     s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
11898     tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
11899
11900     /* and insert the new node in the heap */
11901     s.heap[1/*SMALLEST*/] = node++;
11902     pqdownheap(s, tree, 1/*SMALLEST*/);
11903
11904   } while (s.heap_len >= 2);
11905
11906   s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
11907
11908   /* At this point, the fields freq and dad are set. We can now
11909    * generate the bit lengths.
11910    */
11911   gen_bitlen(s, desc);
11912
11913   /* The field len is now set, we can generate the bit codes */
11914   gen_codes(tree, max_code, s.bl_count);
11915 }
11916
11917
11918 /* ===========================================================================
11919  * Scan a literal or distance tree to determine the frequencies of the codes
11920  * in the bit length tree.
11921  */
11922 function scan_tree(s, tree, max_code)
11923 //    deflate_state *s;
11924 //    ct_data *tree;   /* the tree to be scanned */
11925 //    int max_code;    /* and its largest code of non zero frequency */
11926 {
11927   var n;                     /* iterates over all tree elements */
11928   var prevlen = -1;          /* last emitted length */
11929   var curlen;                /* length of current code */
11930
11931   var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
11932
11933   var count = 0;             /* repeat count of the current code */
11934   var max_count = 7;         /* max repeat count */
11935   var min_count = 4;         /* min repeat count */
11936
11937   if (nextlen === 0) {
11938     max_count = 138;
11939     min_count = 3;
11940   }
11941   tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
11942
11943   for (n = 0; n <= max_code; n++) {
11944     curlen = nextlen;
11945     nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
11946
11947     if (++count < max_count && curlen === nextlen) {
11948       continue;
11949
11950     } else if (count < min_count) {
11951       s.bl_tree[curlen * 2]/*.Freq*/ += count;
11952
11953     } else if (curlen !== 0) {
11954
11955       if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
11956       s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
11957
11958     } else if (count <= 10) {
11959       s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
11960
11961     } else {
11962       s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
11963     }
11964
11965     count = 0;
11966     prevlen = curlen;
11967
11968     if (nextlen === 0) {
11969       max_count = 138;
11970       min_count = 3;
11971
11972     } else if (curlen === nextlen) {
11973       max_count = 6;
11974       min_count = 3;
11975
11976     } else {
11977       max_count = 7;
11978       min_count = 4;
11979     }
11980   }
11981 }
11982
11983
11984 /* ===========================================================================
11985  * Send a literal or distance tree in compressed form, using the codes in
11986  * bl_tree.
11987  */
11988 function send_tree(s, tree, max_code)
11989 //    deflate_state *s;
11990 //    ct_data *tree; /* the tree to be scanned */
11991 //    int max_code;       /* and its largest code of non zero frequency */
11992 {
11993   var n;                     /* iterates over all tree elements */
11994   var prevlen = -1;          /* last emitted length */
11995   var curlen;                /* length of current code */
11996
11997   var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
11998
11999   var count = 0;             /* repeat count of the current code */
12000   var max_count = 7;         /* max repeat count */
12001   var min_count = 4;         /* min repeat count */
12002
12003   /* tree[max_code+1].Len = -1; */  /* guard already set */
12004   if (nextlen === 0) {
12005     max_count = 138;
12006     min_count = 3;
12007   }
12008
12009   for (n = 0; n <= max_code; n++) {
12010     curlen = nextlen;
12011     nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
12012
12013     if (++count < max_count && curlen === nextlen) {
12014       continue;
12015
12016     } else if (count < min_count) {
12017       do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
12018
12019     } else if (curlen !== 0) {
12020       if (curlen !== prevlen) {
12021         send_code(s, curlen, s.bl_tree);
12022         count--;
12023       }
12024       //Assert(count >= 3 && count <= 6, " 3_6?");
12025       send_code(s, REP_3_6, s.bl_tree);
12026       send_bits(s, count - 3, 2);
12027
12028     } else if (count <= 10) {
12029       send_code(s, REPZ_3_10, s.bl_tree);
12030       send_bits(s, count - 3, 3);
12031
12032     } else {
12033       send_code(s, REPZ_11_138, s.bl_tree);
12034       send_bits(s, count - 11, 7);
12035     }
12036
12037     count = 0;
12038     prevlen = curlen;
12039     if (nextlen === 0) {
12040       max_count = 138;
12041       min_count = 3;
12042
12043     } else if (curlen === nextlen) {
12044       max_count = 6;
12045       min_count = 3;
12046
12047     } else {
12048       max_count = 7;
12049       min_count = 4;
12050     }
12051   }
12052 }
12053
12054
12055 /* ===========================================================================
12056  * Construct the Huffman tree for the bit lengths and return the index in
12057  * bl_order of the last bit length code to send.
12058  */
12059 function build_bl_tree(s) {
12060   var max_blindex;  /* index of last bit length code of non zero freq */
12061
12062   /* Determine the bit length frequencies for literal and distance trees */
12063   scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
12064   scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
12065
12066   /* Build the bit length tree: */
12067   build_tree(s, s.bl_desc);
12068   /* opt_len now includes the length of the tree representations, except
12069    * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
12070    */
12071
12072   /* Determine the number of bit length codes to send. The pkzip format
12073    * requires that at least 4 bit length codes be sent. (appnote.txt says
12074    * 3 but the actual value used is 4.)
12075    */
12076   for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
12077     if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
12078       break;
12079     }
12080   }
12081   /* Update opt_len to include the bit length tree and counts */
12082   s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
12083   //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
12084   //        s->opt_len, s->static_len));
12085
12086   return max_blindex;
12087 }
12088
12089
12090 /* ===========================================================================
12091  * Send the header for a block using dynamic Huffman trees: the counts, the
12092  * lengths of the bit length codes, the literal tree and the distance tree.
12093  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
12094  */
12095 function send_all_trees(s, lcodes, dcodes, blcodes)
12096 //    deflate_state *s;
12097 //    int lcodes, dcodes, blcodes; /* number of codes for each tree */
12098 {
12099   var rank;                    /* index in bl_order */
12100
12101   //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
12102   //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
12103   //        "too many codes");
12104   //Tracev((stderr, "\nbl counts: "));
12105   send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
12106   send_bits(s, dcodes - 1,   5);
12107   send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
12108   for (rank = 0; rank < blcodes; rank++) {
12109     //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
12110     send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
12111   }
12112   //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
12113
12114   send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
12115   //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
12116
12117   send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
12118   //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
12119 }
12120
12121
12122 /* ===========================================================================
12123  * Check if the data type is TEXT or BINARY, using the following algorithm:
12124  * - TEXT if the two conditions below are satisfied:
12125  *    a) There are no non-portable control characters belonging to the
12126  *       "black list" (0..6, 14..25, 28..31).
12127  *    b) There is at least one printable character belonging to the
12128  *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
12129  * - BINARY otherwise.
12130  * - The following partially-portable control characters form a
12131  *   "gray list" that is ignored in this detection algorithm:
12132  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
12133  * IN assertion: the fields Freq of dyn_ltree are set.
12134  */
12135 function detect_data_type(s) {
12136   /* black_mask is the bit mask of black-listed bytes
12137    * set bits 0..6, 14..25, and 28..31
12138    * 0xf3ffc07f = binary 11110011111111111100000001111111
12139    */
12140   var black_mask = 0xf3ffc07f;
12141   var n;
12142
12143   /* Check for non-textual ("black-listed") bytes. */
12144   for (n = 0; n <= 31; n++, black_mask >>>= 1) {
12145     if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
12146       return Z_BINARY;
12147     }
12148   }
12149
12150   /* Check for textual ("white-listed") bytes. */
12151   if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
12152       s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
12153     return Z_TEXT;
12154   }
12155   for (n = 32; n < LITERALS; n++) {
12156     if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
12157       return Z_TEXT;
12158     }
12159   }
12160
12161   /* There are no "black-listed" or "white-listed" bytes:
12162    * this stream either is empty or has tolerated ("gray-listed") bytes only.
12163    */
12164   return Z_BINARY;
12165 }
12166
12167
12168 var static_init_done = false;
12169
12170 /* ===========================================================================
12171  * Initialize the tree data structures for a new zlib stream.
12172  */
12173 function _tr_init(s)
12174 {
12175
12176   if (!static_init_done) {
12177     tr_static_init();
12178     static_init_done = true;
12179   }
12180
12181   s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
12182   s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
12183   s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
12184
12185   s.bi_buf = 0;
12186   s.bi_valid = 0;
12187
12188   /* Initialize the first block of the first file: */
12189   init_block(s);
12190 }
12191
12192
12193 /* ===========================================================================
12194  * Send a stored block
12195  */
12196 function _tr_stored_block(s, buf, stored_len, last)
12197 //DeflateState *s;
12198 //charf *buf;       /* input block */
12199 //ulg stored_len;   /* length of input block */
12200 //int last;         /* one if this is the last block for a file */
12201 {
12202   send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
12203   copy_block(s, buf, stored_len, true); /* with header */
12204 }
12205
12206
12207 /* ===========================================================================
12208  * Send one empty static block to give enough lookahead for inflate.
12209  * This takes 10 bits, of which 7 may remain in the bit buffer.
12210  */
12211 function _tr_align(s) {
12212   send_bits(s, STATIC_TREES << 1, 3);
12213   send_code(s, END_BLOCK, static_ltree);
12214   bi_flush(s);
12215 }
12216
12217
12218 /* ===========================================================================
12219  * Determine the best encoding for the current block: dynamic trees, static
12220  * trees or store, and output the encoded block to the zip file.
12221  */
12222 function _tr_flush_block(s, buf, stored_len, last)
12223 //DeflateState *s;
12224 //charf *buf;       /* input block, or NULL if too old */
12225 //ulg stored_len;   /* length of input block */
12226 //int last;         /* one if this is the last block for a file */
12227 {
12228   var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
12229   var max_blindex = 0;        /* index of last bit length code of non zero freq */
12230
12231   /* Build the Huffman trees unless a stored block is forced */
12232   if (s.level > 0) {
12233
12234     /* Check if the file is binary or text */
12235     if (s.strm.data_type === Z_UNKNOWN) {
12236       s.strm.data_type = detect_data_type(s);
12237     }
12238
12239     /* Construct the literal and distance trees */
12240     build_tree(s, s.l_desc);
12241     // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
12242     //        s->static_len));
12243
12244     build_tree(s, s.d_desc);
12245     // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
12246     //        s->static_len));
12247     /* At this point, opt_len and static_len are the total bit lengths of
12248      * the compressed block data, excluding the tree representations.
12249      */
12250
12251     /* Build the bit length tree for the above two trees, and get the index
12252      * in bl_order of the last bit length code to send.
12253      */
12254     max_blindex = build_bl_tree(s);
12255
12256     /* Determine the best encoding. Compute the block lengths in bytes. */
12257     opt_lenb = (s.opt_len + 3 + 7) >>> 3;
12258     static_lenb = (s.static_len + 3 + 7) >>> 3;
12259
12260     // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
12261     //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
12262     //        s->last_lit));
12263
12264     if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
12265
12266   } else {
12267     // Assert(buf != (char*)0, "lost buf");
12268     opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
12269   }
12270
12271   if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
12272     /* 4: two words for the lengths */
12273
12274     /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
12275      * Otherwise we can't have processed more than WSIZE input bytes since
12276      * the last block flush, because compression would have been
12277      * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
12278      * transform a block into a stored block.
12279      */
12280     _tr_stored_block(s, buf, stored_len, last);
12281
12282   } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
12283
12284     send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
12285     compress_block(s, static_ltree, static_dtree);
12286
12287   } else {
12288     send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
12289     send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
12290     compress_block(s, s.dyn_ltree, s.dyn_dtree);
12291   }
12292   // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
12293   /* The above check is made mod 2^32, for files larger than 512 MB
12294    * and uLong implemented on 32 bits.
12295    */
12296   init_block(s);
12297
12298   if (last) {
12299     bi_windup(s);
12300   }
12301   // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
12302   //       s->compressed_len-7*last));
12303 }
12304
12305 /* ===========================================================================
12306  * Save the match info and tally the frequency counts. Return true if
12307  * the current block must be flushed.
12308  */
12309 function _tr_tally(s, dist, lc)
12310 //    deflate_state *s;
12311 //    unsigned dist;  /* distance of matched string */
12312 //    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
12313 {
12314   //var out_length, in_length, dcode;
12315
12316   s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
12317   s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
12318
12319   s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
12320   s.last_lit++;
12321
12322   if (dist === 0) {
12323     /* lc is the unmatched char */
12324     s.dyn_ltree[lc * 2]/*.Freq*/++;
12325   } else {
12326     s.matches++;
12327     /* Here, lc is the match length - MIN_MATCH */
12328     dist--;             /* dist = match distance - 1 */
12329     //Assert((ush)dist < (ush)MAX_DIST(s) &&
12330     //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
12331     //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
12332
12333     s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
12334     s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
12335   }
12336
12337 // (!) This block is disabled in zlib defaults,
12338 // don't enable it for binary compatibility
12339
12340 //#ifdef TRUNCATE_BLOCK
12341 //  /* Try to guess if it is profitable to stop the current block here */
12342 //  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
12343 //    /* Compute an upper bound for the compressed length */
12344 //    out_length = s.last_lit*8;
12345 //    in_length = s.strstart - s.block_start;
12346 //
12347 //    for (dcode = 0; dcode < D_CODES; dcode++) {
12348 //      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
12349 //    }
12350 //    out_length >>>= 3;
12351 //    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
12352 //    //       s->last_lit, in_length, out_length,
12353 //    //       100L - out_length*100L/in_length));
12354 //    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
12355 //      return true;
12356 //    }
12357 //  }
12358 //#endif
12359
12360   return (s.last_lit === s.lit_bufsize - 1);
12361   /* We avoid equality with lit_bufsize because of wraparound at 64K
12362    * on 16 bit machines and because stored blocks are restricted to
12363    * 64K-1 bytes.
12364    */
12365 }
12366
12367 exports._tr_init  = _tr_init;
12368 exports._tr_stored_block = _tr_stored_block;
12369 exports._tr_flush_block  = _tr_flush_block;
12370 exports._tr_tally = _tr_tally;
12371 exports._tr_align = _tr_align;
12372
12373 },{"../utils/common":26}],38:[function(require,module,exports){
12374 'use strict';
12375
12376 // (C) 1995-2013 Jean-loup Gailly and Mark Adler
12377 // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
12378 //
12379 // This software is provided 'as-is', without any express or implied
12380 // warranty. In no event will the authors be held liable for any damages
12381 // arising from the use of this software.
12382 //
12383 // Permission is granted to anyone to use this software for any purpose,
12384 // including commercial applications, and to alter it and redistribute it
12385 // freely, subject to the following restrictions:
12386 //
12387 // 1. The origin of this software must not be misrepresented; you must not
12388 //   claim that you wrote the original software. If you use this software
12389 //   in a product, an acknowledgment in the product documentation would be
12390 //   appreciated but is not required.
12391 // 2. Altered source versions must be plainly marked as such, and must not be
12392 //   misrepresented as being the original software.
12393 // 3. This notice may not be removed or altered from any source distribution.
12394
12395 function ZStream() {
12396   /* next input byte */
12397   this.input = null; // JS specific, because we have no pointers
12398   this.next_in = 0;
12399   /* number of bytes available at input */
12400   this.avail_in = 0;
12401   /* total number of input bytes read so far */
12402   this.total_in = 0;
12403   /* next output byte should be put there */
12404   this.output = null; // JS specific, because we have no pointers
12405   this.next_out = 0;
12406   /* remaining free space at output */
12407   this.avail_out = 0;
12408   /* total number of bytes output so far */
12409   this.total_out = 0;
12410   /* last error message, NULL if no error */
12411   this.msg = ''/*Z_NULL*/;
12412   /* not visible by applications */
12413   this.state = null;
12414   /* best guess about the data type: binary or text */
12415   this.data_type = 2/*Z_UNKNOWN*/;
12416   /* adler32 value of the uncompressed data */
12417   this.adler = 0;
12418 }
12419
12420 module.exports = ZStream;
12421
12422 },{}],39:[function(require,module,exports){
12423 (function (process){
12424 // Copyright Joyent, Inc. and other Node contributors.
12425 //
12426 // Permission is hereby granted, free of charge, to any person obtaining a
12427 // copy of this software and associated documentation files (the
12428 // "Software"), to deal in the Software without restriction, including
12429 // without limitation the rights to use, copy, modify, merge, publish,
12430 // distribute, sublicense, and/or sell copies of the Software, and to permit
12431 // persons to whom the Software is furnished to do so, subject to the
12432 // following conditions:
12433 //
12434 // The above copyright notice and this permission notice shall be included
12435 // in all copies or substantial portions of the Software.
12436 //
12437 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12438 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12439 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12440 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12441 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12442 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12443 // USE OR OTHER DEALINGS IN THE SOFTWARE.
12444
12445 // resolves . and .. elements in a path array with directory names there
12446 // must be no slashes, empty elements, or device names (c:\) in the array
12447 // (so also no leading and trailing slashes - it does not distinguish
12448 // relative and absolute paths)
12449 function normalizeArray(parts, allowAboveRoot) {
12450   // if the path tries to go above the root, `up` ends up > 0
12451   var up = 0;
12452   for (var i = parts.length - 1; i >= 0; i--) {
12453     var last = parts[i];
12454     if (last === '.') {
12455       parts.splice(i, 1);
12456     } else if (last === '..') {
12457       parts.splice(i, 1);
12458       up++;
12459     } else if (up) {
12460       parts.splice(i, 1);
12461       up--;
12462     }
12463   }
12464
12465   // if the path is allowed to go above the root, restore leading ..s
12466   if (allowAboveRoot) {
12467     for (; up--; up) {
12468       parts.unshift('..');
12469     }
12470   }
12471
12472   return parts;
12473 }
12474
12475 // Split a filename into [root, dir, basename, ext], unix version
12476 // 'root' is just a slash, or nothing.
12477 var splitPathRe =
12478     /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
12479 var splitPath = function(filename) {
12480   return splitPathRe.exec(filename).slice(1);
12481 };
12482
12483 // path.resolve([from ...], to)
12484 // posix version
12485 exports.resolve = function() {
12486   var resolvedPath = '',
12487       resolvedAbsolute = false;
12488
12489   for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
12490     var path = (i >= 0) ? arguments[i] : process.cwd();
12491
12492     // Skip empty and invalid entries
12493     if (typeof path !== 'string') {
12494       throw new TypeError('Arguments to path.resolve must be strings');
12495     } else if (!path) {
12496       continue;
12497     }
12498
12499     resolvedPath = path + '/' + resolvedPath;
12500     resolvedAbsolute = path.charAt(0) === '/';
12501   }
12502
12503   // At this point the path should be resolved to a full absolute path, but
12504   // handle relative paths to be safe (might happen when process.cwd() fails)
12505
12506   // Normalize the path
12507   resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
12508     return !!p;
12509   }), !resolvedAbsolute).join('/');
12510
12511   return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
12512 };
12513
12514 // path.normalize(path)
12515 // posix version
12516 exports.normalize = function(path) {
12517   var isAbsolute = exports.isAbsolute(path),
12518       trailingSlash = substr(path, -1) === '/';
12519
12520   // Normalize the path
12521   path = normalizeArray(filter(path.split('/'), function(p) {
12522     return !!p;
12523   }), !isAbsolute).join('/');
12524
12525   if (!path && !isAbsolute) {
12526     path = '.';
12527   }
12528   if (path && trailingSlash) {
12529     path += '/';
12530   }
12531
12532   return (isAbsolute ? '/' : '') + path;
12533 };
12534
12535 // posix version
12536 exports.isAbsolute = function(path) {
12537   return path.charAt(0) === '/';
12538 };
12539
12540 // posix version
12541 exports.join = function() {
12542   var paths = Array.prototype.slice.call(arguments, 0);
12543   return exports.normalize(filter(paths, function(p, index) {
12544     if (typeof p !== 'string') {
12545       throw new TypeError('Arguments to path.join must be strings');
12546     }
12547     return p;
12548   }).join('/'));
12549 };
12550
12551
12552 // path.relative(from, to)
12553 // posix version
12554 exports.relative = function(from, to) {
12555   from = exports.resolve(from).substr(1);
12556   to = exports.resolve(to).substr(1);
12557
12558   function trim(arr) {
12559     var start = 0;
12560     for (; start < arr.length; start++) {
12561       if (arr[start] !== '') break;
12562     }
12563
12564     var end = arr.length - 1;
12565     for (; end >= 0; end--) {
12566       if (arr[end] !== '') break;
12567     }
12568
12569     if (start > end) return [];
12570     return arr.slice(start, end - start + 1);
12571   }
12572
12573   var fromParts = trim(from.split('/'));
12574   var toParts = trim(to.split('/'));
12575
12576   var length = Math.min(fromParts.length, toParts.length);
12577   var samePartsLength = length;
12578   for (var i = 0; i < length; i++) {
12579     if (fromParts[i] !== toParts[i]) {
12580       samePartsLength = i;
12581       break;
12582     }
12583   }
12584
12585   var outputParts = [];
12586   for (var i = samePartsLength; i < fromParts.length; i++) {
12587     outputParts.push('..');
12588   }
12589
12590   outputParts = outputParts.concat(toParts.slice(samePartsLength));
12591
12592   return outputParts.join('/');
12593 };
12594
12595 exports.sep = '/';
12596 exports.delimiter = ':';
12597
12598 exports.dirname = function(path) {
12599   var result = splitPath(path),
12600       root = result[0],
12601       dir = result[1];
12602
12603   if (!root && !dir) {
12604     // No dirname whatsoever
12605     return '.';
12606   }
12607
12608   if (dir) {
12609     // It has a dirname, strip trailing slash
12610     dir = dir.substr(0, dir.length - 1);
12611   }
12612
12613   return root + dir;
12614 };
12615
12616
12617 exports.basename = function(path, ext) {
12618   var f = splitPath(path)[2];
12619   // TODO: make this comparison case-insensitive on windows?
12620   if (ext && f.substr(-1 * ext.length) === ext) {
12621     f = f.substr(0, f.length - ext.length);
12622   }
12623   return f;
12624 };
12625
12626
12627 exports.extname = function(path) {
12628   return splitPath(path)[3];
12629 };
12630
12631 function filter (xs, f) {
12632     if (xs.filter) return xs.filter(f);
12633     var res = [];
12634     for (var i = 0; i < xs.length; i++) {
12635         if (f(xs[i], i, xs)) res.push(xs[i]);
12636     }
12637     return res;
12638 }
12639
12640 // String.prototype.substr - negative index don't work in IE8
12641 var substr = 'ab'.substr(-1) === 'b'
12642     ? function (str, start, len) { return str.substr(start, len) }
12643     : function (str, start, len) {
12644         if (start < 0) start = str.length + start;
12645         return str.substr(start, len);
12646     }
12647 ;
12648
12649 }).call(this,require('_process'))
12650
12651 },{"_process":6}],40:[function(require,module,exports){
12652 'use strict';
12653
12654 module.exports = Pbf;
12655
12656 var ieee754 = require('ieee754');
12657
12658 function Pbf(buf) {
12659     this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
12660     this.pos = 0;
12661     this.type = 0;
12662     this.length = this.buf.length;
12663 }
12664
12665 Pbf.Varint  = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
12666 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
12667 Pbf.Bytes   = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
12668 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
12669
12670 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
12671     SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
12672
12673 Pbf.prototype = {
12674
12675     destroy: function() {
12676         this.buf = null;
12677     },
12678
12679     // === READING =================================================================
12680
12681     readFields: function(readField, result, end) {
12682         end = end || this.length;
12683
12684         while (this.pos < end) {
12685             var val = this.readVarint(),
12686                 tag = val >> 3,
12687                 startPos = this.pos;
12688
12689             this.type = val & 0x7;
12690             readField(tag, result, this);
12691
12692             if (this.pos === startPos) this.skip(val);
12693         }
12694         return result;
12695     },
12696
12697     readMessage: function(readField, result) {
12698         return this.readFields(readField, result, this.readVarint() + this.pos);
12699     },
12700
12701     readFixed32: function() {
12702         var val = readUInt32(this.buf, this.pos);
12703         this.pos += 4;
12704         return val;
12705     },
12706
12707     readSFixed32: function() {
12708         var val = readInt32(this.buf, this.pos);
12709         this.pos += 4;
12710         return val;
12711     },
12712
12713     // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
12714
12715     readFixed64: function() {
12716         var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
12717         this.pos += 8;
12718         return val;
12719     },
12720
12721     readSFixed64: function() {
12722         var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
12723         this.pos += 8;
12724         return val;
12725     },
12726
12727     readFloat: function() {
12728         var val = ieee754.read(this.buf, this.pos, true, 23, 4);
12729         this.pos += 4;
12730         return val;
12731     },
12732
12733     readDouble: function() {
12734         var val = ieee754.read(this.buf, this.pos, true, 52, 8);
12735         this.pos += 8;
12736         return val;
12737     },
12738
12739     readVarint: function(isSigned) {
12740         var buf = this.buf,
12741             val, b;
12742
12743         b = buf[this.pos++]; val  =  b & 0x7f;        if (b < 0x80) return val;
12744         b = buf[this.pos++]; val |= (b & 0x7f) << 7;  if (b < 0x80) return val;
12745         b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
12746         b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
12747         b = buf[this.pos];   val |= (b & 0x0f) << 28;
12748
12749         return readVarintRemainder(val, isSigned, this);
12750     },
12751
12752     readVarint64: function() { // for compatibility with v2.0.1
12753         return this.readVarint(true);
12754     },
12755
12756     readSVarint: function() {
12757         var num = this.readVarint();
12758         return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
12759     },
12760
12761     readBoolean: function() {
12762         return Boolean(this.readVarint());
12763     },
12764
12765     readString: function() {
12766         var end = this.readVarint() + this.pos,
12767             str = readUtf8(this.buf, this.pos, end);
12768         this.pos = end;
12769         return str;
12770     },
12771
12772     readBytes: function() {
12773         var end = this.readVarint() + this.pos,
12774             buffer = this.buf.subarray(this.pos, end);
12775         this.pos = end;
12776         return buffer;
12777     },
12778
12779     // verbose for performance reasons; doesn't affect gzipped size
12780
12781     readPackedVarint: function(arr, isSigned) {
12782         var end = readPackedEnd(this);
12783         arr = arr || [];
12784         while (this.pos < end) arr.push(this.readVarint(isSigned));
12785         return arr;
12786     },
12787     readPackedSVarint: function(arr) {
12788         var end = readPackedEnd(this);
12789         arr = arr || [];
12790         while (this.pos < end) arr.push(this.readSVarint());
12791         return arr;
12792     },
12793     readPackedBoolean: function(arr) {
12794         var end = readPackedEnd(this);
12795         arr = arr || [];
12796         while (this.pos < end) arr.push(this.readBoolean());
12797         return arr;
12798     },
12799     readPackedFloat: function(arr) {
12800         var end = readPackedEnd(this);
12801         arr = arr || [];
12802         while (this.pos < end) arr.push(this.readFloat());
12803         return arr;
12804     },
12805     readPackedDouble: function(arr) {
12806         var end = readPackedEnd(this);
12807         arr = arr || [];
12808         while (this.pos < end) arr.push(this.readDouble());
12809         return arr;
12810     },
12811     readPackedFixed32: function(arr) {
12812         var end = readPackedEnd(this);
12813         arr = arr || [];
12814         while (this.pos < end) arr.push(this.readFixed32());
12815         return arr;
12816     },
12817     readPackedSFixed32: function(arr) {
12818         var end = readPackedEnd(this);
12819         arr = arr || [];
12820         while (this.pos < end) arr.push(this.readSFixed32());
12821         return arr;
12822     },
12823     readPackedFixed64: function(arr) {
12824         var end = readPackedEnd(this);
12825         arr = arr || [];
12826         while (this.pos < end) arr.push(this.readFixed64());
12827         return arr;
12828     },
12829     readPackedSFixed64: function(arr) {
12830         var end = readPackedEnd(this);
12831         arr = arr || [];
12832         while (this.pos < end) arr.push(this.readSFixed64());
12833         return arr;
12834     },
12835
12836     skip: function(val) {
12837         var type = val & 0x7;
12838         if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
12839         else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
12840         else if (type === Pbf.Fixed32) this.pos += 4;
12841         else if (type === Pbf.Fixed64) this.pos += 8;
12842         else throw new Error('Unimplemented type: ' + type);
12843     },
12844
12845     // === WRITING =================================================================
12846
12847     writeTag: function(tag, type) {
12848         this.writeVarint((tag << 3) | type);
12849     },
12850
12851     realloc: function(min) {
12852         var length = this.length || 16;
12853
12854         while (length < this.pos + min) length *= 2;
12855
12856         if (length !== this.length) {
12857             var buf = new Uint8Array(length);
12858             buf.set(this.buf);
12859             this.buf = buf;
12860             this.length = length;
12861         }
12862     },
12863
12864     finish: function() {
12865         this.length = this.pos;
12866         this.pos = 0;
12867         return this.buf.subarray(0, this.length);
12868     },
12869
12870     writeFixed32: function(val) {
12871         this.realloc(4);
12872         writeInt32(this.buf, val, this.pos);
12873         this.pos += 4;
12874     },
12875
12876     writeSFixed32: function(val) {
12877         this.realloc(4);
12878         writeInt32(this.buf, val, this.pos);
12879         this.pos += 4;
12880     },
12881
12882     writeFixed64: function(val) {
12883         this.realloc(8);
12884         writeInt32(this.buf, val & -1, this.pos);
12885         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
12886         this.pos += 8;
12887     },
12888
12889     writeSFixed64: function(val) {
12890         this.realloc(8);
12891         writeInt32(this.buf, val & -1, this.pos);
12892         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
12893         this.pos += 8;
12894     },
12895
12896     writeVarint: function(val) {
12897         val = +val || 0;
12898
12899         if (val > 0xfffffff || val < 0) {
12900             writeBigVarint(val, this);
12901             return;
12902         }
12903
12904         this.realloc(4);
12905
12906         this.buf[this.pos++] =           val & 0x7f  | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
12907         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
12908         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
12909         this.buf[this.pos++] =   (val >>> 7) & 0x7f;
12910     },
12911
12912     writeSVarint: function(val) {
12913         this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
12914     },
12915
12916     writeBoolean: function(val) {
12917         this.writeVarint(Boolean(val));
12918     },
12919
12920     writeString: function(str) {
12921         str = String(str);
12922         this.realloc(str.length * 4);
12923
12924         this.pos++; // reserve 1 byte for short string length
12925
12926         var startPos = this.pos;
12927         // write the string directly to the buffer and see how much was written
12928         this.pos = writeUtf8(this.buf, str, this.pos);
12929         var len = this.pos - startPos;
12930
12931         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
12932
12933         // finally, write the message length in the reserved place and restore the position
12934         this.pos = startPos - 1;
12935         this.writeVarint(len);
12936         this.pos += len;
12937     },
12938
12939     writeFloat: function(val) {
12940         this.realloc(4);
12941         ieee754.write(this.buf, val, this.pos, true, 23, 4);
12942         this.pos += 4;
12943     },
12944
12945     writeDouble: function(val) {
12946         this.realloc(8);
12947         ieee754.write(this.buf, val, this.pos, true, 52, 8);
12948         this.pos += 8;
12949     },
12950
12951     writeBytes: function(buffer) {
12952         var len = buffer.length;
12953         this.writeVarint(len);
12954         this.realloc(len);
12955         for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
12956     },
12957
12958     writeRawMessage: function(fn, obj) {
12959         this.pos++; // reserve 1 byte for short message length
12960
12961         // write the message directly to the buffer and see how much was written
12962         var startPos = this.pos;
12963         fn(obj, this);
12964         var len = this.pos - startPos;
12965
12966         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
12967
12968         // finally, write the message length in the reserved place and restore the position
12969         this.pos = startPos - 1;
12970         this.writeVarint(len);
12971         this.pos += len;
12972     },
12973
12974     writeMessage: function(tag, fn, obj) {
12975         this.writeTag(tag, Pbf.Bytes);
12976         this.writeRawMessage(fn, obj);
12977     },
12978
12979     writePackedVarint:   function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr);   },
12980     writePackedSVarint:  function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr);  },
12981     writePackedBoolean:  function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr);  },
12982     writePackedFloat:    function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr);    },
12983     writePackedDouble:   function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr);   },
12984     writePackedFixed32:  function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr);  },
12985     writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
12986     writePackedFixed64:  function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr);  },
12987     writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
12988
12989     writeBytesField: function(tag, buffer) {
12990         this.writeTag(tag, Pbf.Bytes);
12991         this.writeBytes(buffer);
12992     },
12993     writeFixed32Field: function(tag, val) {
12994         this.writeTag(tag, Pbf.Fixed32);
12995         this.writeFixed32(val);
12996     },
12997     writeSFixed32Field: function(tag, val) {
12998         this.writeTag(tag, Pbf.Fixed32);
12999         this.writeSFixed32(val);
13000     },
13001     writeFixed64Field: function(tag, val) {
13002         this.writeTag(tag, Pbf.Fixed64);
13003         this.writeFixed64(val);
13004     },
13005     writeSFixed64Field: function(tag, val) {
13006         this.writeTag(tag, Pbf.Fixed64);
13007         this.writeSFixed64(val);
13008     },
13009     writeVarintField: function(tag, val) {
13010         this.writeTag(tag, Pbf.Varint);
13011         this.writeVarint(val);
13012     },
13013     writeSVarintField: function(tag, val) {
13014         this.writeTag(tag, Pbf.Varint);
13015         this.writeSVarint(val);
13016     },
13017     writeStringField: function(tag, str) {
13018         this.writeTag(tag, Pbf.Bytes);
13019         this.writeString(str);
13020     },
13021     writeFloatField: function(tag, val) {
13022         this.writeTag(tag, Pbf.Fixed32);
13023         this.writeFloat(val);
13024     },
13025     writeDoubleField: function(tag, val) {
13026         this.writeTag(tag, Pbf.Fixed64);
13027         this.writeDouble(val);
13028     },
13029     writeBooleanField: function(tag, val) {
13030         this.writeVarintField(tag, Boolean(val));
13031     }
13032 };
13033
13034 function readVarintRemainder(l, s, p) {
13035     var buf = p.buf,
13036         h, b;
13037
13038     b = buf[p.pos++]; h  = (b & 0x70) >> 4;  if (b < 0x80) return toNum(l, h, s);
13039     b = buf[p.pos++]; h |= (b & 0x7f) << 3;  if (b < 0x80) return toNum(l, h, s);
13040     b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
13041     b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
13042     b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
13043     b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
13044
13045     throw new Error('Expected varint not more than 10 bytes');
13046 }
13047
13048 function readPackedEnd(pbf) {
13049     return pbf.type === Pbf.Bytes ?
13050         pbf.readVarint() + pbf.pos : pbf.pos + 1;
13051 }
13052
13053 function toNum(low, high, isSigned) {
13054     if (isSigned) {
13055         return high * 0x100000000 + (low >>> 0);
13056     }
13057
13058     return ((high >>> 0) * 0x100000000) + (low >>> 0);
13059 }
13060
13061 function writeBigVarint(val, pbf) {
13062     var low, high;
13063
13064     if (val >= 0) {
13065         low  = (val % 0x100000000) | 0;
13066         high = (val / 0x100000000) | 0;
13067     } else {
13068         low  = ~(-val % 0x100000000);
13069         high = ~(-val / 0x100000000);
13070
13071         if (low ^ 0xffffffff) {
13072             low = (low + 1) | 0;
13073         } else {
13074             low = 0;
13075             high = (high + 1) | 0;
13076         }
13077     }
13078
13079     if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
13080         throw new Error('Given varint doesn\'t fit into 10 bytes');
13081     }
13082
13083     pbf.realloc(10);
13084
13085     writeBigVarintLow(low, high, pbf);
13086     writeBigVarintHigh(high, pbf);
13087 }
13088
13089 function writeBigVarintLow(low, high, pbf) {
13090     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
13091     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
13092     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
13093     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
13094     pbf.buf[pbf.pos]   = low & 0x7f;
13095 }
13096
13097 function writeBigVarintHigh(high, pbf) {
13098     var lsb = (high & 0x07) << 4;
13099
13100     pbf.buf[pbf.pos++] |= lsb         | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
13101     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
13102     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
13103     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
13104     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
13105     pbf.buf[pbf.pos++]  = high & 0x7f;
13106 }
13107
13108 function makeRoomForExtraLength(startPos, len, pbf) {
13109     var extraLen =
13110         len <= 0x3fff ? 1 :
13111         len <= 0x1fffff ? 2 :
13112         len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
13113
13114     // if 1 byte isn't enough for encoding message length, shift the data to the right
13115     pbf.realloc(extraLen);
13116     for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
13117 }
13118
13119 function writePackedVarint(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]);   }
13120 function writePackedSVarint(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]);  }
13121 function writePackedFloat(arr, pbf)    { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]);    }
13122 function writePackedDouble(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]);   }
13123 function writePackedBoolean(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]);  }
13124 function writePackedFixed32(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]);  }
13125 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
13126 function writePackedFixed64(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]);  }
13127 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
13128
13129 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
13130
13131 function readUInt32(buf, pos) {
13132     return ((buf[pos]) |
13133         (buf[pos + 1] << 8) |
13134         (buf[pos + 2] << 16)) +
13135         (buf[pos + 3] * 0x1000000);
13136 }
13137
13138 function writeInt32(buf, val, pos) {
13139     buf[pos] = val;
13140     buf[pos + 1] = (val >>> 8);
13141     buf[pos + 2] = (val >>> 16);
13142     buf[pos + 3] = (val >>> 24);
13143 }
13144
13145 function readInt32(buf, pos) {
13146     return ((buf[pos]) |
13147         (buf[pos + 1] << 8) |
13148         (buf[pos + 2] << 16)) +
13149         (buf[pos + 3] << 24);
13150 }
13151
13152 function readUtf8(buf, pos, end) {
13153     var str = '';
13154     var i = pos;
13155
13156     while (i < end) {
13157         var b0 = buf[i];
13158         var c = null; // codepoint
13159         var bytesPerSequence =
13160             b0 > 0xEF ? 4 :
13161             b0 > 0xDF ? 3 :
13162             b0 > 0xBF ? 2 : 1;
13163
13164         if (i + bytesPerSequence > end) break;
13165
13166         var b1, b2, b3;
13167
13168         if (bytesPerSequence === 1) {
13169             if (b0 < 0x80) {
13170                 c = b0;
13171             }
13172         } else if (bytesPerSequence === 2) {
13173             b1 = buf[i + 1];
13174             if ((b1 & 0xC0) === 0x80) {
13175                 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
13176                 if (c <= 0x7F) {
13177                     c = null;
13178                 }
13179             }
13180         } else if (bytesPerSequence === 3) {
13181             b1 = buf[i + 1];
13182             b2 = buf[i + 2];
13183             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
13184                 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
13185                 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
13186                     c = null;
13187                 }
13188             }
13189         } else if (bytesPerSequence === 4) {
13190             b1 = buf[i + 1];
13191             b2 = buf[i + 2];
13192             b3 = buf[i + 3];
13193             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
13194                 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
13195                 if (c <= 0xFFFF || c >= 0x110000) {
13196                     c = null;
13197                 }
13198             }
13199         }
13200
13201         if (c === null) {
13202             c = 0xFFFD;
13203             bytesPerSequence = 1;
13204
13205         } else if (c > 0xFFFF) {
13206             c -= 0x10000;
13207             str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
13208             c = 0xDC00 | c & 0x3FF;
13209         }
13210
13211         str += String.fromCharCode(c);
13212         i += bytesPerSequence;
13213     }
13214
13215     return str;
13216 }
13217
13218 function writeUtf8(buf, str, pos) {
13219     for (var i = 0, c, lead; i < str.length; i++) {
13220         c = str.charCodeAt(i); // code point
13221
13222         if (c > 0xD7FF && c < 0xE000) {
13223             if (lead) {
13224                 if (c < 0xDC00) {
13225                     buf[pos++] = 0xEF;
13226                     buf[pos++] = 0xBF;
13227                     buf[pos++] = 0xBD;
13228                     lead = c;
13229                     continue;
13230                 } else {
13231                     c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
13232                     lead = null;
13233                 }
13234             } else {
13235                 if (c > 0xDBFF || (i + 1 === str.length)) {
13236                     buf[pos++] = 0xEF;
13237                     buf[pos++] = 0xBF;
13238                     buf[pos++] = 0xBD;
13239                 } else {
13240                     lead = c;
13241                 }
13242                 continue;
13243             }
13244         } else if (lead) {
13245             buf[pos++] = 0xEF;
13246             buf[pos++] = 0xBF;
13247             buf[pos++] = 0xBD;
13248             lead = null;
13249         }
13250
13251         if (c < 0x80) {
13252             buf[pos++] = c;
13253         } else {
13254             if (c < 0x800) {
13255                 buf[pos++] = c >> 0x6 | 0xC0;
13256             } else {
13257                 if (c < 0x10000) {
13258                     buf[pos++] = c >> 0xC | 0xE0;
13259                 } else {
13260                     buf[pos++] = c >> 0x12 | 0xF0;
13261                     buf[pos++] = c >> 0xC & 0x3F | 0x80;
13262                 }
13263                 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
13264             }
13265             buf[pos++] = c & 0x3F | 0x80;
13266         }
13267     }
13268     return pos;
13269 }
13270
13271 },{"ieee754":17}],41:[function(require,module,exports){
13272 (function (global, factory) {
13273         typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
13274         typeof define === 'function' && define.amd ? define(factory) :
13275         (global.quickselect = factory());
13276 }(this, (function () { 'use strict';
13277
13278 function quickselect(arr, k, left, right, compare) {
13279     quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);
13280 }
13281
13282 function quickselectStep(arr, k, left, right, compare) {
13283
13284     while (right > left) {
13285         if (right - left > 600) {
13286             var n = right - left + 1;
13287             var m = k - left + 1;
13288             var z = Math.log(n);
13289             var s = 0.5 * Math.exp(2 * z / 3);
13290             var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
13291             var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
13292             var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
13293             quickselectStep(arr, k, newLeft, newRight, compare);
13294         }
13295
13296         var t = arr[k];
13297         var i = left;
13298         var j = right;
13299
13300         swap(arr, left, k);
13301         if (compare(arr[right], t) > 0) swap(arr, left, right);
13302
13303         while (i < j) {
13304             swap(arr, i, j);
13305             i++;
13306             j--;
13307             while (compare(arr[i], t) < 0) i++;
13308             while (compare(arr[j], t) > 0) j--;
13309         }
13310
13311         if (compare(arr[left], t) === 0) swap(arr, left, j);
13312         else {
13313             j++;
13314             swap(arr, j, right);
13315         }
13316
13317         if (j <= k) left = j + 1;
13318         if (k <= j) right = j - 1;
13319     }
13320 }
13321
13322 function swap(arr, i, j) {
13323     var tmp = arr[i];
13324     arr[i] = arr[j];
13325     arr[j] = tmp;
13326 }
13327
13328 function defaultCompare(a, b) {
13329     return a < b ? -1 : a > b ? 1 : 0;
13330 }
13331
13332 return quickselect;
13333
13334 })));
13335
13336 },{}],42:[function(require,module,exports){
13337 'use strict';
13338
13339 module.exports = rbush;
13340 module.exports.default = rbush;
13341
13342 var quickselect = require('quickselect');
13343
13344 function rbush(maxEntries, format) {
13345     if (!(this instanceof rbush)) return new rbush(maxEntries, format);
13346
13347     // max entries in a node is 9 by default; min node fill is 40% for best performance
13348     this._maxEntries = Math.max(4, maxEntries || 9);
13349     this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
13350
13351     if (format) {
13352         this._initFormat(format);
13353     }
13354
13355     this.clear();
13356 }
13357
13358 rbush.prototype = {
13359
13360     all: function () {
13361         return this._all(this.data, []);
13362     },
13363
13364     search: function (bbox) {
13365
13366         var node = this.data,
13367             result = [],
13368             toBBox = this.toBBox;
13369
13370         if (!intersects(bbox, node)) return result;
13371
13372         var nodesToSearch = [],
13373             i, len, child, childBBox;
13374
13375         while (node) {
13376             for (i = 0, len = node.children.length; i < len; i++) {
13377
13378                 child = node.children[i];
13379                 childBBox = node.leaf ? toBBox(child) : child;
13380
13381                 if (intersects(bbox, childBBox)) {
13382                     if (node.leaf) result.push(child);
13383                     else if (contains(bbox, childBBox)) this._all(child, result);
13384                     else nodesToSearch.push(child);
13385                 }
13386             }
13387             node = nodesToSearch.pop();
13388         }
13389
13390         return result;
13391     },
13392
13393     collides: function (bbox) {
13394
13395         var node = this.data,
13396             toBBox = this.toBBox;
13397
13398         if (!intersects(bbox, node)) return false;
13399
13400         var nodesToSearch = [],
13401             i, len, child, childBBox;
13402
13403         while (node) {
13404             for (i = 0, len = node.children.length; i < len; i++) {
13405
13406                 child = node.children[i];
13407                 childBBox = node.leaf ? toBBox(child) : child;
13408
13409                 if (intersects(bbox, childBBox)) {
13410                     if (node.leaf || contains(bbox, childBBox)) return true;
13411                     nodesToSearch.push(child);
13412                 }
13413             }
13414             node = nodesToSearch.pop();
13415         }
13416
13417         return false;
13418     },
13419
13420     load: function (data) {
13421         if (!(data && data.length)) return this;
13422
13423         if (data.length < this._minEntries) {
13424             for (var i = 0, len = data.length; i < len; i++) {
13425                 this.insert(data[i]);
13426             }
13427             return this;
13428         }
13429
13430         // recursively build the tree with the given data from scratch using OMT algorithm
13431         var node = this._build(data.slice(), 0, data.length - 1, 0);
13432
13433         if (!this.data.children.length) {
13434             // save as is if tree is empty
13435             this.data = node;
13436
13437         } else if (this.data.height === node.height) {
13438             // split root if trees have the same height
13439             this._splitRoot(this.data, node);
13440
13441         } else {
13442             if (this.data.height < node.height) {
13443                 // swap trees if inserted one is bigger
13444                 var tmpNode = this.data;
13445                 this.data = node;
13446                 node = tmpNode;
13447             }
13448
13449             // insert the small tree into the large tree at appropriate level
13450             this._insert(node, this.data.height - node.height - 1, true);
13451         }
13452
13453         return this;
13454     },
13455
13456     insert: function (item) {
13457         if (item) this._insert(item, this.data.height - 1);
13458         return this;
13459     },
13460
13461     clear: function () {
13462         this.data = createNode([]);
13463         return this;
13464     },
13465
13466     remove: function (item, equalsFn) {
13467         if (!item) return this;
13468
13469         var node = this.data,
13470             bbox = this.toBBox(item),
13471             path = [],
13472             indexes = [],
13473             i, parent, index, goingUp;
13474
13475         // depth-first iterative tree traversal
13476         while (node || path.length) {
13477
13478             if (!node) { // go up
13479                 node = path.pop();
13480                 parent = path[path.length - 1];
13481                 i = indexes.pop();
13482                 goingUp = true;
13483             }
13484
13485             if (node.leaf) { // check current node
13486                 index = findItem(item, node.children, equalsFn);
13487
13488                 if (index !== -1) {
13489                     // item found, remove the item and condense tree upwards
13490                     node.children.splice(index, 1);
13491                     path.push(node);
13492                     this._condense(path);
13493                     return this;
13494                 }
13495             }
13496
13497             if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
13498                 path.push(node);
13499                 indexes.push(i);
13500                 i = 0;
13501                 parent = node;
13502                 node = node.children[0];
13503
13504             } else if (parent) { // go right
13505                 i++;
13506                 node = parent.children[i];
13507                 goingUp = false;
13508
13509             } else node = null; // nothing found
13510         }
13511
13512         return this;
13513     },
13514
13515     toBBox: function (item) { return item; },
13516
13517     compareMinX: compareNodeMinX,
13518     compareMinY: compareNodeMinY,
13519
13520     toJSON: function () { return this.data; },
13521
13522     fromJSON: function (data) {
13523         this.data = data;
13524         return this;
13525     },
13526
13527     _all: function (node, result) {
13528         var nodesToSearch = [];
13529         while (node) {
13530             if (node.leaf) result.push.apply(result, node.children);
13531             else nodesToSearch.push.apply(nodesToSearch, node.children);
13532
13533             node = nodesToSearch.pop();
13534         }
13535         return result;
13536     },
13537
13538     _build: function (items, left, right, height) {
13539
13540         var N = right - left + 1,
13541             M = this._maxEntries,
13542             node;
13543
13544         if (N <= M) {
13545             // reached leaf level; return leaf
13546             node = createNode(items.slice(left, right + 1));
13547             calcBBox(node, this.toBBox);
13548             return node;
13549         }
13550
13551         if (!height) {
13552             // target height of the bulk-loaded tree
13553             height = Math.ceil(Math.log(N) / Math.log(M));
13554
13555             // target number of root entries to maximize storage utilization
13556             M = Math.ceil(N / Math.pow(M, height - 1));
13557         }
13558
13559         node = createNode([]);
13560         node.leaf = false;
13561         node.height = height;
13562
13563         // split the items into M mostly square tiles
13564
13565         var N2 = Math.ceil(N / M),
13566             N1 = N2 * Math.ceil(Math.sqrt(M)),
13567             i, j, right2, right3;
13568
13569         multiSelect(items, left, right, N1, this.compareMinX);
13570
13571         for (i = left; i <= right; i += N1) {
13572
13573             right2 = Math.min(i + N1 - 1, right);
13574
13575             multiSelect(items, i, right2, N2, this.compareMinY);
13576
13577             for (j = i; j <= right2; j += N2) {
13578
13579                 right3 = Math.min(j + N2 - 1, right2);
13580
13581                 // pack each entry recursively
13582                 node.children.push(this._build(items, j, right3, height - 1));
13583             }
13584         }
13585
13586         calcBBox(node, this.toBBox);
13587
13588         return node;
13589     },
13590
13591     _chooseSubtree: function (bbox, node, level, path) {
13592
13593         var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
13594
13595         while (true) {
13596             path.push(node);
13597
13598             if (node.leaf || path.length - 1 === level) break;
13599
13600             minArea = minEnlargement = Infinity;
13601
13602             for (i = 0, len = node.children.length; i < len; i++) {
13603                 child = node.children[i];
13604                 area = bboxArea(child);
13605                 enlargement = enlargedArea(bbox, child) - area;
13606
13607                 // choose entry with the least area enlargement
13608                 if (enlargement < minEnlargement) {
13609                     minEnlargement = enlargement;
13610                     minArea = area < minArea ? area : minArea;
13611                     targetNode = child;
13612
13613                 } else if (enlargement === minEnlargement) {
13614                     // otherwise choose one with the smallest area
13615                     if (area < minArea) {
13616                         minArea = area;
13617                         targetNode = child;
13618                     }
13619                 }
13620             }
13621
13622             node = targetNode || node.children[0];
13623         }
13624
13625         return node;
13626     },
13627
13628     _insert: function (item, level, isNode) {
13629
13630         var toBBox = this.toBBox,
13631             bbox = isNode ? item : toBBox(item),
13632             insertPath = [];
13633
13634         // find the best node for accommodating the item, saving all nodes along the path too
13635         var node = this._chooseSubtree(bbox, this.data, level, insertPath);
13636
13637         // put the item into the node
13638         node.children.push(item);
13639         extend(node, bbox);
13640
13641         // split on node overflow; propagate upwards if necessary
13642         while (level >= 0) {
13643             if (insertPath[level].children.length > this._maxEntries) {
13644                 this._split(insertPath, level);
13645                 level--;
13646             } else break;
13647         }
13648
13649         // adjust bboxes along the insertion path
13650         this._adjustParentBBoxes(bbox, insertPath, level);
13651     },
13652
13653     // split overflowed node into two
13654     _split: function (insertPath, level) {
13655
13656         var node = insertPath[level],
13657             M = node.children.length,
13658             m = this._minEntries;
13659
13660         this._chooseSplitAxis(node, m, M);
13661
13662         var splitIndex = this._chooseSplitIndex(node, m, M);
13663
13664         var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
13665         newNode.height = node.height;
13666         newNode.leaf = node.leaf;
13667
13668         calcBBox(node, this.toBBox);
13669         calcBBox(newNode, this.toBBox);
13670
13671         if (level) insertPath[level - 1].children.push(newNode);
13672         else this._splitRoot(node, newNode);
13673     },
13674
13675     _splitRoot: function (node, newNode) {
13676         // split root node
13677         this.data = createNode([node, newNode]);
13678         this.data.height = node.height + 1;
13679         this.data.leaf = false;
13680         calcBBox(this.data, this.toBBox);
13681     },
13682
13683     _chooseSplitIndex: function (node, m, M) {
13684
13685         var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
13686
13687         minOverlap = minArea = Infinity;
13688
13689         for (i = m; i <= M - m; i++) {
13690             bbox1 = distBBox(node, 0, i, this.toBBox);
13691             bbox2 = distBBox(node, i, M, this.toBBox);
13692
13693             overlap = intersectionArea(bbox1, bbox2);
13694             area = bboxArea(bbox1) + bboxArea(bbox2);
13695
13696             // choose distribution with minimum overlap
13697             if (overlap < minOverlap) {
13698                 minOverlap = overlap;
13699                 index = i;
13700
13701                 minArea = area < minArea ? area : minArea;
13702
13703             } else if (overlap === minOverlap) {
13704                 // otherwise choose distribution with minimum area
13705                 if (area < minArea) {
13706                     minArea = area;
13707                     index = i;
13708                 }
13709             }
13710         }
13711
13712         return index;
13713     },
13714
13715     // sorts node children by the best axis for split
13716     _chooseSplitAxis: function (node, m, M) {
13717
13718         var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
13719             compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
13720             xMargin = this._allDistMargin(node, m, M, compareMinX),
13721             yMargin = this._allDistMargin(node, m, M, compareMinY);
13722
13723         // if total distributions margin value is minimal for x, sort by minX,
13724         // otherwise it's already sorted by minY
13725         if (xMargin < yMargin) node.children.sort(compareMinX);
13726     },
13727
13728     // total margin of all possible split distributions where each node is at least m full
13729     _allDistMargin: function (node, m, M, compare) {
13730
13731         node.children.sort(compare);
13732
13733         var toBBox = this.toBBox,
13734             leftBBox = distBBox(node, 0, m, toBBox),
13735             rightBBox = distBBox(node, M - m, M, toBBox),
13736             margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
13737             i, child;
13738
13739         for (i = m; i < M - m; i++) {
13740             child = node.children[i];
13741             extend(leftBBox, node.leaf ? toBBox(child) : child);
13742             margin += bboxMargin(leftBBox);
13743         }
13744
13745         for (i = M - m - 1; i >= m; i--) {
13746             child = node.children[i];
13747             extend(rightBBox, node.leaf ? toBBox(child) : child);
13748             margin += bboxMargin(rightBBox);
13749         }
13750
13751         return margin;
13752     },
13753
13754     _adjustParentBBoxes: function (bbox, path, level) {
13755         // adjust bboxes along the given tree path
13756         for (var i = level; i >= 0; i--) {
13757             extend(path[i], bbox);
13758         }
13759     },
13760
13761     _condense: function (path) {
13762         // go through the path, removing empty nodes and updating bboxes
13763         for (var i = path.length - 1, siblings; i >= 0; i--) {
13764             if (path[i].children.length === 0) {
13765                 if (i > 0) {
13766                     siblings = path[i - 1].children;
13767                     siblings.splice(siblings.indexOf(path[i]), 1);
13768
13769                 } else this.clear();
13770
13771             } else calcBBox(path[i], this.toBBox);
13772         }
13773     },
13774
13775     _initFormat: function (format) {
13776         // data format (minX, minY, maxX, maxY accessors)
13777
13778         // uses eval-type function compilation instead of just accepting a toBBox function
13779         // because the algorithms are very sensitive to sorting functions performance,
13780         // so they should be dead simple and without inner calls
13781
13782         var compareArr = ['return a', ' - b', ';'];
13783
13784         this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
13785         this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
13786
13787         this.toBBox = new Function('a',
13788             'return {minX: a' + format[0] +
13789             ', minY: a' + format[1] +
13790             ', maxX: a' + format[2] +
13791             ', maxY: a' + format[3] + '};');
13792     }
13793 };
13794
13795 function findItem(item, items, equalsFn) {
13796     if (!equalsFn) return items.indexOf(item);
13797
13798     for (var i = 0; i < items.length; i++) {
13799         if (equalsFn(item, items[i])) return i;
13800     }
13801     return -1;
13802 }
13803
13804 // calculate node's bbox from bboxes of its children
13805 function calcBBox(node, toBBox) {
13806     distBBox(node, 0, node.children.length, toBBox, node);
13807 }
13808
13809 // min bounding rectangle of node children from k to p-1
13810 function distBBox(node, k, p, toBBox, destNode) {
13811     if (!destNode) destNode = createNode(null);
13812     destNode.minX = Infinity;
13813     destNode.minY = Infinity;
13814     destNode.maxX = -Infinity;
13815     destNode.maxY = -Infinity;
13816
13817     for (var i = k, child; i < p; i++) {
13818         child = node.children[i];
13819         extend(destNode, node.leaf ? toBBox(child) : child);
13820     }
13821
13822     return destNode;
13823 }
13824
13825 function extend(a, b) {
13826     a.minX = Math.min(a.minX, b.minX);
13827     a.minY = Math.min(a.minY, b.minY);
13828     a.maxX = Math.max(a.maxX, b.maxX);
13829     a.maxY = Math.max(a.maxY, b.maxY);
13830     return a;
13831 }
13832
13833 function compareNodeMinX(a, b) { return a.minX - b.minX; }
13834 function compareNodeMinY(a, b) { return a.minY - b.minY; }
13835
13836 function bboxArea(a)   { return (a.maxX - a.minX) * (a.maxY - a.minY); }
13837 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
13838
13839 function enlargedArea(a, b) {
13840     return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
13841            (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
13842 }
13843
13844 function intersectionArea(a, b) {
13845     var minX = Math.max(a.minX, b.minX),
13846         minY = Math.max(a.minY, b.minY),
13847         maxX = Math.min(a.maxX, b.maxX),
13848         maxY = Math.min(a.maxY, b.maxY);
13849
13850     return Math.max(0, maxX - minX) *
13851            Math.max(0, maxY - minY);
13852 }
13853
13854 function contains(a, b) {
13855     return a.minX <= b.minX &&
13856            a.minY <= b.minY &&
13857            b.maxX <= a.maxX &&
13858            b.maxY <= a.maxY;
13859 }
13860
13861 function intersects(a, b) {
13862     return b.minX <= a.maxX &&
13863            b.minY <= a.maxY &&
13864            b.maxX >= a.minX &&
13865            b.maxY >= a.minY;
13866 }
13867
13868 function createNode(children) {
13869     return {
13870         children: children,
13871         height: 1,
13872         leaf: true,
13873         minX: Infinity,
13874         minY: Infinity,
13875         maxX: -Infinity,
13876         maxY: -Infinity
13877     };
13878 }
13879
13880 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
13881 // combines selection algorithm with binary divide & conquer approach
13882
13883 function multiSelect(arr, left, right, n, compare) {
13884     var stack = [left, right],
13885         mid;
13886
13887     while (stack.length) {
13888         right = stack.pop();
13889         left = stack.pop();
13890
13891         if (right - left <= n) continue;
13892
13893         mid = left + Math.ceil((right - left) / n / 2) * n;
13894         quickselect(arr, mid, left, right, compare);
13895
13896         stack.push(left, mid, mid, right);
13897     }
13898 }
13899
13900 },{"quickselect":41}],43:[function(require,module,exports){
13901 "use strict";
13902 Object.defineProperty(exports, "__esModule", { value: true });
13903 var Observable_1 = require("./internal/Observable");
13904 exports.Observable = Observable_1.Observable;
13905 var ConnectableObservable_1 = require("./internal/observable/ConnectableObservable");
13906 exports.ConnectableObservable = ConnectableObservable_1.ConnectableObservable;
13907 var groupBy_1 = require("./internal/operators/groupBy");
13908 exports.GroupedObservable = groupBy_1.GroupedObservable;
13909 var observable_1 = require("./internal/symbol/observable");
13910 exports.observable = observable_1.observable;
13911 var Subject_1 = require("./internal/Subject");
13912 exports.Subject = Subject_1.Subject;
13913 var BehaviorSubject_1 = require("./internal/BehaviorSubject");
13914 exports.BehaviorSubject = BehaviorSubject_1.BehaviorSubject;
13915 var ReplaySubject_1 = require("./internal/ReplaySubject");
13916 exports.ReplaySubject = ReplaySubject_1.ReplaySubject;
13917 var AsyncSubject_1 = require("./internal/AsyncSubject");
13918 exports.AsyncSubject = AsyncSubject_1.AsyncSubject;
13919 var asap_1 = require("./internal/scheduler/asap");
13920 exports.asapScheduler = asap_1.asap;
13921 var async_1 = require("./internal/scheduler/async");
13922 exports.asyncScheduler = async_1.async;
13923 var queue_1 = require("./internal/scheduler/queue");
13924 exports.queueScheduler = queue_1.queue;
13925 var animationFrame_1 = require("./internal/scheduler/animationFrame");
13926 exports.animationFrameScheduler = animationFrame_1.animationFrame;
13927 var VirtualTimeScheduler_1 = require("./internal/scheduler/VirtualTimeScheduler");
13928 exports.VirtualTimeScheduler = VirtualTimeScheduler_1.VirtualTimeScheduler;
13929 exports.VirtualAction = VirtualTimeScheduler_1.VirtualAction;
13930 var Scheduler_1 = require("./internal/Scheduler");
13931 exports.Scheduler = Scheduler_1.Scheduler;
13932 var Subscription_1 = require("./internal/Subscription");
13933 exports.Subscription = Subscription_1.Subscription;
13934 var Subscriber_1 = require("./internal/Subscriber");
13935 exports.Subscriber = Subscriber_1.Subscriber;
13936 var Notification_1 = require("./internal/Notification");
13937 exports.Notification = Notification_1.Notification;
13938 var pipe_1 = require("./internal/util/pipe");
13939 exports.pipe = pipe_1.pipe;
13940 var noop_1 = require("./internal/util/noop");
13941 exports.noop = noop_1.noop;
13942 var identity_1 = require("./internal/util/identity");
13943 exports.identity = identity_1.identity;
13944 var isObservable_1 = require("./internal/util/isObservable");
13945 exports.isObservable = isObservable_1.isObservable;
13946 var ArgumentOutOfRangeError_1 = require("./internal/util/ArgumentOutOfRangeError");
13947 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
13948 var EmptyError_1 = require("./internal/util/EmptyError");
13949 exports.EmptyError = EmptyError_1.EmptyError;
13950 var ObjectUnsubscribedError_1 = require("./internal/util/ObjectUnsubscribedError");
13951 exports.ObjectUnsubscribedError = ObjectUnsubscribedError_1.ObjectUnsubscribedError;
13952 var UnsubscriptionError_1 = require("./internal/util/UnsubscriptionError");
13953 exports.UnsubscriptionError = UnsubscriptionError_1.UnsubscriptionError;
13954 var TimeoutError_1 = require("./internal/util/TimeoutError");
13955 exports.TimeoutError = TimeoutError_1.TimeoutError;
13956 var bindCallback_1 = require("./internal/observable/bindCallback");
13957 exports.bindCallback = bindCallback_1.bindCallback;
13958 var bindNodeCallback_1 = require("./internal/observable/bindNodeCallback");
13959 exports.bindNodeCallback = bindNodeCallback_1.bindNodeCallback;
13960 var combineLatest_1 = require("./internal/observable/combineLatest");
13961 exports.combineLatest = combineLatest_1.combineLatest;
13962 var concat_1 = require("./internal/observable/concat");
13963 exports.concat = concat_1.concat;
13964 var defer_1 = require("./internal/observable/defer");
13965 exports.defer = defer_1.defer;
13966 var empty_1 = require("./internal/observable/empty");
13967 exports.empty = empty_1.empty;
13968 var forkJoin_1 = require("./internal/observable/forkJoin");
13969 exports.forkJoin = forkJoin_1.forkJoin;
13970 var from_1 = require("./internal/observable/from");
13971 exports.from = from_1.from;
13972 var fromEvent_1 = require("./internal/observable/fromEvent");
13973 exports.fromEvent = fromEvent_1.fromEvent;
13974 var fromEventPattern_1 = require("./internal/observable/fromEventPattern");
13975 exports.fromEventPattern = fromEventPattern_1.fromEventPattern;
13976 var generate_1 = require("./internal/observable/generate");
13977 exports.generate = generate_1.generate;
13978 var iif_1 = require("./internal/observable/iif");
13979 exports.iif = iif_1.iif;
13980 var interval_1 = require("./internal/observable/interval");
13981 exports.interval = interval_1.interval;
13982 var merge_1 = require("./internal/observable/merge");
13983 exports.merge = merge_1.merge;
13984 var never_1 = require("./internal/observable/never");
13985 exports.never = never_1.never;
13986 var of_1 = require("./internal/observable/of");
13987 exports.of = of_1.of;
13988 var onErrorResumeNext_1 = require("./internal/observable/onErrorResumeNext");
13989 exports.onErrorResumeNext = onErrorResumeNext_1.onErrorResumeNext;
13990 var pairs_1 = require("./internal/observable/pairs");
13991 exports.pairs = pairs_1.pairs;
13992 var race_1 = require("./internal/observable/race");
13993 exports.race = race_1.race;
13994 var range_1 = require("./internal/observable/range");
13995 exports.range = range_1.range;
13996 var throwError_1 = require("./internal/observable/throwError");
13997 exports.throwError = throwError_1.throwError;
13998 var timer_1 = require("./internal/observable/timer");
13999 exports.timer = timer_1.timer;
14000 var using_1 = require("./internal/observable/using");
14001 exports.using = using_1.using;
14002 var zip_1 = require("./internal/observable/zip");
14003 exports.zip = zip_1.zip;
14004 var empty_2 = require("./internal/observable/empty");
14005 exports.EMPTY = empty_2.EMPTY;
14006 var never_2 = require("./internal/observable/never");
14007 exports.NEVER = never_2.NEVER;
14008 var config_1 = require("./internal/config");
14009 exports.config = config_1.config;
14010
14011 },{"./internal/AsyncSubject":44,"./internal/BehaviorSubject":45,"./internal/Notification":47,"./internal/Observable":48,"./internal/ReplaySubject":51,"./internal/Scheduler":52,"./internal/Subject":53,"./internal/Subscriber":55,"./internal/Subscription":56,"./internal/config":57,"./internal/observable/ConnectableObservable":58,"./internal/observable/bindCallback":60,"./internal/observable/bindNodeCallback":61,"./internal/observable/combineLatest":62,"./internal/observable/concat":63,"./internal/observable/defer":64,"./internal/observable/empty":65,"./internal/observable/forkJoin":66,"./internal/observable/from":67,"./internal/observable/fromEvent":69,"./internal/observable/fromEventPattern":70,"./internal/observable/generate":74,"./internal/observable/iif":75,"./internal/observable/interval":76,"./internal/observable/merge":77,"./internal/observable/never":78,"./internal/observable/of":79,"./internal/observable/onErrorResumeNext":80,"./internal/observable/pairs":81,"./internal/observable/race":82,"./internal/observable/range":83,"./internal/observable/throwError":85,"./internal/observable/timer":86,"./internal/observable/using":87,"./internal/observable/zip":88,"./internal/operators/groupBy":124,"./internal/scheduler/VirtualTimeScheduler":201,"./internal/scheduler/animationFrame":202,"./internal/scheduler/asap":203,"./internal/scheduler/async":204,"./internal/scheduler/queue":205,"./internal/symbol/observable":207,"./internal/util/ArgumentOutOfRangeError":209,"./internal/util/EmptyError":210,"./internal/util/ObjectUnsubscribedError":212,"./internal/util/TimeoutError":213,"./internal/util/UnsubscriptionError":214,"./internal/util/identity":218,"./internal/util/isObservable":227,"./internal/util/noop":230,"./internal/util/pipe":232}],44:[function(require,module,exports){
14012 "use strict";
14013 var __extends = (this && this.__extends) || (function () {
14014     var extendStatics = function (d, b) {
14015         extendStatics = Object.setPrototypeOf ||
14016             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14017             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14018         return extendStatics(d, b);
14019     }
14020     return function (d, b) {
14021         extendStatics(d, b);
14022         function __() { this.constructor = d; }
14023         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14024     };
14025 })();
14026 Object.defineProperty(exports, "__esModule", { value: true });
14027 var Subject_1 = require("./Subject");
14028 var Subscription_1 = require("./Subscription");
14029 var AsyncSubject = (function (_super) {
14030     __extends(AsyncSubject, _super);
14031     function AsyncSubject() {
14032         var _this = _super !== null && _super.apply(this, arguments) || this;
14033         _this.value = null;
14034         _this.hasNext = false;
14035         _this.hasCompleted = false;
14036         return _this;
14037     }
14038     AsyncSubject.prototype._subscribe = function (subscriber) {
14039         if (this.hasError) {
14040             subscriber.error(this.thrownError);
14041             return Subscription_1.Subscription.EMPTY;
14042         }
14043         else if (this.hasCompleted && this.hasNext) {
14044             subscriber.next(this.value);
14045             subscriber.complete();
14046             return Subscription_1.Subscription.EMPTY;
14047         }
14048         return _super.prototype._subscribe.call(this, subscriber);
14049     };
14050     AsyncSubject.prototype.next = function (value) {
14051         if (!this.hasCompleted) {
14052             this.value = value;
14053             this.hasNext = true;
14054         }
14055     };
14056     AsyncSubject.prototype.error = function (error) {
14057         if (!this.hasCompleted) {
14058             _super.prototype.error.call(this, error);
14059         }
14060     };
14061     AsyncSubject.prototype.complete = function () {
14062         this.hasCompleted = true;
14063         if (this.hasNext) {
14064             _super.prototype.next.call(this, this.value);
14065         }
14066         _super.prototype.complete.call(this);
14067     };
14068     return AsyncSubject;
14069 }(Subject_1.Subject));
14070 exports.AsyncSubject = AsyncSubject;
14071
14072 },{"./Subject":53,"./Subscription":56}],45:[function(require,module,exports){
14073 "use strict";
14074 var __extends = (this && this.__extends) || (function () {
14075     var extendStatics = function (d, b) {
14076         extendStatics = Object.setPrototypeOf ||
14077             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14078             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14079         return extendStatics(d, b);
14080     }
14081     return function (d, b) {
14082         extendStatics(d, b);
14083         function __() { this.constructor = d; }
14084         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14085     };
14086 })();
14087 Object.defineProperty(exports, "__esModule", { value: true });
14088 var Subject_1 = require("./Subject");
14089 var ObjectUnsubscribedError_1 = require("./util/ObjectUnsubscribedError");
14090 var BehaviorSubject = (function (_super) {
14091     __extends(BehaviorSubject, _super);
14092     function BehaviorSubject(_value) {
14093         var _this = _super.call(this) || this;
14094         _this._value = _value;
14095         return _this;
14096     }
14097     Object.defineProperty(BehaviorSubject.prototype, "value", {
14098         get: function () {
14099             return this.getValue();
14100         },
14101         enumerable: true,
14102         configurable: true
14103     });
14104     BehaviorSubject.prototype._subscribe = function (subscriber) {
14105         var subscription = _super.prototype._subscribe.call(this, subscriber);
14106         if (subscription && !subscription.closed) {
14107             subscriber.next(this._value);
14108         }
14109         return subscription;
14110     };
14111     BehaviorSubject.prototype.getValue = function () {
14112         if (this.hasError) {
14113             throw this.thrownError;
14114         }
14115         else if (this.closed) {
14116             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
14117         }
14118         else {
14119             return this._value;
14120         }
14121     };
14122     BehaviorSubject.prototype.next = function (value) {
14123         _super.prototype.next.call(this, this._value = value);
14124     };
14125     return BehaviorSubject;
14126 }(Subject_1.Subject));
14127 exports.BehaviorSubject = BehaviorSubject;
14128
14129 },{"./Subject":53,"./util/ObjectUnsubscribedError":212}],46:[function(require,module,exports){
14130 "use strict";
14131 var __extends = (this && this.__extends) || (function () {
14132     var extendStatics = function (d, b) {
14133         extendStatics = Object.setPrototypeOf ||
14134             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14135             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14136         return extendStatics(d, b);
14137     }
14138     return function (d, b) {
14139         extendStatics(d, b);
14140         function __() { this.constructor = d; }
14141         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14142     };
14143 })();
14144 Object.defineProperty(exports, "__esModule", { value: true });
14145 var Subscriber_1 = require("./Subscriber");
14146 var InnerSubscriber = (function (_super) {
14147     __extends(InnerSubscriber, _super);
14148     function InnerSubscriber(parent, outerValue, outerIndex) {
14149         var _this = _super.call(this) || this;
14150         _this.parent = parent;
14151         _this.outerValue = outerValue;
14152         _this.outerIndex = outerIndex;
14153         _this.index = 0;
14154         return _this;
14155     }
14156     InnerSubscriber.prototype._next = function (value) {
14157         this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
14158     };
14159     InnerSubscriber.prototype._error = function (error) {
14160         this.parent.notifyError(error, this);
14161         this.unsubscribe();
14162     };
14163     InnerSubscriber.prototype._complete = function () {
14164         this.parent.notifyComplete(this);
14165         this.unsubscribe();
14166     };
14167     return InnerSubscriber;
14168 }(Subscriber_1.Subscriber));
14169 exports.InnerSubscriber = InnerSubscriber;
14170
14171 },{"./Subscriber":55}],47:[function(require,module,exports){
14172 "use strict";
14173 Object.defineProperty(exports, "__esModule", { value: true });
14174 var empty_1 = require("./observable/empty");
14175 var of_1 = require("./observable/of");
14176 var throwError_1 = require("./observable/throwError");
14177 var Notification = (function () {
14178     function Notification(kind, value, error) {
14179         this.kind = kind;
14180         this.value = value;
14181         this.error = error;
14182         this.hasValue = kind === 'N';
14183     }
14184     Notification.prototype.observe = function (observer) {
14185         switch (this.kind) {
14186             case 'N':
14187                 return observer.next && observer.next(this.value);
14188             case 'E':
14189                 return observer.error && observer.error(this.error);
14190             case 'C':
14191                 return observer.complete && observer.complete();
14192         }
14193     };
14194     Notification.prototype.do = function (next, error, complete) {
14195         var kind = this.kind;
14196         switch (kind) {
14197             case 'N':
14198                 return next && next(this.value);
14199             case 'E':
14200                 return error && error(this.error);
14201             case 'C':
14202                 return complete && complete();
14203         }
14204     };
14205     Notification.prototype.accept = function (nextOrObserver, error, complete) {
14206         if (nextOrObserver && typeof nextOrObserver.next === 'function') {
14207             return this.observe(nextOrObserver);
14208         }
14209         else {
14210             return this.do(nextOrObserver, error, complete);
14211         }
14212     };
14213     Notification.prototype.toObservable = function () {
14214         var kind = this.kind;
14215         switch (kind) {
14216             case 'N':
14217                 return of_1.of(this.value);
14218             case 'E':
14219                 return throwError_1.throwError(this.error);
14220             case 'C':
14221                 return empty_1.empty();
14222         }
14223         throw new Error('unexpected notification kind value');
14224     };
14225     Notification.createNext = function (value) {
14226         if (typeof value !== 'undefined') {
14227             return new Notification('N', value);
14228         }
14229         return Notification.undefinedValueNotification;
14230     };
14231     Notification.createError = function (err) {
14232         return new Notification('E', undefined, err);
14233     };
14234     Notification.createComplete = function () {
14235         return Notification.completeNotification;
14236     };
14237     Notification.completeNotification = new Notification('C');
14238     Notification.undefinedValueNotification = new Notification('N', undefined);
14239     return Notification;
14240 }());
14241 exports.Notification = Notification;
14242
14243 },{"./observable/empty":65,"./observable/of":79,"./observable/throwError":85}],48:[function(require,module,exports){
14244 "use strict";
14245 Object.defineProperty(exports, "__esModule", { value: true });
14246 var canReportError_1 = require("./util/canReportError");
14247 var toSubscriber_1 = require("./util/toSubscriber");
14248 var observable_1 = require("../internal/symbol/observable");
14249 var pipe_1 = require("./util/pipe");
14250 var config_1 = require("./config");
14251 var Observable = (function () {
14252     function Observable(subscribe) {
14253         this._isScalar = false;
14254         if (subscribe) {
14255             this._subscribe = subscribe;
14256         }
14257     }
14258     Observable.prototype.lift = function (operator) {
14259         var observable = new Observable();
14260         observable.source = this;
14261         observable.operator = operator;
14262         return observable;
14263     };
14264     Observable.prototype.subscribe = function (observerOrNext, error, complete) {
14265         var operator = this.operator;
14266         var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
14267         if (operator) {
14268             operator.call(sink, this.source);
14269         }
14270         else {
14271             sink.add(this.source || (config_1.config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
14272                 this._subscribe(sink) :
14273                 this._trySubscribe(sink));
14274         }
14275         if (config_1.config.useDeprecatedSynchronousErrorHandling) {
14276             if (sink.syncErrorThrowable) {
14277                 sink.syncErrorThrowable = false;
14278                 if (sink.syncErrorThrown) {
14279                     throw sink.syncErrorValue;
14280                 }
14281             }
14282         }
14283         return sink;
14284     };
14285     Observable.prototype._trySubscribe = function (sink) {
14286         try {
14287             return this._subscribe(sink);
14288         }
14289         catch (err) {
14290             if (config_1.config.useDeprecatedSynchronousErrorHandling) {
14291                 sink.syncErrorThrown = true;
14292                 sink.syncErrorValue = err;
14293             }
14294             if (canReportError_1.canReportError(sink)) {
14295                 sink.error(err);
14296             }
14297             else {
14298                 console.warn(err);
14299             }
14300         }
14301     };
14302     Observable.prototype.forEach = function (next, promiseCtor) {
14303         var _this = this;
14304         promiseCtor = getPromiseCtor(promiseCtor);
14305         return new promiseCtor(function (resolve, reject) {
14306             var subscription;
14307             subscription = _this.subscribe(function (value) {
14308                 try {
14309                     next(value);
14310                 }
14311                 catch (err) {
14312                     reject(err);
14313                     if (subscription) {
14314                         subscription.unsubscribe();
14315                     }
14316                 }
14317             }, reject, resolve);
14318         });
14319     };
14320     Observable.prototype._subscribe = function (subscriber) {
14321         var source = this.source;
14322         return source && source.subscribe(subscriber);
14323     };
14324     Observable.prototype[observable_1.observable] = function () {
14325         return this;
14326     };
14327     Observable.prototype.pipe = function () {
14328         var operations = [];
14329         for (var _i = 0; _i < arguments.length; _i++) {
14330             operations[_i] = arguments[_i];
14331         }
14332         if (operations.length === 0) {
14333             return this;
14334         }
14335         return pipe_1.pipeFromArray(operations)(this);
14336     };
14337     Observable.prototype.toPromise = function (promiseCtor) {
14338         var _this = this;
14339         promiseCtor = getPromiseCtor(promiseCtor);
14340         return new promiseCtor(function (resolve, reject) {
14341             var value;
14342             _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
14343         });
14344     };
14345     Observable.create = function (subscribe) {
14346         return new Observable(subscribe);
14347     };
14348     return Observable;
14349 }());
14350 exports.Observable = Observable;
14351 function getPromiseCtor(promiseCtor) {
14352     if (!promiseCtor) {
14353         promiseCtor = config_1.config.Promise || Promise;
14354     }
14355     if (!promiseCtor) {
14356         throw new Error('no Promise impl found');
14357     }
14358     return promiseCtor;
14359 }
14360
14361 },{"../internal/symbol/observable":207,"./config":57,"./util/canReportError":215,"./util/pipe":232,"./util/toSubscriber":239}],49:[function(require,module,exports){
14362 "use strict";
14363 Object.defineProperty(exports, "__esModule", { value: true });
14364 var config_1 = require("./config");
14365 var hostReportError_1 = require("./util/hostReportError");
14366 exports.empty = {
14367     closed: true,
14368     next: function (value) { },
14369     error: function (err) {
14370         if (config_1.config.useDeprecatedSynchronousErrorHandling) {
14371             throw err;
14372         }
14373         else {
14374             hostReportError_1.hostReportError(err);
14375         }
14376     },
14377     complete: function () { }
14378 };
14379
14380 },{"./config":57,"./util/hostReportError":217}],50:[function(require,module,exports){
14381 "use strict";
14382 var __extends = (this && this.__extends) || (function () {
14383     var extendStatics = function (d, b) {
14384         extendStatics = Object.setPrototypeOf ||
14385             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14386             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14387         return extendStatics(d, b);
14388     }
14389     return function (d, b) {
14390         extendStatics(d, b);
14391         function __() { this.constructor = d; }
14392         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14393     };
14394 })();
14395 Object.defineProperty(exports, "__esModule", { value: true });
14396 var Subscriber_1 = require("./Subscriber");
14397 var OuterSubscriber = (function (_super) {
14398     __extends(OuterSubscriber, _super);
14399     function OuterSubscriber() {
14400         return _super !== null && _super.apply(this, arguments) || this;
14401     }
14402     OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14403         this.destination.next(innerValue);
14404     };
14405     OuterSubscriber.prototype.notifyError = function (error, innerSub) {
14406         this.destination.error(error);
14407     };
14408     OuterSubscriber.prototype.notifyComplete = function (innerSub) {
14409         this.destination.complete();
14410     };
14411     return OuterSubscriber;
14412 }(Subscriber_1.Subscriber));
14413 exports.OuterSubscriber = OuterSubscriber;
14414
14415 },{"./Subscriber":55}],51:[function(require,module,exports){
14416 "use strict";
14417 var __extends = (this && this.__extends) || (function () {
14418     var extendStatics = function (d, b) {
14419         extendStatics = Object.setPrototypeOf ||
14420             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14421             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14422         return extendStatics(d, b);
14423     }
14424     return function (d, b) {
14425         extendStatics(d, b);
14426         function __() { this.constructor = d; }
14427         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14428     };
14429 })();
14430 Object.defineProperty(exports, "__esModule", { value: true });
14431 var Subject_1 = require("./Subject");
14432 var queue_1 = require("./scheduler/queue");
14433 var Subscription_1 = require("./Subscription");
14434 var observeOn_1 = require("./operators/observeOn");
14435 var ObjectUnsubscribedError_1 = require("./util/ObjectUnsubscribedError");
14436 var SubjectSubscription_1 = require("./SubjectSubscription");
14437 var ReplaySubject = (function (_super) {
14438     __extends(ReplaySubject, _super);
14439     function ReplaySubject(bufferSize, windowTime, scheduler) {
14440         if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
14441         if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
14442         var _this = _super.call(this) || this;
14443         _this.scheduler = scheduler;
14444         _this._events = [];
14445         _this._infiniteTimeWindow = false;
14446         _this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
14447         _this._windowTime = windowTime < 1 ? 1 : windowTime;
14448         if (windowTime === Number.POSITIVE_INFINITY) {
14449             _this._infiniteTimeWindow = true;
14450             _this.next = _this.nextInfiniteTimeWindow;
14451         }
14452         else {
14453             _this.next = _this.nextTimeWindow;
14454         }
14455         return _this;
14456     }
14457     ReplaySubject.prototype.nextInfiniteTimeWindow = function (value) {
14458         var _events = this._events;
14459         _events.push(value);
14460         if (_events.length > this._bufferSize) {
14461             _events.shift();
14462         }
14463         _super.prototype.next.call(this, value);
14464     };
14465     ReplaySubject.prototype.nextTimeWindow = function (value) {
14466         this._events.push(new ReplayEvent(this._getNow(), value));
14467         this._trimBufferThenGetEvents();
14468         _super.prototype.next.call(this, value);
14469     };
14470     ReplaySubject.prototype._subscribe = function (subscriber) {
14471         var _infiniteTimeWindow = this._infiniteTimeWindow;
14472         var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();
14473         var scheduler = this.scheduler;
14474         var len = _events.length;
14475         var subscription;
14476         if (this.closed) {
14477             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
14478         }
14479         else if (this.isStopped || this.hasError) {
14480             subscription = Subscription_1.Subscription.EMPTY;
14481         }
14482         else {
14483             this.observers.push(subscriber);
14484             subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
14485         }
14486         if (scheduler) {
14487             subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
14488         }
14489         if (_infiniteTimeWindow) {
14490             for (var i = 0; i < len && !subscriber.closed; i++) {
14491                 subscriber.next(_events[i]);
14492             }
14493         }
14494         else {
14495             for (var i = 0; i < len && !subscriber.closed; i++) {
14496                 subscriber.next(_events[i].value);
14497             }
14498         }
14499         if (this.hasError) {
14500             subscriber.error(this.thrownError);
14501         }
14502         else if (this.isStopped) {
14503             subscriber.complete();
14504         }
14505         return subscription;
14506     };
14507     ReplaySubject.prototype._getNow = function () {
14508         return (this.scheduler || queue_1.queue).now();
14509     };
14510     ReplaySubject.prototype._trimBufferThenGetEvents = function () {
14511         var now = this._getNow();
14512         var _bufferSize = this._bufferSize;
14513         var _windowTime = this._windowTime;
14514         var _events = this._events;
14515         var eventsCount = _events.length;
14516         var spliceCount = 0;
14517         while (spliceCount < eventsCount) {
14518             if ((now - _events[spliceCount].time) < _windowTime) {
14519                 break;
14520             }
14521             spliceCount++;
14522         }
14523         if (eventsCount > _bufferSize) {
14524             spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
14525         }
14526         if (spliceCount > 0) {
14527             _events.splice(0, spliceCount);
14528         }
14529         return _events;
14530     };
14531     return ReplaySubject;
14532 }(Subject_1.Subject));
14533 exports.ReplaySubject = ReplaySubject;
14534 var ReplayEvent = (function () {
14535     function ReplayEvent(time, value) {
14536         this.time = time;
14537         this.value = value;
14538     }
14539     return ReplayEvent;
14540 }());
14541
14542 },{"./Subject":53,"./SubjectSubscription":54,"./Subscription":56,"./operators/observeOn":139,"./scheduler/queue":205,"./util/ObjectUnsubscribedError":212}],52:[function(require,module,exports){
14543 "use strict";
14544 Object.defineProperty(exports, "__esModule", { value: true });
14545 var Scheduler = (function () {
14546     function Scheduler(SchedulerAction, now) {
14547         if (now === void 0) { now = Scheduler.now; }
14548         this.SchedulerAction = SchedulerAction;
14549         this.now = now;
14550     }
14551     Scheduler.prototype.schedule = function (work, delay, state) {
14552         if (delay === void 0) { delay = 0; }
14553         return new this.SchedulerAction(this, work).schedule(state, delay);
14554     };
14555     Scheduler.now = function () { return Date.now(); };
14556     return Scheduler;
14557 }());
14558 exports.Scheduler = Scheduler;
14559
14560 },{}],53:[function(require,module,exports){
14561 "use strict";
14562 var __extends = (this && this.__extends) || (function () {
14563     var extendStatics = function (d, b) {
14564         extendStatics = Object.setPrototypeOf ||
14565             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14566             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14567         return extendStatics(d, b);
14568     }
14569     return function (d, b) {
14570         extendStatics(d, b);
14571         function __() { this.constructor = d; }
14572         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14573     };
14574 })();
14575 Object.defineProperty(exports, "__esModule", { value: true });
14576 var Observable_1 = require("./Observable");
14577 var Subscriber_1 = require("./Subscriber");
14578 var Subscription_1 = require("./Subscription");
14579 var ObjectUnsubscribedError_1 = require("./util/ObjectUnsubscribedError");
14580 var SubjectSubscription_1 = require("./SubjectSubscription");
14581 var rxSubscriber_1 = require("../internal/symbol/rxSubscriber");
14582 var SubjectSubscriber = (function (_super) {
14583     __extends(SubjectSubscriber, _super);
14584     function SubjectSubscriber(destination) {
14585         var _this = _super.call(this, destination) || this;
14586         _this.destination = destination;
14587         return _this;
14588     }
14589     return SubjectSubscriber;
14590 }(Subscriber_1.Subscriber));
14591 exports.SubjectSubscriber = SubjectSubscriber;
14592 var Subject = (function (_super) {
14593     __extends(Subject, _super);
14594     function Subject() {
14595         var _this = _super.call(this) || this;
14596         _this.observers = [];
14597         _this.closed = false;
14598         _this.isStopped = false;
14599         _this.hasError = false;
14600         _this.thrownError = null;
14601         return _this;
14602     }
14603     Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
14604         return new SubjectSubscriber(this);
14605     };
14606     Subject.prototype.lift = function (operator) {
14607         var subject = new AnonymousSubject(this, this);
14608         subject.operator = operator;
14609         return subject;
14610     };
14611     Subject.prototype.next = function (value) {
14612         if (this.closed) {
14613             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
14614         }
14615         if (!this.isStopped) {
14616             var observers = this.observers;
14617             var len = observers.length;
14618             var copy = observers.slice();
14619             for (var i = 0; i < len; i++) {
14620                 copy[i].next(value);
14621             }
14622         }
14623     };
14624     Subject.prototype.error = function (err) {
14625         if (this.closed) {
14626             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
14627         }
14628         this.hasError = true;
14629         this.thrownError = err;
14630         this.isStopped = true;
14631         var observers = this.observers;
14632         var len = observers.length;
14633         var copy = observers.slice();
14634         for (var i = 0; i < len; i++) {
14635             copy[i].error(err);
14636         }
14637         this.observers.length = 0;
14638     };
14639     Subject.prototype.complete = function () {
14640         if (this.closed) {
14641             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
14642         }
14643         this.isStopped = true;
14644         var observers = this.observers;
14645         var len = observers.length;
14646         var copy = observers.slice();
14647         for (var i = 0; i < len; i++) {
14648             copy[i].complete();
14649         }
14650         this.observers.length = 0;
14651     };
14652     Subject.prototype.unsubscribe = function () {
14653         this.isStopped = true;
14654         this.closed = true;
14655         this.observers = null;
14656     };
14657     Subject.prototype._trySubscribe = function (subscriber) {
14658         if (this.closed) {
14659             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
14660         }
14661         else {
14662             return _super.prototype._trySubscribe.call(this, subscriber);
14663         }
14664     };
14665     Subject.prototype._subscribe = function (subscriber) {
14666         if (this.closed) {
14667             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
14668         }
14669         else if (this.hasError) {
14670             subscriber.error(this.thrownError);
14671             return Subscription_1.Subscription.EMPTY;
14672         }
14673         else if (this.isStopped) {
14674             subscriber.complete();
14675             return Subscription_1.Subscription.EMPTY;
14676         }
14677         else {
14678             this.observers.push(subscriber);
14679             return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
14680         }
14681     };
14682     Subject.prototype.asObservable = function () {
14683         var observable = new Observable_1.Observable();
14684         observable.source = this;
14685         return observable;
14686     };
14687     Subject.create = function (destination, source) {
14688         return new AnonymousSubject(destination, source);
14689     };
14690     return Subject;
14691 }(Observable_1.Observable));
14692 exports.Subject = Subject;
14693 var AnonymousSubject = (function (_super) {
14694     __extends(AnonymousSubject, _super);
14695     function AnonymousSubject(destination, source) {
14696         var _this = _super.call(this) || this;
14697         _this.destination = destination;
14698         _this.source = source;
14699         return _this;
14700     }
14701     AnonymousSubject.prototype.next = function (value) {
14702         var destination = this.destination;
14703         if (destination && destination.next) {
14704             destination.next(value);
14705         }
14706     };
14707     AnonymousSubject.prototype.error = function (err) {
14708         var destination = this.destination;
14709         if (destination && destination.error) {
14710             this.destination.error(err);
14711         }
14712     };
14713     AnonymousSubject.prototype.complete = function () {
14714         var destination = this.destination;
14715         if (destination && destination.complete) {
14716             this.destination.complete();
14717         }
14718     };
14719     AnonymousSubject.prototype._subscribe = function (subscriber) {
14720         var source = this.source;
14721         if (source) {
14722             return this.source.subscribe(subscriber);
14723         }
14724         else {
14725             return Subscription_1.Subscription.EMPTY;
14726         }
14727     };
14728     return AnonymousSubject;
14729 }(Subject));
14730 exports.AnonymousSubject = AnonymousSubject;
14731
14732 },{"../internal/symbol/rxSubscriber":208,"./Observable":48,"./SubjectSubscription":54,"./Subscriber":55,"./Subscription":56,"./util/ObjectUnsubscribedError":212}],54:[function(require,module,exports){
14733 "use strict";
14734 var __extends = (this && this.__extends) || (function () {
14735     var extendStatics = function (d, b) {
14736         extendStatics = Object.setPrototypeOf ||
14737             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14738             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14739         return extendStatics(d, b);
14740     }
14741     return function (d, b) {
14742         extendStatics(d, b);
14743         function __() { this.constructor = d; }
14744         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14745     };
14746 })();
14747 Object.defineProperty(exports, "__esModule", { value: true });
14748 var Subscription_1 = require("./Subscription");
14749 var SubjectSubscription = (function (_super) {
14750     __extends(SubjectSubscription, _super);
14751     function SubjectSubscription(subject, subscriber) {
14752         var _this = _super.call(this) || this;
14753         _this.subject = subject;
14754         _this.subscriber = subscriber;
14755         _this.closed = false;
14756         return _this;
14757     }
14758     SubjectSubscription.prototype.unsubscribe = function () {
14759         if (this.closed) {
14760             return;
14761         }
14762         this.closed = true;
14763         var subject = this.subject;
14764         var observers = subject.observers;
14765         this.subject = null;
14766         if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
14767             return;
14768         }
14769         var subscriberIndex = observers.indexOf(this.subscriber);
14770         if (subscriberIndex !== -1) {
14771             observers.splice(subscriberIndex, 1);
14772         }
14773     };
14774     return SubjectSubscription;
14775 }(Subscription_1.Subscription));
14776 exports.SubjectSubscription = SubjectSubscription;
14777
14778 },{"./Subscription":56}],55:[function(require,module,exports){
14779 "use strict";
14780 var __extends = (this && this.__extends) || (function () {
14781     var extendStatics = function (d, b) {
14782         extendStatics = Object.setPrototypeOf ||
14783             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
14784             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
14785         return extendStatics(d, b);
14786     }
14787     return function (d, b) {
14788         extendStatics(d, b);
14789         function __() { this.constructor = d; }
14790         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14791     };
14792 })();
14793 Object.defineProperty(exports, "__esModule", { value: true });
14794 var isFunction_1 = require("./util/isFunction");
14795 var Observer_1 = require("./Observer");
14796 var Subscription_1 = require("./Subscription");
14797 var rxSubscriber_1 = require("../internal/symbol/rxSubscriber");
14798 var config_1 = require("./config");
14799 var hostReportError_1 = require("./util/hostReportError");
14800 var Subscriber = (function (_super) {
14801     __extends(Subscriber, _super);
14802     function Subscriber(destinationOrNext, error, complete) {
14803         var _this = _super.call(this) || this;
14804         _this.syncErrorValue = null;
14805         _this.syncErrorThrown = false;
14806         _this.syncErrorThrowable = false;
14807         _this.isStopped = false;
14808         _this._parentSubscription = null;
14809         switch (arguments.length) {
14810             case 0:
14811                 _this.destination = Observer_1.empty;
14812                 break;
14813             case 1:
14814                 if (!destinationOrNext) {
14815                     _this.destination = Observer_1.empty;
14816                     break;
14817                 }
14818                 if (typeof destinationOrNext === 'object') {
14819                     if (destinationOrNext instanceof Subscriber) {
14820                         _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
14821                         _this.destination = destinationOrNext;
14822                         destinationOrNext.add(_this);
14823                     }
14824                     else {
14825                         _this.syncErrorThrowable = true;
14826                         _this.destination = new SafeSubscriber(_this, destinationOrNext);
14827                     }
14828                     break;
14829                 }
14830             default:
14831                 _this.syncErrorThrowable = true;
14832                 _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);
14833                 break;
14834         }
14835         return _this;
14836     }
14837     Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
14838     Subscriber.create = function (next, error, complete) {
14839         var subscriber = new Subscriber(next, error, complete);
14840         subscriber.syncErrorThrowable = false;
14841         return subscriber;
14842     };
14843     Subscriber.prototype.next = function (value) {
14844         if (!this.isStopped) {
14845             this._next(value);
14846         }
14847     };
14848     Subscriber.prototype.error = function (err) {
14849         if (!this.isStopped) {
14850             this.isStopped = true;
14851             this._error(err);
14852         }
14853     };
14854     Subscriber.prototype.complete = function () {
14855         if (!this.isStopped) {
14856             this.isStopped = true;
14857             this._complete();
14858         }
14859     };
14860     Subscriber.prototype.unsubscribe = function () {
14861         if (this.closed) {
14862             return;
14863         }
14864         this.isStopped = true;
14865         _super.prototype.unsubscribe.call(this);
14866     };
14867     Subscriber.prototype._next = function (value) {
14868         this.destination.next(value);
14869     };
14870     Subscriber.prototype._error = function (err) {
14871         this.destination.error(err);
14872         this.unsubscribe();
14873     };
14874     Subscriber.prototype._complete = function () {
14875         this.destination.complete();
14876         this.unsubscribe();
14877     };
14878     Subscriber.prototype._unsubscribeAndRecycle = function () {
14879         var _a = this, _parent = _a._parent, _parents = _a._parents;
14880         this._parent = null;
14881         this._parents = null;
14882         this.unsubscribe();
14883         this.closed = false;
14884         this.isStopped = false;
14885         this._parent = _parent;
14886         this._parents = _parents;
14887         this._parentSubscription = null;
14888         return this;
14889     };
14890     return Subscriber;
14891 }(Subscription_1.Subscription));
14892 exports.Subscriber = Subscriber;
14893 var SafeSubscriber = (function (_super) {
14894     __extends(SafeSubscriber, _super);
14895     function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
14896         var _this = _super.call(this) || this;
14897         _this._parentSubscriber = _parentSubscriber;
14898         var next;
14899         var context = _this;
14900         if (isFunction_1.isFunction(observerOrNext)) {
14901             next = observerOrNext;
14902         }
14903         else if (observerOrNext) {
14904             next = observerOrNext.next;
14905             error = observerOrNext.error;
14906             complete = observerOrNext.complete;
14907             if (observerOrNext !== Observer_1.empty) {
14908                 context = Object.create(observerOrNext);
14909                 if (isFunction_1.isFunction(context.unsubscribe)) {
14910                     _this.add(context.unsubscribe.bind(context));
14911                 }
14912                 context.unsubscribe = _this.unsubscribe.bind(_this);
14913             }
14914         }
14915         _this._context = context;
14916         _this._next = next;
14917         _this._error = error;
14918         _this._complete = complete;
14919         return _this;
14920     }
14921     SafeSubscriber.prototype.next = function (value) {
14922         if (!this.isStopped && this._next) {
14923             var _parentSubscriber = this._parentSubscriber;
14924             if (!config_1.config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
14925                 this.__tryOrUnsub(this._next, value);
14926             }
14927             else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
14928                 this.unsubscribe();
14929             }
14930         }
14931     };
14932     SafeSubscriber.prototype.error = function (err) {
14933         if (!this.isStopped) {
14934             var _parentSubscriber = this._parentSubscriber;
14935             var useDeprecatedSynchronousErrorHandling = config_1.config.useDeprecatedSynchronousErrorHandling;
14936             if (this._error) {
14937                 if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
14938                     this.__tryOrUnsub(this._error, err);
14939                     this.unsubscribe();
14940                 }
14941                 else {
14942                     this.__tryOrSetError(_parentSubscriber, this._error, err);
14943                     this.unsubscribe();
14944                 }
14945             }
14946             else if (!_parentSubscriber.syncErrorThrowable) {
14947                 this.unsubscribe();
14948                 if (useDeprecatedSynchronousErrorHandling) {
14949                     throw err;
14950                 }
14951                 hostReportError_1.hostReportError(err);
14952             }
14953             else {
14954                 if (useDeprecatedSynchronousErrorHandling) {
14955                     _parentSubscriber.syncErrorValue = err;
14956                     _parentSubscriber.syncErrorThrown = true;
14957                 }
14958                 else {
14959                     hostReportError_1.hostReportError(err);
14960                 }
14961                 this.unsubscribe();
14962             }
14963         }
14964     };
14965     SafeSubscriber.prototype.complete = function () {
14966         var _this = this;
14967         if (!this.isStopped) {
14968             var _parentSubscriber = this._parentSubscriber;
14969             if (this._complete) {
14970                 var wrappedComplete = function () { return _this._complete.call(_this._context); };
14971                 if (!config_1.config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
14972                     this.__tryOrUnsub(wrappedComplete);
14973                     this.unsubscribe();
14974                 }
14975                 else {
14976                     this.__tryOrSetError(_parentSubscriber, wrappedComplete);
14977                     this.unsubscribe();
14978                 }
14979             }
14980             else {
14981                 this.unsubscribe();
14982             }
14983         }
14984     };
14985     SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
14986         try {
14987             fn.call(this._context, value);
14988         }
14989         catch (err) {
14990             this.unsubscribe();
14991             if (config_1.config.useDeprecatedSynchronousErrorHandling) {
14992                 throw err;
14993             }
14994             else {
14995                 hostReportError_1.hostReportError(err);
14996             }
14997         }
14998     };
14999     SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
15000         if (!config_1.config.useDeprecatedSynchronousErrorHandling) {
15001             throw new Error('bad call');
15002         }
15003         try {
15004             fn.call(this._context, value);
15005         }
15006         catch (err) {
15007             if (config_1.config.useDeprecatedSynchronousErrorHandling) {
15008                 parent.syncErrorValue = err;
15009                 parent.syncErrorThrown = true;
15010                 return true;
15011             }
15012             else {
15013                 hostReportError_1.hostReportError(err);
15014                 return true;
15015             }
15016         }
15017         return false;
15018     };
15019     SafeSubscriber.prototype._unsubscribe = function () {
15020         var _parentSubscriber = this._parentSubscriber;
15021         this._context = null;
15022         this._parentSubscriber = null;
15023         _parentSubscriber.unsubscribe();
15024     };
15025     return SafeSubscriber;
15026 }(Subscriber));
15027 exports.SafeSubscriber = SafeSubscriber;
15028
15029 },{"../internal/symbol/rxSubscriber":208,"./Observer":49,"./Subscription":56,"./config":57,"./util/hostReportError":217,"./util/isFunction":222}],56:[function(require,module,exports){
15030 "use strict";
15031 Object.defineProperty(exports, "__esModule", { value: true });
15032 var isArray_1 = require("./util/isArray");
15033 var isObject_1 = require("./util/isObject");
15034 var isFunction_1 = require("./util/isFunction");
15035 var tryCatch_1 = require("./util/tryCatch");
15036 var errorObject_1 = require("./util/errorObject");
15037 var UnsubscriptionError_1 = require("./util/UnsubscriptionError");
15038 var Subscription = (function () {
15039     function Subscription(unsubscribe) {
15040         this.closed = false;
15041         this._parent = null;
15042         this._parents = null;
15043         this._subscriptions = null;
15044         if (unsubscribe) {
15045             this._unsubscribe = unsubscribe;
15046         }
15047     }
15048     Subscription.prototype.unsubscribe = function () {
15049         var hasErrors = false;
15050         var errors;
15051         if (this.closed) {
15052             return;
15053         }
15054         var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
15055         this.closed = true;
15056         this._parent = null;
15057         this._parents = null;
15058         this._subscriptions = null;
15059         var index = -1;
15060         var len = _parents ? _parents.length : 0;
15061         while (_parent) {
15062             _parent.remove(this);
15063             _parent = ++index < len && _parents[index] || null;
15064         }
15065         if (isFunction_1.isFunction(_unsubscribe)) {
15066             var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
15067             if (trial === errorObject_1.errorObject) {
15068                 hasErrors = true;
15069                 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
15070                     flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
15071             }
15072         }
15073         if (isArray_1.isArray(_subscriptions)) {
15074             index = -1;
15075             len = _subscriptions.length;
15076             while (++index < len) {
15077                 var sub = _subscriptions[index];
15078                 if (isObject_1.isObject(sub)) {
15079                     var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
15080                     if (trial === errorObject_1.errorObject) {
15081                         hasErrors = true;
15082                         errors = errors || [];
15083                         var err = errorObject_1.errorObject.e;
15084                         if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
15085                             errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
15086                         }
15087                         else {
15088                             errors.push(err);
15089                         }
15090                     }
15091                 }
15092             }
15093         }
15094         if (hasErrors) {
15095             throw new UnsubscriptionError_1.UnsubscriptionError(errors);
15096         }
15097     };
15098     Subscription.prototype.add = function (teardown) {
15099         if (!teardown || (teardown === Subscription.EMPTY)) {
15100             return Subscription.EMPTY;
15101         }
15102         if (teardown === this) {
15103             return this;
15104         }
15105         var subscription = teardown;
15106         switch (typeof teardown) {
15107             case 'function':
15108                 subscription = new Subscription(teardown);
15109             case 'object':
15110                 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
15111                     return subscription;
15112                 }
15113                 else if (this.closed) {
15114                     subscription.unsubscribe();
15115                     return subscription;
15116                 }
15117                 else if (typeof subscription._addParent !== 'function') {
15118                     var tmp = subscription;
15119                     subscription = new Subscription();
15120                     subscription._subscriptions = [tmp];
15121                 }
15122                 break;
15123             default:
15124                 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
15125         }
15126         var subscriptions = this._subscriptions || (this._subscriptions = []);
15127         subscriptions.push(subscription);
15128         subscription._addParent(this);
15129         return subscription;
15130     };
15131     Subscription.prototype.remove = function (subscription) {
15132         var subscriptions = this._subscriptions;
15133         if (subscriptions) {
15134             var subscriptionIndex = subscriptions.indexOf(subscription);
15135             if (subscriptionIndex !== -1) {
15136                 subscriptions.splice(subscriptionIndex, 1);
15137             }
15138         }
15139     };
15140     Subscription.prototype._addParent = function (parent) {
15141         var _a = this, _parent = _a._parent, _parents = _a._parents;
15142         if (!_parent || _parent === parent) {
15143             this._parent = parent;
15144         }
15145         else if (!_parents) {
15146             this._parents = [parent];
15147         }
15148         else if (_parents.indexOf(parent) === -1) {
15149             _parents.push(parent);
15150         }
15151     };
15152     Subscription.EMPTY = (function (empty) {
15153         empty.closed = true;
15154         return empty;
15155     }(new Subscription()));
15156     return Subscription;
15157 }());
15158 exports.Subscription = Subscription;
15159 function flattenUnsubscriptionErrors(errors) {
15160     return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
15161 }
15162
15163 },{"./util/UnsubscriptionError":214,"./util/errorObject":216,"./util/isArray":219,"./util/isFunction":222,"./util/isObject":226,"./util/tryCatch":240}],57:[function(require,module,exports){
15164 "use strict";
15165 Object.defineProperty(exports, "__esModule", { value: true });
15166 var _enable_super_gross_mode_that_will_cause_bad_things = false;
15167 exports.config = {
15168     Promise: undefined,
15169     set useDeprecatedSynchronousErrorHandling(value) {
15170         if (value) {
15171             var error = new Error();
15172             console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
15173         }
15174         else if (_enable_super_gross_mode_that_will_cause_bad_things) {
15175             console.log('RxJS: Back to a better error behavior. Thank you. <3');
15176         }
15177         _enable_super_gross_mode_that_will_cause_bad_things = value;
15178     },
15179     get useDeprecatedSynchronousErrorHandling() {
15180         return _enable_super_gross_mode_that_will_cause_bad_things;
15181     },
15182 };
15183
15184 },{}],58:[function(require,module,exports){
15185 "use strict";
15186 var __extends = (this && this.__extends) || (function () {
15187     var extendStatics = function (d, b) {
15188         extendStatics = Object.setPrototypeOf ||
15189             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15190             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15191         return extendStatics(d, b);
15192     }
15193     return function (d, b) {
15194         extendStatics(d, b);
15195         function __() { this.constructor = d; }
15196         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15197     };
15198 })();
15199 Object.defineProperty(exports, "__esModule", { value: true });
15200 var Subject_1 = require("../Subject");
15201 var Observable_1 = require("../Observable");
15202 var Subscriber_1 = require("../Subscriber");
15203 var Subscription_1 = require("../Subscription");
15204 var refCount_1 = require("../operators/refCount");
15205 var ConnectableObservable = (function (_super) {
15206     __extends(ConnectableObservable, _super);
15207     function ConnectableObservable(source, subjectFactory) {
15208         var _this = _super.call(this) || this;
15209         _this.source = source;
15210         _this.subjectFactory = subjectFactory;
15211         _this._refCount = 0;
15212         _this._isComplete = false;
15213         return _this;
15214     }
15215     ConnectableObservable.prototype._subscribe = function (subscriber) {
15216         return this.getSubject().subscribe(subscriber);
15217     };
15218     ConnectableObservable.prototype.getSubject = function () {
15219         var subject = this._subject;
15220         if (!subject || subject.isStopped) {
15221             this._subject = this.subjectFactory();
15222         }
15223         return this._subject;
15224     };
15225     ConnectableObservable.prototype.connect = function () {
15226         var connection = this._connection;
15227         if (!connection) {
15228             this._isComplete = false;
15229             connection = this._connection = new Subscription_1.Subscription();
15230             connection.add(this.source
15231                 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
15232             if (connection.closed) {
15233                 this._connection = null;
15234                 connection = Subscription_1.Subscription.EMPTY;
15235             }
15236             else {
15237                 this._connection = connection;
15238             }
15239         }
15240         return connection;
15241     };
15242     ConnectableObservable.prototype.refCount = function () {
15243         return refCount_1.refCount()(this);
15244     };
15245     return ConnectableObservable;
15246 }(Observable_1.Observable));
15247 exports.ConnectableObservable = ConnectableObservable;
15248 var connectableProto = ConnectableObservable.prototype;
15249 exports.connectableObservableDescriptor = {
15250     operator: { value: null },
15251     _refCount: { value: 0, writable: true },
15252     _subject: { value: null, writable: true },
15253     _connection: { value: null, writable: true },
15254     _subscribe: { value: connectableProto._subscribe },
15255     _isComplete: { value: connectableProto._isComplete, writable: true },
15256     getSubject: { value: connectableProto.getSubject },
15257     connect: { value: connectableProto.connect },
15258     refCount: { value: connectableProto.refCount }
15259 };
15260 var ConnectableSubscriber = (function (_super) {
15261     __extends(ConnectableSubscriber, _super);
15262     function ConnectableSubscriber(destination, connectable) {
15263         var _this = _super.call(this, destination) || this;
15264         _this.connectable = connectable;
15265         return _this;
15266     }
15267     ConnectableSubscriber.prototype._error = function (err) {
15268         this._unsubscribe();
15269         _super.prototype._error.call(this, err);
15270     };
15271     ConnectableSubscriber.prototype._complete = function () {
15272         this.connectable._isComplete = true;
15273         this._unsubscribe();
15274         _super.prototype._complete.call(this);
15275     };
15276     ConnectableSubscriber.prototype._unsubscribe = function () {
15277         var connectable = this.connectable;
15278         if (connectable) {
15279             this.connectable = null;
15280             var connection = connectable._connection;
15281             connectable._refCount = 0;
15282             connectable._subject = null;
15283             connectable._connection = null;
15284             if (connection) {
15285                 connection.unsubscribe();
15286             }
15287         }
15288     };
15289     return ConnectableSubscriber;
15290 }(Subject_1.SubjectSubscriber));
15291 var RefCountOperator = (function () {
15292     function RefCountOperator(connectable) {
15293         this.connectable = connectable;
15294     }
15295     RefCountOperator.prototype.call = function (subscriber, source) {
15296         var connectable = this.connectable;
15297         connectable._refCount++;
15298         var refCounter = new RefCountSubscriber(subscriber, connectable);
15299         var subscription = source.subscribe(refCounter);
15300         if (!refCounter.closed) {
15301             refCounter.connection = connectable.connect();
15302         }
15303         return subscription;
15304     };
15305     return RefCountOperator;
15306 }());
15307 var RefCountSubscriber = (function (_super) {
15308     __extends(RefCountSubscriber, _super);
15309     function RefCountSubscriber(destination, connectable) {
15310         var _this = _super.call(this, destination) || this;
15311         _this.connectable = connectable;
15312         return _this;
15313     }
15314     RefCountSubscriber.prototype._unsubscribe = function () {
15315         var connectable = this.connectable;
15316         if (!connectable) {
15317             this.connection = null;
15318             return;
15319         }
15320         this.connectable = null;
15321         var refCount = connectable._refCount;
15322         if (refCount <= 0) {
15323             this.connection = null;
15324             return;
15325         }
15326         connectable._refCount = refCount - 1;
15327         if (refCount > 1) {
15328             this.connection = null;
15329             return;
15330         }
15331         var connection = this.connection;
15332         var sharedConnection = connectable._connection;
15333         this.connection = null;
15334         if (sharedConnection && (!connection || sharedConnection === connection)) {
15335             sharedConnection.unsubscribe();
15336         }
15337     };
15338     return RefCountSubscriber;
15339 }(Subscriber_1.Subscriber));
15340
15341 },{"../Observable":48,"../Subject":53,"../Subscriber":55,"../Subscription":56,"../operators/refCount":150}],59:[function(require,module,exports){
15342 "use strict";
15343 var __extends = (this && this.__extends) || (function () {
15344     var extendStatics = function (d, b) {
15345         extendStatics = Object.setPrototypeOf ||
15346             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15347             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15348         return extendStatics(d, b);
15349     }
15350     return function (d, b) {
15351         extendStatics(d, b);
15352         function __() { this.constructor = d; }
15353         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15354     };
15355 })();
15356 Object.defineProperty(exports, "__esModule", { value: true });
15357 var Observable_1 = require("../Observable");
15358 var asap_1 = require("../scheduler/asap");
15359 var isNumeric_1 = require("../util/isNumeric");
15360 var SubscribeOnObservable = (function (_super) {
15361     __extends(SubscribeOnObservable, _super);
15362     function SubscribeOnObservable(source, delayTime, scheduler) {
15363         if (delayTime === void 0) { delayTime = 0; }
15364         if (scheduler === void 0) { scheduler = asap_1.asap; }
15365         var _this = _super.call(this) || this;
15366         _this.source = source;
15367         _this.delayTime = delayTime;
15368         _this.scheduler = scheduler;
15369         if (!isNumeric_1.isNumeric(delayTime) || delayTime < 0) {
15370             _this.delayTime = 0;
15371         }
15372         if (!scheduler || typeof scheduler.schedule !== 'function') {
15373             _this.scheduler = asap_1.asap;
15374         }
15375         return _this;
15376     }
15377     SubscribeOnObservable.create = function (source, delay, scheduler) {
15378         if (delay === void 0) { delay = 0; }
15379         if (scheduler === void 0) { scheduler = asap_1.asap; }
15380         return new SubscribeOnObservable(source, delay, scheduler);
15381     };
15382     SubscribeOnObservable.dispatch = function (arg) {
15383         var source = arg.source, subscriber = arg.subscriber;
15384         return this.add(source.subscribe(subscriber));
15385     };
15386     SubscribeOnObservable.prototype._subscribe = function (subscriber) {
15387         var delay = this.delayTime;
15388         var source = this.source;
15389         var scheduler = this.scheduler;
15390         return scheduler.schedule(SubscribeOnObservable.dispatch, delay, {
15391             source: source, subscriber: subscriber
15392         });
15393     };
15394     return SubscribeOnObservable;
15395 }(Observable_1.Observable));
15396 exports.SubscribeOnObservable = SubscribeOnObservable;
15397
15398 },{"../Observable":48,"../scheduler/asap":203,"../util/isNumeric":225}],60:[function(require,module,exports){
15399 "use strict";
15400 Object.defineProperty(exports, "__esModule", { value: true });
15401 var Observable_1 = require("../Observable");
15402 var AsyncSubject_1 = require("../AsyncSubject");
15403 var map_1 = require("../operators/map");
15404 var canReportError_1 = require("../util/canReportError");
15405 var isArray_1 = require("../util/isArray");
15406 var isScheduler_1 = require("../util/isScheduler");
15407 function bindCallback(callbackFunc, resultSelector, scheduler) {
15408     if (resultSelector) {
15409         if (isScheduler_1.isScheduler(resultSelector)) {
15410             scheduler = resultSelector;
15411         }
15412         else {
15413             return function () {
15414                 var args = [];
15415                 for (var _i = 0; _i < arguments.length; _i++) {
15416                     args[_i] = arguments[_i];
15417                 }
15418                 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); }));
15419             };
15420         }
15421     }
15422     return function () {
15423         var args = [];
15424         for (var _i = 0; _i < arguments.length; _i++) {
15425             args[_i] = arguments[_i];
15426         }
15427         var context = this;
15428         var subject;
15429         var params = {
15430             context: context,
15431             subject: subject,
15432             callbackFunc: callbackFunc,
15433             scheduler: scheduler,
15434         };
15435         return new Observable_1.Observable(function (subscriber) {
15436             if (!scheduler) {
15437                 if (!subject) {
15438                     subject = new AsyncSubject_1.AsyncSubject();
15439                     var handler = function () {
15440                         var innerArgs = [];
15441                         for (var _i = 0; _i < arguments.length; _i++) {
15442                             innerArgs[_i] = arguments[_i];
15443                         }
15444                         subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
15445                         subject.complete();
15446                     };
15447                     try {
15448                         callbackFunc.apply(context, args.concat([handler]));
15449                     }
15450                     catch (err) {
15451                         if (canReportError_1.canReportError(subject)) {
15452                             subject.error(err);
15453                         }
15454                         else {
15455                             console.warn(err);
15456                         }
15457                     }
15458                 }
15459                 return subject.subscribe(subscriber);
15460             }
15461             else {
15462                 var state = {
15463                     args: args, subscriber: subscriber, params: params,
15464                 };
15465                 return scheduler.schedule(dispatch, 0, state);
15466             }
15467         });
15468     };
15469 }
15470 exports.bindCallback = bindCallback;
15471 function dispatch(state) {
15472     var _this = this;
15473     var self = this;
15474     var args = state.args, subscriber = state.subscriber, params = state.params;
15475     var callbackFunc = params.callbackFunc, context = params.context, scheduler = params.scheduler;
15476     var subject = params.subject;
15477     if (!subject) {
15478         subject = params.subject = new AsyncSubject_1.AsyncSubject();
15479         var handler = function () {
15480             var innerArgs = [];
15481             for (var _i = 0; _i < arguments.length; _i++) {
15482                 innerArgs[_i] = arguments[_i];
15483             }
15484             var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
15485             _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject }));
15486         };
15487         try {
15488             callbackFunc.apply(context, args.concat([handler]));
15489         }
15490         catch (err) {
15491             subject.error(err);
15492         }
15493     }
15494     this.add(subject.subscribe(subscriber));
15495 }
15496 function dispatchNext(state) {
15497     var value = state.value, subject = state.subject;
15498     subject.next(value);
15499     subject.complete();
15500 }
15501 function dispatchError(state) {
15502     var err = state.err, subject = state.subject;
15503     subject.error(err);
15504 }
15505
15506 },{"../AsyncSubject":44,"../Observable":48,"../operators/map":128,"../util/canReportError":215,"../util/isArray":219,"../util/isScheduler":229}],61:[function(require,module,exports){
15507 "use strict";
15508 Object.defineProperty(exports, "__esModule", { value: true });
15509 var Observable_1 = require("../Observable");
15510 var AsyncSubject_1 = require("../AsyncSubject");
15511 var map_1 = require("../operators/map");
15512 var canReportError_1 = require("../util/canReportError");
15513 var isScheduler_1 = require("../util/isScheduler");
15514 var isArray_1 = require("../util/isArray");
15515 function bindNodeCallback(callbackFunc, resultSelector, scheduler) {
15516     if (resultSelector) {
15517         if (isScheduler_1.isScheduler(resultSelector)) {
15518             scheduler = resultSelector;
15519         }
15520         else {
15521             return function () {
15522                 var args = [];
15523                 for (var _i = 0; _i < arguments.length; _i++) {
15524                     args[_i] = arguments[_i];
15525                 }
15526                 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); }));
15527             };
15528         }
15529     }
15530     return function () {
15531         var args = [];
15532         for (var _i = 0; _i < arguments.length; _i++) {
15533             args[_i] = arguments[_i];
15534         }
15535         var params = {
15536             subject: undefined,
15537             args: args,
15538             callbackFunc: callbackFunc,
15539             scheduler: scheduler,
15540             context: this,
15541         };
15542         return new Observable_1.Observable(function (subscriber) {
15543             var context = params.context;
15544             var subject = params.subject;
15545             if (!scheduler) {
15546                 if (!subject) {
15547                     subject = params.subject = new AsyncSubject_1.AsyncSubject();
15548                     var handler = function () {
15549                         var innerArgs = [];
15550                         for (var _i = 0; _i < arguments.length; _i++) {
15551                             innerArgs[_i] = arguments[_i];
15552                         }
15553                         var err = innerArgs.shift();
15554                         if (err) {
15555                             subject.error(err);
15556                             return;
15557                         }
15558                         subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
15559                         subject.complete();
15560                     };
15561                     try {
15562                         callbackFunc.apply(context, args.concat([handler]));
15563                     }
15564                     catch (err) {
15565                         if (canReportError_1.canReportError(subject)) {
15566                             subject.error(err);
15567                         }
15568                         else {
15569                             console.warn(err);
15570                         }
15571                     }
15572                 }
15573                 return subject.subscribe(subscriber);
15574             }
15575             else {
15576                 return scheduler.schedule(dispatch, 0, { params: params, subscriber: subscriber, context: context });
15577             }
15578         });
15579     };
15580 }
15581 exports.bindNodeCallback = bindNodeCallback;
15582 function dispatch(state) {
15583     var _this = this;
15584     var params = state.params, subscriber = state.subscriber, context = state.context;
15585     var callbackFunc = params.callbackFunc, args = params.args, scheduler = params.scheduler;
15586     var subject = params.subject;
15587     if (!subject) {
15588         subject = params.subject = new AsyncSubject_1.AsyncSubject();
15589         var handler = function () {
15590             var innerArgs = [];
15591             for (var _i = 0; _i < arguments.length; _i++) {
15592                 innerArgs[_i] = arguments[_i];
15593             }
15594             var err = innerArgs.shift();
15595             if (err) {
15596                 _this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject }));
15597             }
15598             else {
15599                 var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
15600                 _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject }));
15601             }
15602         };
15603         try {
15604             callbackFunc.apply(context, args.concat([handler]));
15605         }
15606         catch (err) {
15607             this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject }));
15608         }
15609     }
15610     this.add(subject.subscribe(subscriber));
15611 }
15612 function dispatchNext(arg) {
15613     var value = arg.value, subject = arg.subject;
15614     subject.next(value);
15615     subject.complete();
15616 }
15617 function dispatchError(arg) {
15618     var err = arg.err, subject = arg.subject;
15619     subject.error(err);
15620 }
15621
15622 },{"../AsyncSubject":44,"../Observable":48,"../operators/map":128,"../util/canReportError":215,"../util/isArray":219,"../util/isScheduler":229}],62:[function(require,module,exports){
15623 "use strict";
15624 var __extends = (this && this.__extends) || (function () {
15625     var extendStatics = function (d, b) {
15626         extendStatics = Object.setPrototypeOf ||
15627             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15628             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15629         return extendStatics(d, b);
15630     }
15631     return function (d, b) {
15632         extendStatics(d, b);
15633         function __() { this.constructor = d; }
15634         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15635     };
15636 })();
15637 Object.defineProperty(exports, "__esModule", { value: true });
15638 var isScheduler_1 = require("../util/isScheduler");
15639 var isArray_1 = require("../util/isArray");
15640 var OuterSubscriber_1 = require("../OuterSubscriber");
15641 var subscribeToResult_1 = require("../util/subscribeToResult");
15642 var fromArray_1 = require("./fromArray");
15643 var NONE = {};
15644 function combineLatest() {
15645     var observables = [];
15646     for (var _i = 0; _i < arguments.length; _i++) {
15647         observables[_i] = arguments[_i];
15648     }
15649     var resultSelector = null;
15650     var scheduler = null;
15651     if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
15652         scheduler = observables.pop();
15653     }
15654     if (typeof observables[observables.length - 1] === 'function') {
15655         resultSelector = observables.pop();
15656     }
15657     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
15658         observables = observables[0];
15659     }
15660     return fromArray_1.fromArray(observables, scheduler).lift(new CombineLatestOperator(resultSelector));
15661 }
15662 exports.combineLatest = combineLatest;
15663 var CombineLatestOperator = (function () {
15664     function CombineLatestOperator(resultSelector) {
15665         this.resultSelector = resultSelector;
15666     }
15667     CombineLatestOperator.prototype.call = function (subscriber, source) {
15668         return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));
15669     };
15670     return CombineLatestOperator;
15671 }());
15672 exports.CombineLatestOperator = CombineLatestOperator;
15673 var CombineLatestSubscriber = (function (_super) {
15674     __extends(CombineLatestSubscriber, _super);
15675     function CombineLatestSubscriber(destination, resultSelector) {
15676         var _this = _super.call(this, destination) || this;
15677         _this.resultSelector = resultSelector;
15678         _this.active = 0;
15679         _this.values = [];
15680         _this.observables = [];
15681         return _this;
15682     }
15683     CombineLatestSubscriber.prototype._next = function (observable) {
15684         this.values.push(NONE);
15685         this.observables.push(observable);
15686     };
15687     CombineLatestSubscriber.prototype._complete = function () {
15688         var observables = this.observables;
15689         var len = observables.length;
15690         if (len === 0) {
15691             this.destination.complete();
15692         }
15693         else {
15694             this.active = len;
15695             this.toRespond = len;
15696             for (var i = 0; i < len; i++) {
15697                 var observable = observables[i];
15698                 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
15699             }
15700         }
15701     };
15702     CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
15703         if ((this.active -= 1) === 0) {
15704             this.destination.complete();
15705         }
15706     };
15707     CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15708         var values = this.values;
15709         var oldVal = values[outerIndex];
15710         var toRespond = !this.toRespond
15711             ? 0
15712             : oldVal === NONE ? --this.toRespond : this.toRespond;
15713         values[outerIndex] = innerValue;
15714         if (toRespond === 0) {
15715             if (this.resultSelector) {
15716                 this._tryResultSelector(values);
15717             }
15718             else {
15719                 this.destination.next(values.slice());
15720             }
15721         }
15722     };
15723     CombineLatestSubscriber.prototype._tryResultSelector = function (values) {
15724         var result;
15725         try {
15726             result = this.resultSelector.apply(this, values);
15727         }
15728         catch (err) {
15729             this.destination.error(err);
15730             return;
15731         }
15732         this.destination.next(result);
15733     };
15734     return CombineLatestSubscriber;
15735 }(OuterSubscriber_1.OuterSubscriber));
15736 exports.CombineLatestSubscriber = CombineLatestSubscriber;
15737
15738 },{"../OuterSubscriber":50,"../util/isArray":219,"../util/isScheduler":229,"../util/subscribeToResult":238,"./fromArray":68}],63:[function(require,module,exports){
15739 "use strict";
15740 Object.defineProperty(exports, "__esModule", { value: true });
15741 var isScheduler_1 = require("../util/isScheduler");
15742 var of_1 = require("./of");
15743 var from_1 = require("./from");
15744 var concatAll_1 = require("../operators/concatAll");
15745 function concat() {
15746     var observables = [];
15747     for (var _i = 0; _i < arguments.length; _i++) {
15748         observables[_i] = arguments[_i];
15749     }
15750     if (observables.length === 1 || (observables.length === 2 && isScheduler_1.isScheduler(observables[1]))) {
15751         return from_1.from(observables[0]);
15752     }
15753     return concatAll_1.concatAll()(of_1.of.apply(void 0, observables));
15754 }
15755 exports.concat = concat;
15756
15757 },{"../operators/concatAll":100,"../util/isScheduler":229,"./from":67,"./of":79}],64:[function(require,module,exports){
15758 "use strict";
15759 Object.defineProperty(exports, "__esModule", { value: true });
15760 var Observable_1 = require("../Observable");
15761 var from_1 = require("./from");
15762 var empty_1 = require("./empty");
15763 function defer(observableFactory) {
15764     return new Observable_1.Observable(function (subscriber) {
15765         var input;
15766         try {
15767             input = observableFactory();
15768         }
15769         catch (err) {
15770             subscriber.error(err);
15771             return undefined;
15772         }
15773         var source = input ? from_1.from(input) : empty_1.empty();
15774         return source.subscribe(subscriber);
15775     });
15776 }
15777 exports.defer = defer;
15778
15779 },{"../Observable":48,"./empty":65,"./from":67}],65:[function(require,module,exports){
15780 "use strict";
15781 Object.defineProperty(exports, "__esModule", { value: true });
15782 var Observable_1 = require("../Observable");
15783 exports.EMPTY = new Observable_1.Observable(function (subscriber) { return subscriber.complete(); });
15784 function empty(scheduler) {
15785     return scheduler ? emptyScheduled(scheduler) : exports.EMPTY;
15786 }
15787 exports.empty = empty;
15788 function emptyScheduled(scheduler) {
15789     return new Observable_1.Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); });
15790 }
15791 exports.emptyScheduled = emptyScheduled;
15792
15793 },{"../Observable":48}],66:[function(require,module,exports){
15794 "use strict";
15795 var __extends = (this && this.__extends) || (function () {
15796     var extendStatics = function (d, b) {
15797         extendStatics = Object.setPrototypeOf ||
15798             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
15799             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
15800         return extendStatics(d, b);
15801     }
15802     return function (d, b) {
15803         extendStatics(d, b);
15804         function __() { this.constructor = d; }
15805         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15806     };
15807 })();
15808 Object.defineProperty(exports, "__esModule", { value: true });
15809 var Observable_1 = require("../Observable");
15810 var isArray_1 = require("../util/isArray");
15811 var empty_1 = require("./empty");
15812 var subscribeToResult_1 = require("../util/subscribeToResult");
15813 var OuterSubscriber_1 = require("../OuterSubscriber");
15814 var map_1 = require("../operators/map");
15815 function forkJoin() {
15816     var sources = [];
15817     for (var _i = 0; _i < arguments.length; _i++) {
15818         sources[_i] = arguments[_i];
15819     }
15820     var resultSelector;
15821     if (typeof sources[sources.length - 1] === 'function') {
15822         resultSelector = sources.pop();
15823     }
15824     if (sources.length === 1 && isArray_1.isArray(sources[0])) {
15825         sources = sources[0];
15826     }
15827     if (sources.length === 0) {
15828         return empty_1.EMPTY;
15829     }
15830     if (resultSelector) {
15831         return forkJoin(sources).pipe(map_1.map(function (args) { return resultSelector.apply(void 0, args); }));
15832     }
15833     return new Observable_1.Observable(function (subscriber) {
15834         return new ForkJoinSubscriber(subscriber, sources);
15835     });
15836 }
15837 exports.forkJoin = forkJoin;
15838 var ForkJoinSubscriber = (function (_super) {
15839     __extends(ForkJoinSubscriber, _super);
15840     function ForkJoinSubscriber(destination, sources) {
15841         var _this = _super.call(this, destination) || this;
15842         _this.sources = sources;
15843         _this.completed = 0;
15844         _this.haveValues = 0;
15845         var len = sources.length;
15846         _this.values = new Array(len);
15847         for (var i = 0; i < len; i++) {
15848             var source = sources[i];
15849             var innerSubscription = subscribeToResult_1.subscribeToResult(_this, source, null, i);
15850             if (innerSubscription) {
15851                 _this.add(innerSubscription);
15852             }
15853         }
15854         return _this;
15855     }
15856     ForkJoinSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15857         this.values[outerIndex] = innerValue;
15858         if (!innerSub._hasValue) {
15859             innerSub._hasValue = true;
15860             this.haveValues++;
15861         }
15862     };
15863     ForkJoinSubscriber.prototype.notifyComplete = function (innerSub) {
15864         var _a = this, destination = _a.destination, haveValues = _a.haveValues, values = _a.values;
15865         var len = values.length;
15866         if (!innerSub._hasValue) {
15867             destination.complete();
15868             return;
15869         }
15870         this.completed++;
15871         if (this.completed !== len) {
15872             return;
15873         }
15874         if (haveValues === len) {
15875             destination.next(values);
15876         }
15877         destination.complete();
15878     };
15879     return ForkJoinSubscriber;
15880 }(OuterSubscriber_1.OuterSubscriber));
15881
15882 },{"../Observable":48,"../OuterSubscriber":50,"../operators/map":128,"../util/isArray":219,"../util/subscribeToResult":238,"./empty":65}],67:[function(require,module,exports){
15883 "use strict";
15884 Object.defineProperty(exports, "__esModule", { value: true });
15885 var Observable_1 = require("../Observable");
15886 var isPromise_1 = require("../util/isPromise");
15887 var isArrayLike_1 = require("../util/isArrayLike");
15888 var isInteropObservable_1 = require("../util/isInteropObservable");
15889 var isIterable_1 = require("../util/isIterable");
15890 var fromArray_1 = require("./fromArray");
15891 var fromPromise_1 = require("./fromPromise");
15892 var fromIterable_1 = require("./fromIterable");
15893 var fromObservable_1 = require("./fromObservable");
15894 var subscribeTo_1 = require("../util/subscribeTo");
15895 function from(input, scheduler) {
15896     if (!scheduler) {
15897         if (input instanceof Observable_1.Observable) {
15898             return input;
15899         }
15900         return new Observable_1.Observable(subscribeTo_1.subscribeTo(input));
15901     }
15902     if (input != null) {
15903         if (isInteropObservable_1.isInteropObservable(input)) {
15904             return fromObservable_1.fromObservable(input, scheduler);
15905         }
15906         else if (isPromise_1.isPromise(input)) {
15907             return fromPromise_1.fromPromise(input, scheduler);
15908         }
15909         else if (isArrayLike_1.isArrayLike(input)) {
15910             return fromArray_1.fromArray(input, scheduler);
15911         }
15912         else if (isIterable_1.isIterable(input) || typeof input === 'string') {
15913             return fromIterable_1.fromIterable(input, scheduler);
15914         }
15915     }
15916     throw new TypeError((input !== null && typeof input || input) + ' is not observable');
15917 }
15918 exports.from = from;
15919
15920 },{"../Observable":48,"../util/isArrayLike":220,"../util/isInteropObservable":223,"../util/isIterable":224,"../util/isPromise":228,"../util/subscribeTo":233,"./fromArray":68,"./fromIterable":71,"./fromObservable":72,"./fromPromise":73}],68:[function(require,module,exports){
15921 "use strict";
15922 Object.defineProperty(exports, "__esModule", { value: true });
15923 var Observable_1 = require("../Observable");
15924 var Subscription_1 = require("../Subscription");
15925 var subscribeToArray_1 = require("../util/subscribeToArray");
15926 function fromArray(input, scheduler) {
15927     if (!scheduler) {
15928         return new Observable_1.Observable(subscribeToArray_1.subscribeToArray(input));
15929     }
15930     else {
15931         return new Observable_1.Observable(function (subscriber) {
15932             var sub = new Subscription_1.Subscription();
15933             var i = 0;
15934             sub.add(scheduler.schedule(function () {
15935                 if (i === input.length) {
15936                     subscriber.complete();
15937                     return;
15938                 }
15939                 subscriber.next(input[i++]);
15940                 if (!subscriber.closed) {
15941                     sub.add(this.schedule());
15942                 }
15943             }));
15944             return sub;
15945         });
15946     }
15947 }
15948 exports.fromArray = fromArray;
15949
15950 },{"../Observable":48,"../Subscription":56,"../util/subscribeToArray":234}],69:[function(require,module,exports){
15951 "use strict";
15952 Object.defineProperty(exports, "__esModule", { value: true });
15953 var Observable_1 = require("../Observable");
15954 var isArray_1 = require("../util/isArray");
15955 var isFunction_1 = require("../util/isFunction");
15956 var map_1 = require("../operators/map");
15957 var toString = Object.prototype.toString;
15958 function fromEvent(target, eventName, options, resultSelector) {
15959     if (isFunction_1.isFunction(options)) {
15960         resultSelector = options;
15961         options = undefined;
15962     }
15963     if (resultSelector) {
15964         return fromEvent(target, eventName, options).pipe(map_1.map(function (args) { return isArray_1.isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
15965     }
15966     return new Observable_1.Observable(function (subscriber) {
15967         function handler(e) {
15968             if (arguments.length > 1) {
15969                 subscriber.next(Array.prototype.slice.call(arguments));
15970             }
15971             else {
15972                 subscriber.next(e);
15973             }
15974         }
15975         setupSubscription(target, eventName, handler, subscriber, options);
15976     });
15977 }
15978 exports.fromEvent = fromEvent;
15979 function setupSubscription(sourceObj, eventName, handler, subscriber, options) {
15980     var unsubscribe;
15981     if (isEventTarget(sourceObj)) {
15982         var source_1 = sourceObj;
15983         sourceObj.addEventListener(eventName, handler, options);
15984         unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); };
15985     }
15986     else if (isJQueryStyleEventEmitter(sourceObj)) {
15987         var source_2 = sourceObj;
15988         sourceObj.on(eventName, handler);
15989         unsubscribe = function () { return source_2.off(eventName, handler); };
15990     }
15991     else if (isNodeStyleEventEmitter(sourceObj)) {
15992         var source_3 = sourceObj;
15993         sourceObj.addListener(eventName, handler);
15994         unsubscribe = function () { return source_3.removeListener(eventName, handler); };
15995     }
15996     else if (sourceObj && sourceObj.length) {
15997         for (var i = 0, len = sourceObj.length; i < len; i++) {
15998             setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
15999         }
16000     }
16001     else {
16002         throw new TypeError('Invalid event target');
16003     }
16004     subscriber.add(unsubscribe);
16005 }
16006 function isNodeStyleEventEmitter(sourceObj) {
16007     return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
16008 }
16009 function isJQueryStyleEventEmitter(sourceObj) {
16010     return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
16011 }
16012 function isEventTarget(sourceObj) {
16013     return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
16014 }
16015
16016 },{"../Observable":48,"../operators/map":128,"../util/isArray":219,"../util/isFunction":222}],70:[function(require,module,exports){
16017 "use strict";
16018 Object.defineProperty(exports, "__esModule", { value: true });
16019 var Observable_1 = require("../Observable");
16020 var isArray_1 = require("../util/isArray");
16021 var isFunction_1 = require("../util/isFunction");
16022 var map_1 = require("../operators/map");
16023 function fromEventPattern(addHandler, removeHandler, resultSelector) {
16024     if (resultSelector) {
16025         return fromEventPattern(addHandler, removeHandler).pipe(map_1.map(function (args) { return isArray_1.isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
16026     }
16027     return new Observable_1.Observable(function (subscriber) {
16028         var handler = function () {
16029             var e = [];
16030             for (var _i = 0; _i < arguments.length; _i++) {
16031                 e[_i] = arguments[_i];
16032             }
16033             return subscriber.next(e.length === 1 ? e[0] : e);
16034         };
16035         var retValue;
16036         try {
16037             retValue = addHandler(handler);
16038         }
16039         catch (err) {
16040             subscriber.error(err);
16041             return undefined;
16042         }
16043         if (!isFunction_1.isFunction(removeHandler)) {
16044             return undefined;
16045         }
16046         return function () { return removeHandler(handler, retValue); };
16047     });
16048 }
16049 exports.fromEventPattern = fromEventPattern;
16050
16051 },{"../Observable":48,"../operators/map":128,"../util/isArray":219,"../util/isFunction":222}],71:[function(require,module,exports){
16052 "use strict";
16053 Object.defineProperty(exports, "__esModule", { value: true });
16054 var Observable_1 = require("../Observable");
16055 var Subscription_1 = require("../Subscription");
16056 var iterator_1 = require("../symbol/iterator");
16057 var subscribeToIterable_1 = require("../util/subscribeToIterable");
16058 function fromIterable(input, scheduler) {
16059     if (!input) {
16060         throw new Error('Iterable cannot be null');
16061     }
16062     if (!scheduler) {
16063         return new Observable_1.Observable(subscribeToIterable_1.subscribeToIterable(input));
16064     }
16065     else {
16066         return new Observable_1.Observable(function (subscriber) {
16067             var sub = new Subscription_1.Subscription();
16068             var iterator;
16069             sub.add(function () {
16070                 if (iterator && typeof iterator.return === 'function') {
16071                     iterator.return();
16072                 }
16073             });
16074             sub.add(scheduler.schedule(function () {
16075                 iterator = input[iterator_1.iterator]();
16076                 sub.add(scheduler.schedule(function () {
16077                     if (subscriber.closed) {
16078                         return;
16079                     }
16080                     var value;
16081                     var done;
16082                     try {
16083                         var result = iterator.next();
16084                         value = result.value;
16085                         done = result.done;
16086                     }
16087                     catch (err) {
16088                         subscriber.error(err);
16089                         return;
16090                     }
16091                     if (done) {
16092                         subscriber.complete();
16093                     }
16094                     else {
16095                         subscriber.next(value);
16096                         this.schedule();
16097                     }
16098                 }));
16099             }));
16100             return sub;
16101         });
16102     }
16103 }
16104 exports.fromIterable = fromIterable;
16105
16106 },{"../Observable":48,"../Subscription":56,"../symbol/iterator":206,"../util/subscribeToIterable":235}],72:[function(require,module,exports){
16107 "use strict";
16108 Object.defineProperty(exports, "__esModule", { value: true });
16109 var Observable_1 = require("../Observable");
16110 var Subscription_1 = require("../Subscription");
16111 var observable_1 = require("../symbol/observable");
16112 var subscribeToObservable_1 = require("../util/subscribeToObservable");
16113 function fromObservable(input, scheduler) {
16114     if (!scheduler) {
16115         return new Observable_1.Observable(subscribeToObservable_1.subscribeToObservable(input));
16116     }
16117     else {
16118         return new Observable_1.Observable(function (subscriber) {
16119             var sub = new Subscription_1.Subscription();
16120             sub.add(scheduler.schedule(function () {
16121                 var observable = input[observable_1.observable]();
16122                 sub.add(observable.subscribe({
16123                     next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); },
16124                     error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); },
16125                     complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); },
16126                 }));
16127             }));
16128             return sub;
16129         });
16130     }
16131 }
16132 exports.fromObservable = fromObservable;
16133
16134 },{"../Observable":48,"../Subscription":56,"../symbol/observable":207,"../util/subscribeToObservable":236}],73:[function(require,module,exports){
16135 "use strict";
16136 Object.defineProperty(exports, "__esModule", { value: true });
16137 var Observable_1 = require("../Observable");
16138 var Subscription_1 = require("../Subscription");
16139 var subscribeToPromise_1 = require("../util/subscribeToPromise");
16140 function fromPromise(input, scheduler) {
16141     if (!scheduler) {
16142         return new Observable_1.Observable(subscribeToPromise_1.subscribeToPromise(input));
16143     }
16144     else {
16145         return new Observable_1.Observable(function (subscriber) {
16146             var sub = new Subscription_1.Subscription();
16147             sub.add(scheduler.schedule(function () { return input.then(function (value) {
16148                 sub.add(scheduler.schedule(function () {
16149                     subscriber.next(value);
16150                     sub.add(scheduler.schedule(function () { return subscriber.complete(); }));
16151                 }));
16152             }, function (err) {
16153                 sub.add(scheduler.schedule(function () { return subscriber.error(err); }));
16154             }); }));
16155             return sub;
16156         });
16157     }
16158 }
16159 exports.fromPromise = fromPromise;
16160
16161 },{"../Observable":48,"../Subscription":56,"../util/subscribeToPromise":237}],74:[function(require,module,exports){
16162 "use strict";
16163 Object.defineProperty(exports, "__esModule", { value: true });
16164 var Observable_1 = require("../Observable");
16165 var identity_1 = require("../util/identity");
16166 var isScheduler_1 = require("../util/isScheduler");
16167 function generate(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) {
16168     var resultSelector;
16169     var initialState;
16170     if (arguments.length == 1) {
16171         var options = initialStateOrOptions;
16172         initialState = options.initialState;
16173         condition = options.condition;
16174         iterate = options.iterate;
16175         resultSelector = options.resultSelector || identity_1.identity;
16176         scheduler = options.scheduler;
16177     }
16178     else if (resultSelectorOrObservable === undefined || isScheduler_1.isScheduler(resultSelectorOrObservable)) {
16179         initialState = initialStateOrOptions;
16180         resultSelector = identity_1.identity;
16181         scheduler = resultSelectorOrObservable;
16182     }
16183     else {
16184         initialState = initialStateOrOptions;
16185         resultSelector = resultSelectorOrObservable;
16186     }
16187     return new Observable_1.Observable(function (subscriber) {
16188         var state = initialState;
16189         if (scheduler) {
16190             return scheduler.schedule(dispatch, 0, {
16191                 subscriber: subscriber,
16192                 iterate: iterate,
16193                 condition: condition,
16194                 resultSelector: resultSelector,
16195                 state: state
16196             });
16197         }
16198         do {
16199             if (condition) {
16200                 var conditionResult = void 0;
16201                 try {
16202                     conditionResult = condition(state);
16203                 }
16204                 catch (err) {
16205                     subscriber.error(err);
16206                     return undefined;
16207                 }
16208                 if (!conditionResult) {
16209                     subscriber.complete();
16210                     break;
16211                 }
16212             }
16213             var value = void 0;
16214             try {
16215                 value = resultSelector(state);
16216             }
16217             catch (err) {
16218                 subscriber.error(err);
16219                 return undefined;
16220             }
16221             subscriber.next(value);
16222             if (subscriber.closed) {
16223                 break;
16224             }
16225             try {
16226                 state = iterate(state);
16227             }
16228             catch (err) {
16229                 subscriber.error(err);
16230                 return undefined;
16231             }
16232         } while (true);
16233         return undefined;
16234     });
16235 }
16236 exports.generate = generate;
16237 function dispatch(state) {
16238     var subscriber = state.subscriber, condition = state.condition;
16239     if (subscriber.closed) {
16240         return undefined;
16241     }
16242     if (state.needIterate) {
16243         try {
16244             state.state = state.iterate(state.state);
16245         }
16246         catch (err) {
16247             subscriber.error(err);
16248             return undefined;
16249         }
16250     }
16251     else {
16252         state.needIterate = true;
16253     }
16254     if (condition) {
16255         var conditionResult = void 0;
16256         try {
16257             conditionResult = condition(state.state);
16258         }
16259         catch (err) {
16260             subscriber.error(err);
16261             return undefined;
16262         }
16263         if (!conditionResult) {
16264             subscriber.complete();
16265             return undefined;
16266         }
16267         if (subscriber.closed) {
16268             return undefined;
16269         }
16270     }
16271     var value;
16272     try {
16273         value = state.resultSelector(state.state);
16274     }
16275     catch (err) {
16276         subscriber.error(err);
16277         return undefined;
16278     }
16279     if (subscriber.closed) {
16280         return undefined;
16281     }
16282     subscriber.next(value);
16283     if (subscriber.closed) {
16284         return undefined;
16285     }
16286     return this.schedule(state);
16287 }
16288
16289 },{"../Observable":48,"../util/identity":218,"../util/isScheduler":229}],75:[function(require,module,exports){
16290 "use strict";
16291 Object.defineProperty(exports, "__esModule", { value: true });
16292 var defer_1 = require("./defer");
16293 var empty_1 = require("./empty");
16294 function iif(condition, trueResult, falseResult) {
16295     if (trueResult === void 0) { trueResult = empty_1.EMPTY; }
16296     if (falseResult === void 0) { falseResult = empty_1.EMPTY; }
16297     return defer_1.defer(function () { return condition() ? trueResult : falseResult; });
16298 }
16299 exports.iif = iif;
16300
16301 },{"./defer":64,"./empty":65}],76:[function(require,module,exports){
16302 "use strict";
16303 Object.defineProperty(exports, "__esModule", { value: true });
16304 var Observable_1 = require("../Observable");
16305 var async_1 = require("../scheduler/async");
16306 var isNumeric_1 = require("../util/isNumeric");
16307 function interval(period, scheduler) {
16308     if (period === void 0) { period = 0; }
16309     if (scheduler === void 0) { scheduler = async_1.async; }
16310     if (!isNumeric_1.isNumeric(period) || period < 0) {
16311         period = 0;
16312     }
16313     if (!scheduler || typeof scheduler.schedule !== 'function') {
16314         scheduler = async_1.async;
16315     }
16316     return new Observable_1.Observable(function (subscriber) {
16317         subscriber.add(scheduler.schedule(dispatch, period, { subscriber: subscriber, counter: 0, period: period }));
16318         return subscriber;
16319     });
16320 }
16321 exports.interval = interval;
16322 function dispatch(state) {
16323     var subscriber = state.subscriber, counter = state.counter, period = state.period;
16324     subscriber.next(counter);
16325     this.schedule({ subscriber: subscriber, counter: counter + 1, period: period }, period);
16326 }
16327
16328 },{"../Observable":48,"../scheduler/async":204,"../util/isNumeric":225}],77:[function(require,module,exports){
16329 "use strict";
16330 Object.defineProperty(exports, "__esModule", { value: true });
16331 var Observable_1 = require("../Observable");
16332 var isScheduler_1 = require("../util/isScheduler");
16333 var mergeAll_1 = require("../operators/mergeAll");
16334 var fromArray_1 = require("./fromArray");
16335 function merge() {
16336     var observables = [];
16337     for (var _i = 0; _i < arguments.length; _i++) {
16338         observables[_i] = arguments[_i];
16339     }
16340     var concurrent = Number.POSITIVE_INFINITY;
16341     var scheduler = null;
16342     var last = observables[observables.length - 1];
16343     if (isScheduler_1.isScheduler(last)) {
16344         scheduler = observables.pop();
16345         if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
16346             concurrent = observables.pop();
16347         }
16348     }
16349     else if (typeof last === 'number') {
16350         concurrent = observables.pop();
16351     }
16352     if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
16353         return observables[0];
16354     }
16355     return mergeAll_1.mergeAll(concurrent)(fromArray_1.fromArray(observables, scheduler));
16356 }
16357 exports.merge = merge;
16358
16359 },{"../Observable":48,"../operators/mergeAll":133,"../util/isScheduler":229,"./fromArray":68}],78:[function(require,module,exports){
16360 "use strict";
16361 Object.defineProperty(exports, "__esModule", { value: true });
16362 var Observable_1 = require("../Observable");
16363 var noop_1 = require("../util/noop");
16364 exports.NEVER = new Observable_1.Observable(noop_1.noop);
16365 function never() {
16366     return exports.NEVER;
16367 }
16368 exports.never = never;
16369
16370 },{"../Observable":48,"../util/noop":230}],79:[function(require,module,exports){
16371 "use strict";
16372 Object.defineProperty(exports, "__esModule", { value: true });
16373 var isScheduler_1 = require("../util/isScheduler");
16374 var fromArray_1 = require("./fromArray");
16375 var empty_1 = require("./empty");
16376 var scalar_1 = require("./scalar");
16377 function of() {
16378     var args = [];
16379     for (var _i = 0; _i < arguments.length; _i++) {
16380         args[_i] = arguments[_i];
16381     }
16382     var scheduler = args[args.length - 1];
16383     if (isScheduler_1.isScheduler(scheduler)) {
16384         args.pop();
16385     }
16386     else {
16387         scheduler = undefined;
16388     }
16389     switch (args.length) {
16390         case 0:
16391             return empty_1.empty(scheduler);
16392         case 1:
16393             return scheduler ? fromArray_1.fromArray(args, scheduler) : scalar_1.scalar(args[0]);
16394         default:
16395             return fromArray_1.fromArray(args, scheduler);
16396     }
16397 }
16398 exports.of = of;
16399
16400 },{"../util/isScheduler":229,"./empty":65,"./fromArray":68,"./scalar":84}],80:[function(require,module,exports){
16401 "use strict";
16402 Object.defineProperty(exports, "__esModule", { value: true });
16403 var Observable_1 = require("../Observable");
16404 var from_1 = require("./from");
16405 var isArray_1 = require("../util/isArray");
16406 var empty_1 = require("./empty");
16407 function onErrorResumeNext() {
16408     var sources = [];
16409     for (var _i = 0; _i < arguments.length; _i++) {
16410         sources[_i] = arguments[_i];
16411     }
16412     if (sources.length === 0) {
16413         return empty_1.EMPTY;
16414     }
16415     var first = sources[0], remainder = sources.slice(1);
16416     if (sources.length === 1 && isArray_1.isArray(first)) {
16417         return onErrorResumeNext.apply(void 0, first);
16418     }
16419     return new Observable_1.Observable(function (subscriber) {
16420         var subNext = function () { return subscriber.add(onErrorResumeNext.apply(void 0, remainder).subscribe(subscriber)); };
16421         return from_1.from(first).subscribe({
16422             next: function (value) { subscriber.next(value); },
16423             error: subNext,
16424             complete: subNext,
16425         });
16426     });
16427 }
16428 exports.onErrorResumeNext = onErrorResumeNext;
16429
16430 },{"../Observable":48,"../util/isArray":219,"./empty":65,"./from":67}],81:[function(require,module,exports){
16431 "use strict";
16432 Object.defineProperty(exports, "__esModule", { value: true });
16433 var Observable_1 = require("../Observable");
16434 var Subscription_1 = require("../Subscription");
16435 function pairs(obj, scheduler) {
16436     if (!scheduler) {
16437         return new Observable_1.Observable(function (subscriber) {
16438             var keys = Object.keys(obj);
16439             for (var i = 0; i < keys.length && !subscriber.closed; i++) {
16440                 var key = keys[i];
16441                 if (obj.hasOwnProperty(key)) {
16442                     subscriber.next([key, obj[key]]);
16443                 }
16444             }
16445             subscriber.complete();
16446         });
16447     }
16448     else {
16449         return new Observable_1.Observable(function (subscriber) {
16450             var keys = Object.keys(obj);
16451             var subscription = new Subscription_1.Subscription();
16452             subscription.add(scheduler.schedule(dispatch, 0, { keys: keys, index: 0, subscriber: subscriber, subscription: subscription, obj: obj }));
16453             return subscription;
16454         });
16455     }
16456 }
16457 exports.pairs = pairs;
16458 function dispatch(state) {
16459     var keys = state.keys, index = state.index, subscriber = state.subscriber, subscription = state.subscription, obj = state.obj;
16460     if (!subscriber.closed) {
16461         if (index < keys.length) {
16462             var key = keys[index];
16463             subscriber.next([key, obj[key]]);
16464             subscription.add(this.schedule({ keys: keys, index: index + 1, subscriber: subscriber, subscription: subscription, obj: obj }));
16465         }
16466         else {
16467             subscriber.complete();
16468         }
16469     }
16470 }
16471 exports.dispatch = dispatch;
16472
16473 },{"../Observable":48,"../Subscription":56}],82:[function(require,module,exports){
16474 "use strict";
16475 var __extends = (this && this.__extends) || (function () {
16476     var extendStatics = function (d, b) {
16477         extendStatics = Object.setPrototypeOf ||
16478             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16479             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16480         return extendStatics(d, b);
16481     }
16482     return function (d, b) {
16483         extendStatics(d, b);
16484         function __() { this.constructor = d; }
16485         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16486     };
16487 })();
16488 Object.defineProperty(exports, "__esModule", { value: true });
16489 var isArray_1 = require("../util/isArray");
16490 var fromArray_1 = require("./fromArray");
16491 var OuterSubscriber_1 = require("../OuterSubscriber");
16492 var subscribeToResult_1 = require("../util/subscribeToResult");
16493 function race() {
16494     var observables = [];
16495     for (var _i = 0; _i < arguments.length; _i++) {
16496         observables[_i] = arguments[_i];
16497     }
16498     if (observables.length === 1) {
16499         if (isArray_1.isArray(observables[0])) {
16500             observables = observables[0];
16501         }
16502         else {
16503             return observables[0];
16504         }
16505     }
16506     return fromArray_1.fromArray(observables, undefined).lift(new RaceOperator());
16507 }
16508 exports.race = race;
16509 var RaceOperator = (function () {
16510     function RaceOperator() {
16511     }
16512     RaceOperator.prototype.call = function (subscriber, source) {
16513         return source.subscribe(new RaceSubscriber(subscriber));
16514     };
16515     return RaceOperator;
16516 }());
16517 exports.RaceOperator = RaceOperator;
16518 var RaceSubscriber = (function (_super) {
16519     __extends(RaceSubscriber, _super);
16520     function RaceSubscriber(destination) {
16521         var _this = _super.call(this, destination) || this;
16522         _this.hasFirst = false;
16523         _this.observables = [];
16524         _this.subscriptions = [];
16525         return _this;
16526     }
16527     RaceSubscriber.prototype._next = function (observable) {
16528         this.observables.push(observable);
16529     };
16530     RaceSubscriber.prototype._complete = function () {
16531         var observables = this.observables;
16532         var len = observables.length;
16533         if (len === 0) {
16534             this.destination.complete();
16535         }
16536         else {
16537             for (var i = 0; i < len && !this.hasFirst; i++) {
16538                 var observable = observables[i];
16539                 var subscription = subscribeToResult_1.subscribeToResult(this, observable, observable, i);
16540                 if (this.subscriptions) {
16541                     this.subscriptions.push(subscription);
16542                 }
16543                 this.add(subscription);
16544             }
16545             this.observables = null;
16546         }
16547     };
16548     RaceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
16549         if (!this.hasFirst) {
16550             this.hasFirst = true;
16551             for (var i = 0; i < this.subscriptions.length; i++) {
16552                 if (i !== outerIndex) {
16553                     var subscription = this.subscriptions[i];
16554                     subscription.unsubscribe();
16555                     this.remove(subscription);
16556                 }
16557             }
16558             this.subscriptions = null;
16559         }
16560         this.destination.next(innerValue);
16561     };
16562     return RaceSubscriber;
16563 }(OuterSubscriber_1.OuterSubscriber));
16564 exports.RaceSubscriber = RaceSubscriber;
16565
16566 },{"../OuterSubscriber":50,"../util/isArray":219,"../util/subscribeToResult":238,"./fromArray":68}],83:[function(require,module,exports){
16567 "use strict";
16568 Object.defineProperty(exports, "__esModule", { value: true });
16569 var Observable_1 = require("../Observable");
16570 function range(start, count, scheduler) {
16571     if (start === void 0) { start = 0; }
16572     if (count === void 0) { count = 0; }
16573     return new Observable_1.Observable(function (subscriber) {
16574         var index = 0;
16575         var current = start;
16576         if (scheduler) {
16577             return scheduler.schedule(dispatch, 0, {
16578                 index: index, count: count, start: start, subscriber: subscriber
16579             });
16580         }
16581         else {
16582             do {
16583                 if (index++ >= count) {
16584                     subscriber.complete();
16585                     break;
16586                 }
16587                 subscriber.next(current++);
16588                 if (subscriber.closed) {
16589                     break;
16590                 }
16591             } while (true);
16592         }
16593         return undefined;
16594     });
16595 }
16596 exports.range = range;
16597 function dispatch(state) {
16598     var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber;
16599     if (index >= count) {
16600         subscriber.complete();
16601         return;
16602     }
16603     subscriber.next(start);
16604     if (subscriber.closed) {
16605         return;
16606     }
16607     state.index = index + 1;
16608     state.start = start + 1;
16609     this.schedule(state);
16610 }
16611 exports.dispatch = dispatch;
16612
16613 },{"../Observable":48}],84:[function(require,module,exports){
16614 "use strict";
16615 Object.defineProperty(exports, "__esModule", { value: true });
16616 var Observable_1 = require("../Observable");
16617 function scalar(value) {
16618     var result = new Observable_1.Observable(function (subscriber) {
16619         subscriber.next(value);
16620         subscriber.complete();
16621     });
16622     result._isScalar = true;
16623     result.value = value;
16624     return result;
16625 }
16626 exports.scalar = scalar;
16627
16628 },{"../Observable":48}],85:[function(require,module,exports){
16629 "use strict";
16630 Object.defineProperty(exports, "__esModule", { value: true });
16631 var Observable_1 = require("../Observable");
16632 function throwError(error, scheduler) {
16633     if (!scheduler) {
16634         return new Observable_1.Observable(function (subscriber) { return subscriber.error(error); });
16635     }
16636     else {
16637         return new Observable_1.Observable(function (subscriber) { return scheduler.schedule(dispatch, 0, { error: error, subscriber: subscriber }); });
16638     }
16639 }
16640 exports.throwError = throwError;
16641 function dispatch(_a) {
16642     var error = _a.error, subscriber = _a.subscriber;
16643     subscriber.error(error);
16644 }
16645
16646 },{"../Observable":48}],86:[function(require,module,exports){
16647 "use strict";
16648 Object.defineProperty(exports, "__esModule", { value: true });
16649 var Observable_1 = require("../Observable");
16650 var async_1 = require("../scheduler/async");
16651 var isNumeric_1 = require("../util/isNumeric");
16652 var isScheduler_1 = require("../util/isScheduler");
16653 function timer(dueTime, periodOrScheduler, scheduler) {
16654     if (dueTime === void 0) { dueTime = 0; }
16655     var period = -1;
16656     if (isNumeric_1.isNumeric(periodOrScheduler)) {
16657         period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);
16658     }
16659     else if (isScheduler_1.isScheduler(periodOrScheduler)) {
16660         scheduler = periodOrScheduler;
16661     }
16662     if (!isScheduler_1.isScheduler(scheduler)) {
16663         scheduler = async_1.async;
16664     }
16665     return new Observable_1.Observable(function (subscriber) {
16666         var due = isNumeric_1.isNumeric(dueTime)
16667             ? dueTime
16668             : (+dueTime - scheduler.now());
16669         return scheduler.schedule(dispatch, due, {
16670             index: 0, period: period, subscriber: subscriber
16671         });
16672     });
16673 }
16674 exports.timer = timer;
16675 function dispatch(state) {
16676     var index = state.index, period = state.period, subscriber = state.subscriber;
16677     subscriber.next(index);
16678     if (subscriber.closed) {
16679         return;
16680     }
16681     else if (period === -1) {
16682         return subscriber.complete();
16683     }
16684     state.index = index + 1;
16685     this.schedule(state, period);
16686 }
16687
16688 },{"../Observable":48,"../scheduler/async":204,"../util/isNumeric":225,"../util/isScheduler":229}],87:[function(require,module,exports){
16689 "use strict";
16690 Object.defineProperty(exports, "__esModule", { value: true });
16691 var Observable_1 = require("../Observable");
16692 var from_1 = require("./from");
16693 var empty_1 = require("./empty");
16694 function using(resourceFactory, observableFactory) {
16695     return new Observable_1.Observable(function (subscriber) {
16696         var resource;
16697         try {
16698             resource = resourceFactory();
16699         }
16700         catch (err) {
16701             subscriber.error(err);
16702             return undefined;
16703         }
16704         var result;
16705         try {
16706             result = observableFactory(resource);
16707         }
16708         catch (err) {
16709             subscriber.error(err);
16710             return undefined;
16711         }
16712         var source = result ? from_1.from(result) : empty_1.EMPTY;
16713         var subscription = source.subscribe(subscriber);
16714         return function () {
16715             subscription.unsubscribe();
16716             if (resource) {
16717                 resource.unsubscribe();
16718             }
16719         };
16720     });
16721 }
16722 exports.using = using;
16723
16724 },{"../Observable":48,"./empty":65,"./from":67}],88:[function(require,module,exports){
16725 "use strict";
16726 var __extends = (this && this.__extends) || (function () {
16727     var extendStatics = function (d, b) {
16728         extendStatics = Object.setPrototypeOf ||
16729             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16730             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16731         return extendStatics(d, b);
16732     }
16733     return function (d, b) {
16734         extendStatics(d, b);
16735         function __() { this.constructor = d; }
16736         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16737     };
16738 })();
16739 Object.defineProperty(exports, "__esModule", { value: true });
16740 var fromArray_1 = require("./fromArray");
16741 var isArray_1 = require("../util/isArray");
16742 var Subscriber_1 = require("../Subscriber");
16743 var OuterSubscriber_1 = require("../OuterSubscriber");
16744 var subscribeToResult_1 = require("../util/subscribeToResult");
16745 var iterator_1 = require("../../internal/symbol/iterator");
16746 function zip() {
16747     var observables = [];
16748     for (var _i = 0; _i < arguments.length; _i++) {
16749         observables[_i] = arguments[_i];
16750     }
16751     var resultSelector = observables[observables.length - 1];
16752     if (typeof resultSelector === 'function') {
16753         observables.pop();
16754     }
16755     return fromArray_1.fromArray(observables, undefined).lift(new ZipOperator(resultSelector));
16756 }
16757 exports.zip = zip;
16758 var ZipOperator = (function () {
16759     function ZipOperator(resultSelector) {
16760         this.resultSelector = resultSelector;
16761     }
16762     ZipOperator.prototype.call = function (subscriber, source) {
16763         return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));
16764     };
16765     return ZipOperator;
16766 }());
16767 exports.ZipOperator = ZipOperator;
16768 var ZipSubscriber = (function (_super) {
16769     __extends(ZipSubscriber, _super);
16770     function ZipSubscriber(destination, resultSelector, values) {
16771         if (values === void 0) { values = Object.create(null); }
16772         var _this = _super.call(this, destination) || this;
16773         _this.iterators = [];
16774         _this.active = 0;
16775         _this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : null;
16776         _this.values = values;
16777         return _this;
16778     }
16779     ZipSubscriber.prototype._next = function (value) {
16780         var iterators = this.iterators;
16781         if (isArray_1.isArray(value)) {
16782             iterators.push(new StaticArrayIterator(value));
16783         }
16784         else if (typeof value[iterator_1.iterator] === 'function') {
16785             iterators.push(new StaticIterator(value[iterator_1.iterator]()));
16786         }
16787         else {
16788             iterators.push(new ZipBufferIterator(this.destination, this, value));
16789         }
16790     };
16791     ZipSubscriber.prototype._complete = function () {
16792         var iterators = this.iterators;
16793         var len = iterators.length;
16794         this.unsubscribe();
16795         if (len === 0) {
16796             this.destination.complete();
16797             return;
16798         }
16799         this.active = len;
16800         for (var i = 0; i < len; i++) {
16801             var iterator = iterators[i];
16802             if (iterator.stillUnsubscribed) {
16803                 var destination = this.destination;
16804                 destination.add(iterator.subscribe(iterator, i));
16805             }
16806             else {
16807                 this.active--;
16808             }
16809         }
16810     };
16811     ZipSubscriber.prototype.notifyInactive = function () {
16812         this.active--;
16813         if (this.active === 0) {
16814             this.destination.complete();
16815         }
16816     };
16817     ZipSubscriber.prototype.checkIterators = function () {
16818         var iterators = this.iterators;
16819         var len = iterators.length;
16820         var destination = this.destination;
16821         for (var i = 0; i < len; i++) {
16822             var iterator = iterators[i];
16823             if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
16824                 return;
16825             }
16826         }
16827         var shouldComplete = false;
16828         var args = [];
16829         for (var i = 0; i < len; i++) {
16830             var iterator = iterators[i];
16831             var result = iterator.next();
16832             if (iterator.hasCompleted()) {
16833                 shouldComplete = true;
16834             }
16835             if (result.done) {
16836                 destination.complete();
16837                 return;
16838             }
16839             args.push(result.value);
16840         }
16841         if (this.resultSelector) {
16842             this._tryresultSelector(args);
16843         }
16844         else {
16845             destination.next(args);
16846         }
16847         if (shouldComplete) {
16848             destination.complete();
16849         }
16850     };
16851     ZipSubscriber.prototype._tryresultSelector = function (args) {
16852         var result;
16853         try {
16854             result = this.resultSelector.apply(this, args);
16855         }
16856         catch (err) {
16857             this.destination.error(err);
16858             return;
16859         }
16860         this.destination.next(result);
16861     };
16862     return ZipSubscriber;
16863 }(Subscriber_1.Subscriber));
16864 exports.ZipSubscriber = ZipSubscriber;
16865 var StaticIterator = (function () {
16866     function StaticIterator(iterator) {
16867         this.iterator = iterator;
16868         this.nextResult = iterator.next();
16869     }
16870     StaticIterator.prototype.hasValue = function () {
16871         return true;
16872     };
16873     StaticIterator.prototype.next = function () {
16874         var result = this.nextResult;
16875         this.nextResult = this.iterator.next();
16876         return result;
16877     };
16878     StaticIterator.prototype.hasCompleted = function () {
16879         var nextResult = this.nextResult;
16880         return nextResult && nextResult.done;
16881     };
16882     return StaticIterator;
16883 }());
16884 var StaticArrayIterator = (function () {
16885     function StaticArrayIterator(array) {
16886         this.array = array;
16887         this.index = 0;
16888         this.length = 0;
16889         this.length = array.length;
16890     }
16891     StaticArrayIterator.prototype[iterator_1.iterator] = function () {
16892         return this;
16893     };
16894     StaticArrayIterator.prototype.next = function (value) {
16895         var i = this.index++;
16896         var array = this.array;
16897         return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
16898     };
16899     StaticArrayIterator.prototype.hasValue = function () {
16900         return this.array.length > this.index;
16901     };
16902     StaticArrayIterator.prototype.hasCompleted = function () {
16903         return this.array.length === this.index;
16904     };
16905     return StaticArrayIterator;
16906 }());
16907 var ZipBufferIterator = (function (_super) {
16908     __extends(ZipBufferIterator, _super);
16909     function ZipBufferIterator(destination, parent, observable) {
16910         var _this = _super.call(this, destination) || this;
16911         _this.parent = parent;
16912         _this.observable = observable;
16913         _this.stillUnsubscribed = true;
16914         _this.buffer = [];
16915         _this.isComplete = false;
16916         return _this;
16917     }
16918     ZipBufferIterator.prototype[iterator_1.iterator] = function () {
16919         return this;
16920     };
16921     ZipBufferIterator.prototype.next = function () {
16922         var buffer = this.buffer;
16923         if (buffer.length === 0 && this.isComplete) {
16924             return { value: null, done: true };
16925         }
16926         else {
16927             return { value: buffer.shift(), done: false };
16928         }
16929     };
16930     ZipBufferIterator.prototype.hasValue = function () {
16931         return this.buffer.length > 0;
16932     };
16933     ZipBufferIterator.prototype.hasCompleted = function () {
16934         return this.buffer.length === 0 && this.isComplete;
16935     };
16936     ZipBufferIterator.prototype.notifyComplete = function () {
16937         if (this.buffer.length > 0) {
16938             this.isComplete = true;
16939             this.parent.notifyInactive();
16940         }
16941         else {
16942             this.destination.complete();
16943         }
16944     };
16945     ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
16946         this.buffer.push(innerValue);
16947         this.parent.checkIterators();
16948     };
16949     ZipBufferIterator.prototype.subscribe = function (value, index) {
16950         return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
16951     };
16952     return ZipBufferIterator;
16953 }(OuterSubscriber_1.OuterSubscriber));
16954
16955 },{"../../internal/symbol/iterator":206,"../OuterSubscriber":50,"../Subscriber":55,"../util/isArray":219,"../util/subscribeToResult":238,"./fromArray":68}],89:[function(require,module,exports){
16956 "use strict";
16957 var __extends = (this && this.__extends) || (function () {
16958     var extendStatics = function (d, b) {
16959         extendStatics = Object.setPrototypeOf ||
16960             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
16961             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
16962         return extendStatics(d, b);
16963     }
16964     return function (d, b) {
16965         extendStatics(d, b);
16966         function __() { this.constructor = d; }
16967         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16968     };
16969 })();
16970 Object.defineProperty(exports, "__esModule", { value: true });
16971 var tryCatch_1 = require("../util/tryCatch");
16972 var errorObject_1 = require("../util/errorObject");
16973 var OuterSubscriber_1 = require("../OuterSubscriber");
16974 var subscribeToResult_1 = require("../util/subscribeToResult");
16975 function audit(durationSelector) {
16976     return function auditOperatorFunction(source) {
16977         return source.lift(new AuditOperator(durationSelector));
16978     };
16979 }
16980 exports.audit = audit;
16981 var AuditOperator = (function () {
16982     function AuditOperator(durationSelector) {
16983         this.durationSelector = durationSelector;
16984     }
16985     AuditOperator.prototype.call = function (subscriber, source) {
16986         return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));
16987     };
16988     return AuditOperator;
16989 }());
16990 var AuditSubscriber = (function (_super) {
16991     __extends(AuditSubscriber, _super);
16992     function AuditSubscriber(destination, durationSelector) {
16993         var _this = _super.call(this, destination) || this;
16994         _this.durationSelector = durationSelector;
16995         _this.hasValue = false;
16996         return _this;
16997     }
16998     AuditSubscriber.prototype._next = function (value) {
16999         this.value = value;
17000         this.hasValue = true;
17001         if (!this.throttled) {
17002             var duration = tryCatch_1.tryCatch(this.durationSelector)(value);
17003             if (duration === errorObject_1.errorObject) {
17004                 this.destination.error(errorObject_1.errorObject.e);
17005             }
17006             else {
17007                 var innerSubscription = subscribeToResult_1.subscribeToResult(this, duration);
17008                 if (!innerSubscription || innerSubscription.closed) {
17009                     this.clearThrottle();
17010                 }
17011                 else {
17012                     this.add(this.throttled = innerSubscription);
17013                 }
17014             }
17015         }
17016     };
17017     AuditSubscriber.prototype.clearThrottle = function () {
17018         var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled;
17019         if (throttled) {
17020             this.remove(throttled);
17021             this.throttled = null;
17022             throttled.unsubscribe();
17023         }
17024         if (hasValue) {
17025             this.value = null;
17026             this.hasValue = false;
17027             this.destination.next(value);
17028         }
17029     };
17030     AuditSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
17031         this.clearThrottle();
17032     };
17033     AuditSubscriber.prototype.notifyComplete = function () {
17034         this.clearThrottle();
17035     };
17036     return AuditSubscriber;
17037 }(OuterSubscriber_1.OuterSubscriber));
17038
17039 },{"../OuterSubscriber":50,"../util/errorObject":216,"../util/subscribeToResult":238,"../util/tryCatch":240}],90:[function(require,module,exports){
17040 "use strict";
17041 Object.defineProperty(exports, "__esModule", { value: true });
17042 var async_1 = require("../scheduler/async");
17043 var audit_1 = require("./audit");
17044 var timer_1 = require("../observable/timer");
17045 function auditTime(duration, scheduler) {
17046     if (scheduler === void 0) { scheduler = async_1.async; }
17047     return audit_1.audit(function () { return timer_1.timer(duration, scheduler); });
17048 }
17049 exports.auditTime = auditTime;
17050
17051 },{"../observable/timer":86,"../scheduler/async":204,"./audit":89}],91:[function(require,module,exports){
17052 "use strict";
17053 var __extends = (this && this.__extends) || (function () {
17054     var extendStatics = function (d, b) {
17055         extendStatics = Object.setPrototypeOf ||
17056             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17057             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17058         return extendStatics(d, b);
17059     }
17060     return function (d, b) {
17061         extendStatics(d, b);
17062         function __() { this.constructor = d; }
17063         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17064     };
17065 })();
17066 Object.defineProperty(exports, "__esModule", { value: true });
17067 var OuterSubscriber_1 = require("../OuterSubscriber");
17068 var subscribeToResult_1 = require("../util/subscribeToResult");
17069 function buffer(closingNotifier) {
17070     return function bufferOperatorFunction(source) {
17071         return source.lift(new BufferOperator(closingNotifier));
17072     };
17073 }
17074 exports.buffer = buffer;
17075 var BufferOperator = (function () {
17076     function BufferOperator(closingNotifier) {
17077         this.closingNotifier = closingNotifier;
17078     }
17079     BufferOperator.prototype.call = function (subscriber, source) {
17080         return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
17081     };
17082     return BufferOperator;
17083 }());
17084 var BufferSubscriber = (function (_super) {
17085     __extends(BufferSubscriber, _super);
17086     function BufferSubscriber(destination, closingNotifier) {
17087         var _this = _super.call(this, destination) || this;
17088         _this.buffer = [];
17089         _this.add(subscribeToResult_1.subscribeToResult(_this, closingNotifier));
17090         return _this;
17091     }
17092     BufferSubscriber.prototype._next = function (value) {
17093         this.buffer.push(value);
17094     };
17095     BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
17096         var buffer = this.buffer;
17097         this.buffer = [];
17098         this.destination.next(buffer);
17099     };
17100     return BufferSubscriber;
17101 }(OuterSubscriber_1.OuterSubscriber));
17102
17103 },{"../OuterSubscriber":50,"../util/subscribeToResult":238}],92:[function(require,module,exports){
17104 "use strict";
17105 var __extends = (this && this.__extends) || (function () {
17106     var extendStatics = function (d, b) {
17107         extendStatics = Object.setPrototypeOf ||
17108             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17109             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17110         return extendStatics(d, b);
17111     }
17112     return function (d, b) {
17113         extendStatics(d, b);
17114         function __() { this.constructor = d; }
17115         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17116     };
17117 })();
17118 Object.defineProperty(exports, "__esModule", { value: true });
17119 var Subscriber_1 = require("../Subscriber");
17120 function bufferCount(bufferSize, startBufferEvery) {
17121     if (startBufferEvery === void 0) { startBufferEvery = null; }
17122     return function bufferCountOperatorFunction(source) {
17123         return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));
17124     };
17125 }
17126 exports.bufferCount = bufferCount;
17127 var BufferCountOperator = (function () {
17128     function BufferCountOperator(bufferSize, startBufferEvery) {
17129         this.bufferSize = bufferSize;
17130         this.startBufferEvery = startBufferEvery;
17131         if (!startBufferEvery || bufferSize === startBufferEvery) {
17132             this.subscriberClass = BufferCountSubscriber;
17133         }
17134         else {
17135             this.subscriberClass = BufferSkipCountSubscriber;
17136         }
17137     }
17138     BufferCountOperator.prototype.call = function (subscriber, source) {
17139         return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
17140     };
17141     return BufferCountOperator;
17142 }());
17143 var BufferCountSubscriber = (function (_super) {
17144     __extends(BufferCountSubscriber, _super);
17145     function BufferCountSubscriber(destination, bufferSize) {
17146         var _this = _super.call(this, destination) || this;
17147         _this.bufferSize = bufferSize;
17148         _this.buffer = [];
17149         return _this;
17150     }
17151     BufferCountSubscriber.prototype._next = function (value) {
17152         var buffer = this.buffer;
17153         buffer.push(value);
17154         if (buffer.length == this.bufferSize) {
17155             this.destination.next(buffer);
17156             this.buffer = [];
17157         }
17158     };
17159     BufferCountSubscriber.prototype._complete = function () {
17160         var buffer = this.buffer;
17161         if (buffer.length > 0) {
17162             this.destination.next(buffer);
17163         }
17164         _super.prototype._complete.call(this);
17165     };
17166     return BufferCountSubscriber;
17167 }(Subscriber_1.Subscriber));
17168 var BufferSkipCountSubscriber = (function (_super) {
17169     __extends(BufferSkipCountSubscriber, _super);
17170     function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
17171         var _this = _super.call(this, destination) || this;
17172         _this.bufferSize = bufferSize;
17173         _this.startBufferEvery = startBufferEvery;
17174         _this.buffers = [];
17175         _this.count = 0;
17176         return _this;
17177     }
17178     BufferSkipCountSubscriber.prototype._next = function (value) {
17179         var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
17180         this.count++;
17181         if (count % startBufferEvery === 0) {
17182             buffers.push([]);
17183         }
17184         for (var i = buffers.length; i--;) {
17185             var buffer = buffers[i];
17186             buffer.push(value);
17187             if (buffer.length === bufferSize) {
17188                 buffers.splice(i, 1);
17189                 this.destination.next(buffer);
17190             }
17191         }
17192     };
17193     BufferSkipCountSubscriber.prototype._complete = function () {
17194         var _a = this, buffers = _a.buffers, destination = _a.destination;
17195         while (buffers.length > 0) {
17196             var buffer = buffers.shift();
17197             if (buffer.length > 0) {
17198                 destination.next(buffer);
17199             }
17200         }
17201         _super.prototype._complete.call(this);
17202     };
17203     return BufferSkipCountSubscriber;
17204 }(Subscriber_1.Subscriber));
17205
17206 },{"../Subscriber":55}],93:[function(require,module,exports){
17207 "use strict";
17208 var __extends = (this && this.__extends) || (function () {
17209     var extendStatics = function (d, b) {
17210         extendStatics = Object.setPrototypeOf ||
17211             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17212             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17213         return extendStatics(d, b);
17214     }
17215     return function (d, b) {
17216         extendStatics(d, b);
17217         function __() { this.constructor = d; }
17218         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17219     };
17220 })();
17221 Object.defineProperty(exports, "__esModule", { value: true });
17222 var async_1 = require("../scheduler/async");
17223 var Subscriber_1 = require("../Subscriber");
17224 var isScheduler_1 = require("../util/isScheduler");
17225 function bufferTime(bufferTimeSpan) {
17226     var length = arguments.length;
17227     var scheduler = async_1.async;
17228     if (isScheduler_1.isScheduler(arguments[arguments.length - 1])) {
17229         scheduler = arguments[arguments.length - 1];
17230         length--;
17231     }
17232     var bufferCreationInterval = null;
17233     if (length >= 2) {
17234         bufferCreationInterval = arguments[1];
17235     }
17236     var maxBufferSize = Number.POSITIVE_INFINITY;
17237     if (length >= 3) {
17238         maxBufferSize = arguments[2];
17239     }
17240     return function bufferTimeOperatorFunction(source) {
17241         return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));
17242     };
17243 }
17244 exports.bufferTime = bufferTime;
17245 var BufferTimeOperator = (function () {
17246     function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
17247         this.bufferTimeSpan = bufferTimeSpan;
17248         this.bufferCreationInterval = bufferCreationInterval;
17249         this.maxBufferSize = maxBufferSize;
17250         this.scheduler = scheduler;
17251     }
17252     BufferTimeOperator.prototype.call = function (subscriber, source) {
17253         return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler));
17254     };
17255     return BufferTimeOperator;
17256 }());
17257 var Context = (function () {
17258     function Context() {
17259         this.buffer = [];
17260     }
17261     return Context;
17262 }());
17263 var BufferTimeSubscriber = (function (_super) {
17264     __extends(BufferTimeSubscriber, _super);
17265     function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
17266         var _this = _super.call(this, destination) || this;
17267         _this.bufferTimeSpan = bufferTimeSpan;
17268         _this.bufferCreationInterval = bufferCreationInterval;
17269         _this.maxBufferSize = maxBufferSize;
17270         _this.scheduler = scheduler;
17271         _this.contexts = [];
17272         var context = _this.openContext();
17273         _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;
17274         if (_this.timespanOnly) {
17275             var timeSpanOnlyState = { subscriber: _this, context: context, bufferTimeSpan: bufferTimeSpan };
17276             _this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
17277         }
17278         else {
17279             var closeState = { subscriber: _this, context: context };
17280             var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: _this, scheduler: scheduler };
17281             _this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState));
17282             _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState));
17283         }
17284         return _this;
17285     }
17286     BufferTimeSubscriber.prototype._next = function (value) {
17287         var contexts = this.contexts;
17288         var len = contexts.length;
17289         var filledBufferContext;
17290         for (var i = 0; i < len; i++) {
17291             var context_1 = contexts[i];
17292             var buffer = context_1.buffer;
17293             buffer.push(value);
17294             if (buffer.length == this.maxBufferSize) {
17295                 filledBufferContext = context_1;
17296             }
17297         }
17298         if (filledBufferContext) {
17299             this.onBufferFull(filledBufferContext);
17300         }
17301     };
17302     BufferTimeSubscriber.prototype._error = function (err) {
17303         this.contexts.length = 0;
17304         _super.prototype._error.call(this, err);
17305     };
17306     BufferTimeSubscriber.prototype._complete = function () {
17307         var _a = this, contexts = _a.contexts, destination = _a.destination;
17308         while (contexts.length > 0) {
17309             var context_2 = contexts.shift();
17310             destination.next(context_2.buffer);
17311         }
17312         _super.prototype._complete.call(this);
17313     };
17314     BufferTimeSubscriber.prototype._unsubscribe = function () {
17315         this.contexts = null;
17316     };
17317     BufferTimeSubscriber.prototype.onBufferFull = function (context) {
17318         this.closeContext(context);
17319         var closeAction = context.closeAction;
17320         closeAction.unsubscribe();
17321         this.remove(closeAction);
17322         if (!this.closed && this.timespanOnly) {
17323             context = this.openContext();
17324             var bufferTimeSpan = this.bufferTimeSpan;
17325             var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan };
17326             this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
17327         }
17328     };
17329     BufferTimeSubscriber.prototype.openContext = function () {
17330         var context = new Context();
17331         this.contexts.push(context);
17332         return context;
17333     };
17334     BufferTimeSubscriber.prototype.closeContext = function (context) {
17335         this.destination.next(context.buffer);
17336         var contexts = this.contexts;
17337         var spliceIndex = contexts ? contexts.indexOf(context) : -1;
17338         if (spliceIndex >= 0) {
17339             contexts.splice(contexts.indexOf(context), 1);
17340         }
17341     };
17342     return BufferTimeSubscriber;
17343 }(Subscriber_1.Subscriber));
17344 function dispatchBufferTimeSpanOnly(state) {
17345     var subscriber = state.subscriber;
17346     var prevContext = state.context;
17347     if (prevContext) {
17348         subscriber.closeContext(prevContext);
17349     }
17350     if (!subscriber.closed) {
17351         state.context = subscriber.openContext();
17352         state.context.closeAction = this.schedule(state, state.bufferTimeSpan);
17353     }
17354 }
17355 function dispatchBufferCreation(state) {
17356     var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler;
17357     var context = subscriber.openContext();
17358     var action = this;
17359     if (!subscriber.closed) {
17360         subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context }));
17361         action.schedule(state, bufferCreationInterval);
17362     }
17363 }
17364 function dispatchBufferClose(arg) {
17365     var subscriber = arg.subscriber, context = arg.context;
17366     subscriber.closeContext(context);
17367 }
17368
17369 },{"../Subscriber":55,"../scheduler/async":204,"../util/isScheduler":229}],94:[function(require,module,exports){
17370 "use strict";
17371 var __extends = (this && this.__extends) || (function () {
17372     var extendStatics = function (d, b) {
17373         extendStatics = Object.setPrototypeOf ||
17374             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17375             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17376         return extendStatics(d, b);
17377     }
17378     return function (d, b) {
17379         extendStatics(d, b);
17380         function __() { this.constructor = d; }
17381         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17382     };
17383 })();
17384 Object.defineProperty(exports, "__esModule", { value: true });
17385 var Subscription_1 = require("../Subscription");
17386 var subscribeToResult_1 = require("../util/subscribeToResult");
17387 var OuterSubscriber_1 = require("../OuterSubscriber");
17388 function bufferToggle(openings, closingSelector) {
17389     return function bufferToggleOperatorFunction(source) {
17390         return source.lift(new BufferToggleOperator(openings, closingSelector));
17391     };
17392 }
17393 exports.bufferToggle = bufferToggle;
17394 var BufferToggleOperator = (function () {
17395     function BufferToggleOperator(openings, closingSelector) {
17396         this.openings = openings;
17397         this.closingSelector = closingSelector;
17398     }
17399     BufferToggleOperator.prototype.call = function (subscriber, source) {
17400         return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector));
17401     };
17402     return BufferToggleOperator;
17403 }());
17404 var BufferToggleSubscriber = (function (_super) {
17405     __extends(BufferToggleSubscriber, _super);
17406     function BufferToggleSubscriber(destination, openings, closingSelector) {
17407         var _this = _super.call(this, destination) || this;
17408         _this.openings = openings;
17409         _this.closingSelector = closingSelector;
17410         _this.contexts = [];
17411         _this.add(subscribeToResult_1.subscribeToResult(_this, openings));
17412         return _this;
17413     }
17414     BufferToggleSubscriber.prototype._next = function (value) {
17415         var contexts = this.contexts;
17416         var len = contexts.length;
17417         for (var i = 0; i < len; i++) {
17418             contexts[i].buffer.push(value);
17419         }
17420     };
17421     BufferToggleSubscriber.prototype._error = function (err) {
17422         var contexts = this.contexts;
17423         while (contexts.length > 0) {
17424             var context_1 = contexts.shift();
17425             context_1.subscription.unsubscribe();
17426             context_1.buffer = null;
17427             context_1.subscription = null;
17428         }
17429         this.contexts = null;
17430         _super.prototype._error.call(this, err);
17431     };
17432     BufferToggleSubscriber.prototype._complete = function () {
17433         var contexts = this.contexts;
17434         while (contexts.length > 0) {
17435             var context_2 = contexts.shift();
17436             this.destination.next(context_2.buffer);
17437             context_2.subscription.unsubscribe();
17438             context_2.buffer = null;
17439             context_2.subscription = null;
17440         }
17441         this.contexts = null;
17442         _super.prototype._complete.call(this);
17443     };
17444     BufferToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
17445         outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue);
17446     };
17447     BufferToggleSubscriber.prototype.notifyComplete = function (innerSub) {
17448         this.closeBuffer(innerSub.context);
17449     };
17450     BufferToggleSubscriber.prototype.openBuffer = function (value) {
17451         try {
17452             var closingSelector = this.closingSelector;
17453             var closingNotifier = closingSelector.call(this, value);
17454             if (closingNotifier) {
17455                 this.trySubscribe(closingNotifier);
17456             }
17457         }
17458         catch (err) {
17459             this._error(err);
17460         }
17461     };
17462     BufferToggleSubscriber.prototype.closeBuffer = function (context) {
17463         var contexts = this.contexts;
17464         if (contexts && context) {
17465             var buffer = context.buffer, subscription = context.subscription;
17466             this.destination.next(buffer);
17467             contexts.splice(contexts.indexOf(context), 1);
17468             this.remove(subscription);
17469             subscription.unsubscribe();
17470         }
17471     };
17472     BufferToggleSubscriber.prototype.trySubscribe = function (closingNotifier) {
17473         var contexts = this.contexts;
17474         var buffer = [];
17475         var subscription = new Subscription_1.Subscription();
17476         var context = { buffer: buffer, subscription: subscription };
17477         contexts.push(context);
17478         var innerSubscription = subscribeToResult_1.subscribeToResult(this, closingNotifier, context);
17479         if (!innerSubscription || innerSubscription.closed) {
17480             this.closeBuffer(context);
17481         }
17482         else {
17483             innerSubscription.context = context;
17484             this.add(innerSubscription);
17485             subscription.add(innerSubscription);
17486         }
17487     };
17488     return BufferToggleSubscriber;
17489 }(OuterSubscriber_1.OuterSubscriber));
17490
17491 },{"../OuterSubscriber":50,"../Subscription":56,"../util/subscribeToResult":238}],95:[function(require,module,exports){
17492 "use strict";
17493 var __extends = (this && this.__extends) || (function () {
17494     var extendStatics = function (d, b) {
17495         extendStatics = Object.setPrototypeOf ||
17496             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17497             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17498         return extendStatics(d, b);
17499     }
17500     return function (d, b) {
17501         extendStatics(d, b);
17502         function __() { this.constructor = d; }
17503         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17504     };
17505 })();
17506 Object.defineProperty(exports, "__esModule", { value: true });
17507 var Subscription_1 = require("../Subscription");
17508 var tryCatch_1 = require("../util/tryCatch");
17509 var errorObject_1 = require("../util/errorObject");
17510 var OuterSubscriber_1 = require("../OuterSubscriber");
17511 var subscribeToResult_1 = require("../util/subscribeToResult");
17512 function bufferWhen(closingSelector) {
17513     return function (source) {
17514         return source.lift(new BufferWhenOperator(closingSelector));
17515     };
17516 }
17517 exports.bufferWhen = bufferWhen;
17518 var BufferWhenOperator = (function () {
17519     function BufferWhenOperator(closingSelector) {
17520         this.closingSelector = closingSelector;
17521     }
17522     BufferWhenOperator.prototype.call = function (subscriber, source) {
17523         return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
17524     };
17525     return BufferWhenOperator;
17526 }());
17527 var BufferWhenSubscriber = (function (_super) {
17528     __extends(BufferWhenSubscriber, _super);
17529     function BufferWhenSubscriber(destination, closingSelector) {
17530         var _this = _super.call(this, destination) || this;
17531         _this.closingSelector = closingSelector;
17532         _this.subscribing = false;
17533         _this.openBuffer();
17534         return _this;
17535     }
17536     BufferWhenSubscriber.prototype._next = function (value) {
17537         this.buffer.push(value);
17538     };
17539     BufferWhenSubscriber.prototype._complete = function () {
17540         var buffer = this.buffer;
17541         if (buffer) {
17542             this.destination.next(buffer);
17543         }
17544         _super.prototype._complete.call(this);
17545     };
17546     BufferWhenSubscriber.prototype._unsubscribe = function () {
17547         this.buffer = null;
17548         this.subscribing = false;
17549     };
17550     BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
17551         this.openBuffer();
17552     };
17553     BufferWhenSubscriber.prototype.notifyComplete = function () {
17554         if (this.subscribing) {
17555             this.complete();
17556         }
17557         else {
17558             this.openBuffer();
17559         }
17560     };
17561     BufferWhenSubscriber.prototype.openBuffer = function () {
17562         var closingSubscription = this.closingSubscription;
17563         if (closingSubscription) {
17564             this.remove(closingSubscription);
17565             closingSubscription.unsubscribe();
17566         }
17567         var buffer = this.buffer;
17568         if (this.buffer) {
17569             this.destination.next(buffer);
17570         }
17571         this.buffer = [];
17572         var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
17573         if (closingNotifier === errorObject_1.errorObject) {
17574             this.error(errorObject_1.errorObject.e);
17575         }
17576         else {
17577             closingSubscription = new Subscription_1.Subscription();
17578             this.closingSubscription = closingSubscription;
17579             this.add(closingSubscription);
17580             this.subscribing = true;
17581             closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
17582             this.subscribing = false;
17583         }
17584     };
17585     return BufferWhenSubscriber;
17586 }(OuterSubscriber_1.OuterSubscriber));
17587
17588 },{"../OuterSubscriber":50,"../Subscription":56,"../util/errorObject":216,"../util/subscribeToResult":238,"../util/tryCatch":240}],96:[function(require,module,exports){
17589 "use strict";
17590 var __extends = (this && this.__extends) || (function () {
17591     var extendStatics = function (d, b) {
17592         extendStatics = Object.setPrototypeOf ||
17593             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17594             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17595         return extendStatics(d, b);
17596     }
17597     return function (d, b) {
17598         extendStatics(d, b);
17599         function __() { this.constructor = d; }
17600         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17601     };
17602 })();
17603 Object.defineProperty(exports, "__esModule", { value: true });
17604 var OuterSubscriber_1 = require("../OuterSubscriber");
17605 var InnerSubscriber_1 = require("../InnerSubscriber");
17606 var subscribeToResult_1 = require("../util/subscribeToResult");
17607 function catchError(selector) {
17608     return function catchErrorOperatorFunction(source) {
17609         var operator = new CatchOperator(selector);
17610         var caught = source.lift(operator);
17611         return (operator.caught = caught);
17612     };
17613 }
17614 exports.catchError = catchError;
17615 var CatchOperator = (function () {
17616     function CatchOperator(selector) {
17617         this.selector = selector;
17618     }
17619     CatchOperator.prototype.call = function (subscriber, source) {
17620         return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
17621     };
17622     return CatchOperator;
17623 }());
17624 var CatchSubscriber = (function (_super) {
17625     __extends(CatchSubscriber, _super);
17626     function CatchSubscriber(destination, selector, caught) {
17627         var _this = _super.call(this, destination) || this;
17628         _this.selector = selector;
17629         _this.caught = caught;
17630         return _this;
17631     }
17632     CatchSubscriber.prototype.error = function (err) {
17633         if (!this.isStopped) {
17634             var result = void 0;
17635             try {
17636                 result = this.selector(err, this.caught);
17637             }
17638             catch (err2) {
17639                 _super.prototype.error.call(this, err2);
17640                 return;
17641             }
17642             this._unsubscribeAndRecycle();
17643             var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
17644             this.add(innerSubscriber);
17645             subscribeToResult_1.subscribeToResult(this, result, undefined, undefined, innerSubscriber);
17646         }
17647     };
17648     return CatchSubscriber;
17649 }(OuterSubscriber_1.OuterSubscriber));
17650
17651 },{"../InnerSubscriber":46,"../OuterSubscriber":50,"../util/subscribeToResult":238}],97:[function(require,module,exports){
17652 "use strict";
17653 Object.defineProperty(exports, "__esModule", { value: true });
17654 var combineLatest_1 = require("../observable/combineLatest");
17655 function combineAll(project) {
17656     return function (source) { return source.lift(new combineLatest_1.CombineLatestOperator(project)); };
17657 }
17658 exports.combineAll = combineAll;
17659
17660 },{"../observable/combineLatest":62}],98:[function(require,module,exports){
17661 "use strict";
17662 Object.defineProperty(exports, "__esModule", { value: true });
17663 var isArray_1 = require("../util/isArray");
17664 var combineLatest_1 = require("../observable/combineLatest");
17665 var from_1 = require("../observable/from");
17666 var none = {};
17667 function combineLatest() {
17668     var observables = [];
17669     for (var _i = 0; _i < arguments.length; _i++) {
17670         observables[_i] = arguments[_i];
17671     }
17672     var project = null;
17673     if (typeof observables[observables.length - 1] === 'function') {
17674         project = observables.pop();
17675     }
17676     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
17677         observables = observables[0].slice();
17678     }
17679     return function (source) { return source.lift.call(from_1.from([source].concat(observables)), new combineLatest_1.CombineLatestOperator(project)); };
17680 }
17681 exports.combineLatest = combineLatest;
17682
17683 },{"../observable/combineLatest":62,"../observable/from":67,"../util/isArray":219}],99:[function(require,module,exports){
17684 "use strict";
17685 Object.defineProperty(exports, "__esModule", { value: true });
17686 var concat_1 = require("../observable/concat");
17687 function concat() {
17688     var observables = [];
17689     for (var _i = 0; _i < arguments.length; _i++) {
17690         observables[_i] = arguments[_i];
17691     }
17692     return function (source) { return source.lift.call(concat_1.concat.apply(void 0, [source].concat(observables))); };
17693 }
17694 exports.concat = concat;
17695
17696 },{"../observable/concat":63}],100:[function(require,module,exports){
17697 "use strict";
17698 Object.defineProperty(exports, "__esModule", { value: true });
17699 var mergeAll_1 = require("./mergeAll");
17700 function concatAll() {
17701     return mergeAll_1.mergeAll(1);
17702 }
17703 exports.concatAll = concatAll;
17704
17705 },{"./mergeAll":133}],101:[function(require,module,exports){
17706 "use strict";
17707 Object.defineProperty(exports, "__esModule", { value: true });
17708 var mergeMap_1 = require("./mergeMap");
17709 function concatMap(project, resultSelector) {
17710     return mergeMap_1.mergeMap(project, resultSelector, 1);
17711 }
17712 exports.concatMap = concatMap;
17713
17714 },{"./mergeMap":134}],102:[function(require,module,exports){
17715 "use strict";
17716 Object.defineProperty(exports, "__esModule", { value: true });
17717 var concatMap_1 = require("./concatMap");
17718 function concatMapTo(innerObservable, resultSelector) {
17719     return concatMap_1.concatMap(function () { return innerObservable; }, resultSelector);
17720 }
17721 exports.concatMapTo = concatMapTo;
17722
17723 },{"./concatMap":101}],103:[function(require,module,exports){
17724 "use strict";
17725 var __extends = (this && this.__extends) || (function () {
17726     var extendStatics = function (d, b) {
17727         extendStatics = Object.setPrototypeOf ||
17728             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17729             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17730         return extendStatics(d, b);
17731     }
17732     return function (d, b) {
17733         extendStatics(d, b);
17734         function __() { this.constructor = d; }
17735         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17736     };
17737 })();
17738 Object.defineProperty(exports, "__esModule", { value: true });
17739 var Subscriber_1 = require("../Subscriber");
17740 function count(predicate) {
17741     return function (source) { return source.lift(new CountOperator(predicate, source)); };
17742 }
17743 exports.count = count;
17744 var CountOperator = (function () {
17745     function CountOperator(predicate, source) {
17746         this.predicate = predicate;
17747         this.source = source;
17748     }
17749     CountOperator.prototype.call = function (subscriber, source) {
17750         return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source));
17751     };
17752     return CountOperator;
17753 }());
17754 var CountSubscriber = (function (_super) {
17755     __extends(CountSubscriber, _super);
17756     function CountSubscriber(destination, predicate, source) {
17757         var _this = _super.call(this, destination) || this;
17758         _this.predicate = predicate;
17759         _this.source = source;
17760         _this.count = 0;
17761         _this.index = 0;
17762         return _this;
17763     }
17764     CountSubscriber.prototype._next = function (value) {
17765         if (this.predicate) {
17766             this._tryPredicate(value);
17767         }
17768         else {
17769             this.count++;
17770         }
17771     };
17772     CountSubscriber.prototype._tryPredicate = function (value) {
17773         var result;
17774         try {
17775             result = this.predicate(value, this.index++, this.source);
17776         }
17777         catch (err) {
17778             this.destination.error(err);
17779             return;
17780         }
17781         if (result) {
17782             this.count++;
17783         }
17784     };
17785     CountSubscriber.prototype._complete = function () {
17786         this.destination.next(this.count);
17787         this.destination.complete();
17788     };
17789     return CountSubscriber;
17790 }(Subscriber_1.Subscriber));
17791
17792 },{"../Subscriber":55}],104:[function(require,module,exports){
17793 "use strict";
17794 var __extends = (this && this.__extends) || (function () {
17795     var extendStatics = function (d, b) {
17796         extendStatics = Object.setPrototypeOf ||
17797             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17798             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17799         return extendStatics(d, b);
17800     }
17801     return function (d, b) {
17802         extendStatics(d, b);
17803         function __() { this.constructor = d; }
17804         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17805     };
17806 })();
17807 Object.defineProperty(exports, "__esModule", { value: true });
17808 var OuterSubscriber_1 = require("../OuterSubscriber");
17809 var subscribeToResult_1 = require("../util/subscribeToResult");
17810 function debounce(durationSelector) {
17811     return function (source) { return source.lift(new DebounceOperator(durationSelector)); };
17812 }
17813 exports.debounce = debounce;
17814 var DebounceOperator = (function () {
17815     function DebounceOperator(durationSelector) {
17816         this.durationSelector = durationSelector;
17817     }
17818     DebounceOperator.prototype.call = function (subscriber, source) {
17819         return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector));
17820     };
17821     return DebounceOperator;
17822 }());
17823 var DebounceSubscriber = (function (_super) {
17824     __extends(DebounceSubscriber, _super);
17825     function DebounceSubscriber(destination, durationSelector) {
17826         var _this = _super.call(this, destination) || this;
17827         _this.durationSelector = durationSelector;
17828         _this.hasValue = false;
17829         _this.durationSubscription = null;
17830         return _this;
17831     }
17832     DebounceSubscriber.prototype._next = function (value) {
17833         try {
17834             var result = this.durationSelector.call(this, value);
17835             if (result) {
17836                 this._tryNext(value, result);
17837             }
17838         }
17839         catch (err) {
17840             this.destination.error(err);
17841         }
17842     };
17843     DebounceSubscriber.prototype._complete = function () {
17844         this.emitValue();
17845         this.destination.complete();
17846     };
17847     DebounceSubscriber.prototype._tryNext = function (value, duration) {
17848         var subscription = this.durationSubscription;
17849         this.value = value;
17850         this.hasValue = true;
17851         if (subscription) {
17852             subscription.unsubscribe();
17853             this.remove(subscription);
17854         }
17855         subscription = subscribeToResult_1.subscribeToResult(this, duration);
17856         if (subscription && !subscription.closed) {
17857             this.add(this.durationSubscription = subscription);
17858         }
17859     };
17860     DebounceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
17861         this.emitValue();
17862     };
17863     DebounceSubscriber.prototype.notifyComplete = function () {
17864         this.emitValue();
17865     };
17866     DebounceSubscriber.prototype.emitValue = function () {
17867         if (this.hasValue) {
17868             var value = this.value;
17869             var subscription = this.durationSubscription;
17870             if (subscription) {
17871                 this.durationSubscription = null;
17872                 subscription.unsubscribe();
17873                 this.remove(subscription);
17874             }
17875             this.value = null;
17876             this.hasValue = false;
17877             _super.prototype._next.call(this, value);
17878         }
17879     };
17880     return DebounceSubscriber;
17881 }(OuterSubscriber_1.OuterSubscriber));
17882
17883 },{"../OuterSubscriber":50,"../util/subscribeToResult":238}],105:[function(require,module,exports){
17884 "use strict";
17885 var __extends = (this && this.__extends) || (function () {
17886     var extendStatics = function (d, b) {
17887         extendStatics = Object.setPrototypeOf ||
17888             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17889             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17890         return extendStatics(d, b);
17891     }
17892     return function (d, b) {
17893         extendStatics(d, b);
17894         function __() { this.constructor = d; }
17895         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17896     };
17897 })();
17898 Object.defineProperty(exports, "__esModule", { value: true });
17899 var Subscriber_1 = require("../Subscriber");
17900 var async_1 = require("../scheduler/async");
17901 function debounceTime(dueTime, scheduler) {
17902     if (scheduler === void 0) { scheduler = async_1.async; }
17903     return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); };
17904 }
17905 exports.debounceTime = debounceTime;
17906 var DebounceTimeOperator = (function () {
17907     function DebounceTimeOperator(dueTime, scheduler) {
17908         this.dueTime = dueTime;
17909         this.scheduler = scheduler;
17910     }
17911     DebounceTimeOperator.prototype.call = function (subscriber, source) {
17912         return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
17913     };
17914     return DebounceTimeOperator;
17915 }());
17916 var DebounceTimeSubscriber = (function (_super) {
17917     __extends(DebounceTimeSubscriber, _super);
17918     function DebounceTimeSubscriber(destination, dueTime, scheduler) {
17919         var _this = _super.call(this, destination) || this;
17920         _this.dueTime = dueTime;
17921         _this.scheduler = scheduler;
17922         _this.debouncedSubscription = null;
17923         _this.lastValue = null;
17924         _this.hasValue = false;
17925         return _this;
17926     }
17927     DebounceTimeSubscriber.prototype._next = function (value) {
17928         this.clearDebounce();
17929         this.lastValue = value;
17930         this.hasValue = true;
17931         this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
17932     };
17933     DebounceTimeSubscriber.prototype._complete = function () {
17934         this.debouncedNext();
17935         this.destination.complete();
17936     };
17937     DebounceTimeSubscriber.prototype.debouncedNext = function () {
17938         this.clearDebounce();
17939         if (this.hasValue) {
17940             var lastValue = this.lastValue;
17941             this.lastValue = null;
17942             this.hasValue = false;
17943             this.destination.next(lastValue);
17944         }
17945     };
17946     DebounceTimeSubscriber.prototype.clearDebounce = function () {
17947         var debouncedSubscription = this.debouncedSubscription;
17948         if (debouncedSubscription !== null) {
17949             this.remove(debouncedSubscription);
17950             debouncedSubscription.unsubscribe();
17951             this.debouncedSubscription = null;
17952         }
17953     };
17954     return DebounceTimeSubscriber;
17955 }(Subscriber_1.Subscriber));
17956 function dispatchNext(subscriber) {
17957     subscriber.debouncedNext();
17958 }
17959
17960 },{"../Subscriber":55,"../scheduler/async":204}],106:[function(require,module,exports){
17961 "use strict";
17962 var __extends = (this && this.__extends) || (function () {
17963     var extendStatics = function (d, b) {
17964         extendStatics = Object.setPrototypeOf ||
17965             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17966             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17967         return extendStatics(d, b);
17968     }
17969     return function (d, b) {
17970         extendStatics(d, b);
17971         function __() { this.constructor = d; }
17972         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17973     };
17974 })();
17975 Object.defineProperty(exports, "__esModule", { value: true });
17976 var Subscriber_1 = require("../Subscriber");
17977 function defaultIfEmpty(defaultValue) {
17978     if (defaultValue === void 0) { defaultValue = null; }
17979     return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); };
17980 }
17981 exports.defaultIfEmpty = defaultIfEmpty;
17982 var DefaultIfEmptyOperator = (function () {
17983     function DefaultIfEmptyOperator(defaultValue) {
17984         this.defaultValue = defaultValue;
17985     }
17986     DefaultIfEmptyOperator.prototype.call = function (subscriber, source) {
17987         return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
17988     };
17989     return DefaultIfEmptyOperator;
17990 }());
17991 var DefaultIfEmptySubscriber = (function (_super) {
17992     __extends(DefaultIfEmptySubscriber, _super);
17993     function DefaultIfEmptySubscriber(destination, defaultValue) {
17994         var _this = _super.call(this, destination) || this;
17995         _this.defaultValue = defaultValue;
17996         _this.isEmpty = true;
17997         return _this;
17998     }
17999     DefaultIfEmptySubscriber.prototype._next = function (value) {
18000         this.isEmpty = false;
18001         this.destination.next(value);
18002     };
18003     DefaultIfEmptySubscriber.prototype._complete = function () {
18004         if (this.isEmpty) {
18005             this.destination.next(this.defaultValue);
18006         }
18007         this.destination.complete();
18008     };
18009     return DefaultIfEmptySubscriber;
18010 }(Subscriber_1.Subscriber));
18011
18012 },{"../Subscriber":55}],107:[function(require,module,exports){
18013 "use strict";
18014 var __extends = (this && this.__extends) || (function () {
18015     var extendStatics = function (d, b) {
18016         extendStatics = Object.setPrototypeOf ||
18017             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18018             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18019         return extendStatics(d, b);
18020     }
18021     return function (d, b) {
18022         extendStatics(d, b);
18023         function __() { this.constructor = d; }
18024         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18025     };
18026 })();
18027 Object.defineProperty(exports, "__esModule", { value: true });
18028 var async_1 = require("../scheduler/async");
18029 var isDate_1 = require("../util/isDate");
18030 var Subscriber_1 = require("../Subscriber");
18031 var Notification_1 = require("../Notification");
18032 function delay(delay, scheduler) {
18033     if (scheduler === void 0) { scheduler = async_1.async; }
18034     var absoluteDelay = isDate_1.isDate(delay);
18035     var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
18036     return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };
18037 }
18038 exports.delay = delay;
18039 var DelayOperator = (function () {
18040     function DelayOperator(delay, scheduler) {
18041         this.delay = delay;
18042         this.scheduler = scheduler;
18043     }
18044     DelayOperator.prototype.call = function (subscriber, source) {
18045         return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
18046     };
18047     return DelayOperator;
18048 }());
18049 var DelaySubscriber = (function (_super) {
18050     __extends(DelaySubscriber, _super);
18051     function DelaySubscriber(destination, delay, scheduler) {
18052         var _this = _super.call(this, destination) || this;
18053         _this.delay = delay;
18054         _this.scheduler = scheduler;
18055         _this.queue = [];
18056         _this.active = false;
18057         _this.errored = false;
18058         return _this;
18059     }
18060     DelaySubscriber.dispatch = function (state) {
18061         var source = state.source;
18062         var queue = source.queue;
18063         var scheduler = state.scheduler;
18064         var destination = state.destination;
18065         while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
18066             queue.shift().notification.observe(destination);
18067         }
18068         if (queue.length > 0) {
18069             var delay_1 = Math.max(0, queue[0].time - scheduler.now());
18070             this.schedule(state, delay_1);
18071         }
18072         else {
18073             this.unsubscribe();
18074             source.active = false;
18075         }
18076     };
18077     DelaySubscriber.prototype._schedule = function (scheduler) {
18078         this.active = true;
18079         var destination = this.destination;
18080         destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
18081             source: this, destination: this.destination, scheduler: scheduler
18082         }));
18083     };
18084     DelaySubscriber.prototype.scheduleNotification = function (notification) {
18085         if (this.errored === true) {
18086             return;
18087         }
18088         var scheduler = this.scheduler;
18089         var message = new DelayMessage(scheduler.now() + this.delay, notification);
18090         this.queue.push(message);
18091         if (this.active === false) {
18092             this._schedule(scheduler);
18093         }
18094     };
18095     DelaySubscriber.prototype._next = function (value) {
18096         this.scheduleNotification(Notification_1.Notification.createNext(value));
18097     };
18098     DelaySubscriber.prototype._error = function (err) {
18099         this.errored = true;
18100         this.queue = [];
18101         this.destination.error(err);
18102         this.unsubscribe();
18103     };
18104     DelaySubscriber.prototype._complete = function () {
18105         this.scheduleNotification(Notification_1.Notification.createComplete());
18106         this.unsubscribe();
18107     };
18108     return DelaySubscriber;
18109 }(Subscriber_1.Subscriber));
18110 var DelayMessage = (function () {
18111     function DelayMessage(time, notification) {
18112         this.time = time;
18113         this.notification = notification;
18114     }
18115     return DelayMessage;
18116 }());
18117
18118 },{"../Notification":47,"../Subscriber":55,"../scheduler/async":204,"../util/isDate":221}],108:[function(require,module,exports){
18119 "use strict";
18120 var __extends = (this && this.__extends) || (function () {
18121     var extendStatics = function (d, b) {
18122         extendStatics = Object.setPrototypeOf ||
18123             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18124             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18125         return extendStatics(d, b);
18126     }
18127     return function (d, b) {
18128         extendStatics(d, b);
18129         function __() { this.constructor = d; }
18130         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18131     };
18132 })();
18133 Object.defineProperty(exports, "__esModule", { value: true });
18134 var Subscriber_1 = require("../Subscriber");
18135 var Observable_1 = require("../Observable");
18136 var OuterSubscriber_1 = require("../OuterSubscriber");
18137 var subscribeToResult_1 = require("../util/subscribeToResult");
18138 function delayWhen(delayDurationSelector, subscriptionDelay) {
18139     if (subscriptionDelay) {
18140         return function (source) {
18141             return new SubscriptionDelayObservable(source, subscriptionDelay)
18142                 .lift(new DelayWhenOperator(delayDurationSelector));
18143         };
18144     }
18145     return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); };
18146 }
18147 exports.delayWhen = delayWhen;
18148 var DelayWhenOperator = (function () {
18149     function DelayWhenOperator(delayDurationSelector) {
18150         this.delayDurationSelector = delayDurationSelector;
18151     }
18152     DelayWhenOperator.prototype.call = function (subscriber, source) {
18153         return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector));
18154     };
18155     return DelayWhenOperator;
18156 }());
18157 var DelayWhenSubscriber = (function (_super) {
18158     __extends(DelayWhenSubscriber, _super);
18159     function DelayWhenSubscriber(destination, delayDurationSelector) {
18160         var _this = _super.call(this, destination) || this;
18161         _this.delayDurationSelector = delayDurationSelector;
18162         _this.completed = false;
18163         _this.delayNotifierSubscriptions = [];
18164         _this.index = 0;
18165         return _this;
18166     }
18167     DelayWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
18168         this.destination.next(outerValue);
18169         this.removeSubscription(innerSub);
18170         this.tryComplete();
18171     };
18172     DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) {
18173         this._error(error);
18174     };
18175     DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) {
18176         var value = this.removeSubscription(innerSub);
18177         if (value) {
18178             this.destination.next(value);
18179         }
18180         this.tryComplete();
18181     };
18182     DelayWhenSubscriber.prototype._next = function (value) {
18183         var index = this.index++;
18184         try {
18185             var delayNotifier = this.delayDurationSelector(value, index);
18186             if (delayNotifier) {
18187                 this.tryDelay(delayNotifier, value);
18188             }
18189         }
18190         catch (err) {
18191             this.destination.error(err);
18192         }
18193     };
18194     DelayWhenSubscriber.prototype._complete = function () {
18195         this.completed = true;
18196         this.tryComplete();
18197         this.unsubscribe();
18198     };
18199     DelayWhenSubscriber.prototype.removeSubscription = function (subscription) {
18200         subscription.unsubscribe();
18201         var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);
18202         if (subscriptionIdx !== -1) {
18203             this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);
18204         }
18205         return subscription.outerValue;
18206     };
18207     DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) {
18208         var notifierSubscription = subscribeToResult_1.subscribeToResult(this, delayNotifier, value);
18209         if (notifierSubscription && !notifierSubscription.closed) {
18210             var destination = this.destination;
18211             destination.add(notifierSubscription);
18212             this.delayNotifierSubscriptions.push(notifierSubscription);
18213         }
18214     };
18215     DelayWhenSubscriber.prototype.tryComplete = function () {
18216         if (this.completed && this.delayNotifierSubscriptions.length === 0) {
18217             this.destination.complete();
18218         }
18219     };
18220     return DelayWhenSubscriber;
18221 }(OuterSubscriber_1.OuterSubscriber));
18222 var SubscriptionDelayObservable = (function (_super) {
18223     __extends(SubscriptionDelayObservable, _super);
18224     function SubscriptionDelayObservable(source, subscriptionDelay) {
18225         var _this = _super.call(this) || this;
18226         _this.source = source;
18227         _this.subscriptionDelay = subscriptionDelay;
18228         return _this;
18229     }
18230     SubscriptionDelayObservable.prototype._subscribe = function (subscriber) {
18231         this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source));
18232     };
18233     return SubscriptionDelayObservable;
18234 }(Observable_1.Observable));
18235 var SubscriptionDelaySubscriber = (function (_super) {
18236     __extends(SubscriptionDelaySubscriber, _super);
18237     function SubscriptionDelaySubscriber(parent, source) {
18238         var _this = _super.call(this) || this;
18239         _this.parent = parent;
18240         _this.source = source;
18241         _this.sourceSubscribed = false;
18242         return _this;
18243     }
18244     SubscriptionDelaySubscriber.prototype._next = function (unused) {
18245         this.subscribeToSource();
18246     };
18247     SubscriptionDelaySubscriber.prototype._error = function (err) {
18248         this.unsubscribe();
18249         this.parent.error(err);
18250     };
18251     SubscriptionDelaySubscriber.prototype._complete = function () {
18252         this.unsubscribe();
18253         this.subscribeToSource();
18254     };
18255     SubscriptionDelaySubscriber.prototype.subscribeToSource = function () {
18256         if (!this.sourceSubscribed) {
18257             this.sourceSubscribed = true;
18258             this.unsubscribe();
18259             this.source.subscribe(this.parent);
18260         }
18261     };
18262     return SubscriptionDelaySubscriber;
18263 }(Subscriber_1.Subscriber));
18264
18265 },{"../Observable":48,"../OuterSubscriber":50,"../Subscriber":55,"../util/subscribeToResult":238}],109:[function(require,module,exports){
18266 "use strict";
18267 var __extends = (this && this.__extends) || (function () {
18268     var extendStatics = function (d, b) {
18269         extendStatics = Object.setPrototypeOf ||
18270             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18271             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18272         return extendStatics(d, b);
18273     }
18274     return function (d, b) {
18275         extendStatics(d, b);
18276         function __() { this.constructor = d; }
18277         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18278     };
18279 })();
18280 Object.defineProperty(exports, "__esModule", { value: true });
18281 var Subscriber_1 = require("../Subscriber");
18282 function dematerialize() {
18283     return function dematerializeOperatorFunction(source) {
18284         return source.lift(new DeMaterializeOperator());
18285     };
18286 }
18287 exports.dematerialize = dematerialize;
18288 var DeMaterializeOperator = (function () {
18289     function DeMaterializeOperator() {
18290     }
18291     DeMaterializeOperator.prototype.call = function (subscriber, source) {
18292         return source.subscribe(new DeMaterializeSubscriber(subscriber));
18293     };
18294     return DeMaterializeOperator;
18295 }());
18296 var DeMaterializeSubscriber = (function (_super) {
18297     __extends(DeMaterializeSubscriber, _super);
18298     function DeMaterializeSubscriber(destination) {
18299         return _super.call(this, destination) || this;
18300     }
18301     DeMaterializeSubscriber.prototype._next = function (value) {
18302         value.observe(this.destination);
18303     };
18304     return DeMaterializeSubscriber;
18305 }(Subscriber_1.Subscriber));
18306
18307 },{"../Subscriber":55}],110:[function(require,module,exports){
18308 "use strict";
18309 var __extends = (this && this.__extends) || (function () {
18310     var extendStatics = function (d, b) {
18311         extendStatics = Object.setPrototypeOf ||
18312             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18313             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18314         return extendStatics(d, b);
18315     }
18316     return function (d, b) {
18317         extendStatics(d, b);
18318         function __() { this.constructor = d; }
18319         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18320     };
18321 })();
18322 Object.defineProperty(exports, "__esModule", { value: true });
18323 var OuterSubscriber_1 = require("../OuterSubscriber");
18324 var subscribeToResult_1 = require("../util/subscribeToResult");
18325 function distinct(keySelector, flushes) {
18326     return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); };
18327 }
18328 exports.distinct = distinct;
18329 var DistinctOperator = (function () {
18330     function DistinctOperator(keySelector, flushes) {
18331         this.keySelector = keySelector;
18332         this.flushes = flushes;
18333     }
18334     DistinctOperator.prototype.call = function (subscriber, source) {
18335         return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
18336     };
18337     return DistinctOperator;
18338 }());
18339 var DistinctSubscriber = (function (_super) {
18340     __extends(DistinctSubscriber, _super);
18341     function DistinctSubscriber(destination, keySelector, flushes) {
18342         var _this = _super.call(this, destination) || this;
18343         _this.keySelector = keySelector;
18344         _this.values = new Set();
18345         if (flushes) {
18346             _this.add(subscribeToResult_1.subscribeToResult(_this, flushes));
18347         }
18348         return _this;
18349     }
18350     DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
18351         this.values.clear();
18352     };
18353     DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
18354         this._error(error);
18355     };
18356     DistinctSubscriber.prototype._next = function (value) {
18357         if (this.keySelector) {
18358             this._useKeySelector(value);
18359         }
18360         else {
18361             this._finalizeNext(value, value);
18362         }
18363     };
18364     DistinctSubscriber.prototype._useKeySelector = function (value) {
18365         var key;
18366         var destination = this.destination;
18367         try {
18368             key = this.keySelector(value);
18369         }
18370         catch (err) {
18371             destination.error(err);
18372             return;
18373         }
18374         this._finalizeNext(key, value);
18375     };
18376     DistinctSubscriber.prototype._finalizeNext = function (key, value) {
18377         var values = this.values;
18378         if (!values.has(key)) {
18379             values.add(key);
18380             this.destination.next(value);
18381         }
18382     };
18383     return DistinctSubscriber;
18384 }(OuterSubscriber_1.OuterSubscriber));
18385 exports.DistinctSubscriber = DistinctSubscriber;
18386
18387 },{"../OuterSubscriber":50,"../util/subscribeToResult":238}],111:[function(require,module,exports){
18388 "use strict";
18389 var __extends = (this && this.__extends) || (function () {
18390     var extendStatics = function (d, b) {
18391         extendStatics = Object.setPrototypeOf ||
18392             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18393             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18394         return extendStatics(d, b);
18395     }
18396     return function (d, b) {
18397         extendStatics(d, b);
18398         function __() { this.constructor = d; }
18399         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18400     };
18401 })();
18402 Object.defineProperty(exports, "__esModule", { value: true });
18403 var Subscriber_1 = require("../Subscriber");
18404 var tryCatch_1 = require("../util/tryCatch");
18405 var errorObject_1 = require("../util/errorObject");
18406 function distinctUntilChanged(compare, keySelector) {
18407     return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); };
18408 }
18409 exports.distinctUntilChanged = distinctUntilChanged;
18410 var DistinctUntilChangedOperator = (function () {
18411     function DistinctUntilChangedOperator(compare, keySelector) {
18412         this.compare = compare;
18413         this.keySelector = keySelector;
18414     }
18415     DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
18416         return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
18417     };
18418     return DistinctUntilChangedOperator;
18419 }());
18420 var DistinctUntilChangedSubscriber = (function (_super) {
18421     __extends(DistinctUntilChangedSubscriber, _super);
18422     function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
18423         var _this = _super.call(this, destination) || this;
18424         _this.keySelector = keySelector;
18425         _this.hasKey = false;
18426         if (typeof compare === 'function') {
18427             _this.compare = compare;
18428         }
18429         return _this;
18430     }
18431     DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
18432         return x === y;
18433     };
18434     DistinctUntilChangedSubscriber.prototype._next = function (value) {
18435         var keySelector = this.keySelector;
18436         var key = value;
18437         if (keySelector) {
18438             key = tryCatch_1.tryCatch(this.keySelector)(value);
18439             if (key === errorObject_1.errorObject) {
18440                 return this.destination.error(errorObject_1.errorObject.e);
18441             }
18442         }
18443         var result = false;
18444         if (this.hasKey) {
18445             result = tryCatch_1.tryCatch(this.compare)(this.key, key);
18446             if (result === errorObject_1.errorObject) {
18447                 return this.destination.error(errorObject_1.errorObject.e);
18448             }
18449         }
18450         else {
18451             this.hasKey = true;
18452         }
18453         if (Boolean(result) === false) {
18454             this.key = key;
18455             this.destination.next(value);
18456         }
18457     };
18458     return DistinctUntilChangedSubscriber;
18459 }(Subscriber_1.Subscriber));
18460
18461 },{"../Subscriber":55,"../util/errorObject":216,"../util/tryCatch":240}],112:[function(require,module,exports){
18462 "use strict";
18463 Object.defineProperty(exports, "__esModule", { value: true });
18464 var distinctUntilChanged_1 = require("./distinctUntilChanged");
18465 function distinctUntilKeyChanged(key, compare) {
18466     return distinctUntilChanged_1.distinctUntilChanged(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; });
18467 }
18468 exports.distinctUntilKeyChanged = distinctUntilKeyChanged;
18469
18470 },{"./distinctUntilChanged":111}],113:[function(require,module,exports){
18471 "use strict";
18472 Object.defineProperty(exports, "__esModule", { value: true });
18473 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
18474 var filter_1 = require("./filter");
18475 var throwIfEmpty_1 = require("./throwIfEmpty");
18476 var defaultIfEmpty_1 = require("./defaultIfEmpty");
18477 var take_1 = require("./take");
18478 function elementAt(index, defaultValue) {
18479     if (index < 0) {
18480         throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError();
18481     }
18482     var hasDefaultValue = arguments.length >= 2;
18483     return function (source) { return source.pipe(filter_1.filter(function (v, i) { return i === index; }), take_1.take(1), hasDefaultValue
18484         ? defaultIfEmpty_1.defaultIfEmpty(defaultValue)
18485         : throwIfEmpty_1.throwIfEmpty(function () { return new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError(); })); };
18486 }
18487 exports.elementAt = elementAt;
18488
18489 },{"../util/ArgumentOutOfRangeError":209,"./defaultIfEmpty":106,"./filter":119,"./take":171,"./throwIfEmpty":178}],114:[function(require,module,exports){
18490 "use strict";
18491 Object.defineProperty(exports, "__esModule", { value: true });
18492 var fromArray_1 = require("../observable/fromArray");
18493 var scalar_1 = require("../observable/scalar");
18494 var empty_1 = require("../observable/empty");
18495 var concat_1 = require("../observable/concat");
18496 var isScheduler_1 = require("../util/isScheduler");
18497 function endWith() {
18498     var array = [];
18499     for (var _i = 0; _i < arguments.length; _i++) {
18500         array[_i] = arguments[_i];
18501     }
18502     return function (source) {
18503         var scheduler = array[array.length - 1];
18504         if (isScheduler_1.isScheduler(scheduler)) {
18505             array.pop();
18506         }
18507         else {
18508             scheduler = null;
18509         }
18510         var len = array.length;
18511         if (len === 1 && !scheduler) {
18512             return concat_1.concat(source, scalar_1.scalar(array[0]));
18513         }
18514         else if (len > 0) {
18515             return concat_1.concat(source, fromArray_1.fromArray(array, scheduler));
18516         }
18517         else {
18518             return concat_1.concat(source, empty_1.empty(scheduler));
18519         }
18520     };
18521 }
18522 exports.endWith = endWith;
18523
18524 },{"../observable/concat":63,"../observable/empty":65,"../observable/fromArray":68,"../observable/scalar":84,"../util/isScheduler":229}],115:[function(require,module,exports){
18525 "use strict";
18526 var __extends = (this && this.__extends) || (function () {
18527     var extendStatics = function (d, b) {
18528         extendStatics = Object.setPrototypeOf ||
18529             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18530             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18531         return extendStatics(d, b);
18532     }
18533     return function (d, b) {
18534         extendStatics(d, b);
18535         function __() { this.constructor = d; }
18536         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18537     };
18538 })();
18539 Object.defineProperty(exports, "__esModule", { value: true });
18540 var Subscriber_1 = require("../Subscriber");
18541 function every(predicate, thisArg) {
18542     return function (source) { return source.lift(new EveryOperator(predicate, thisArg, source)); };
18543 }
18544 exports.every = every;
18545 var EveryOperator = (function () {
18546     function EveryOperator(predicate, thisArg, source) {
18547         this.predicate = predicate;
18548         this.thisArg = thisArg;
18549         this.source = source;
18550     }
18551     EveryOperator.prototype.call = function (observer, source) {
18552         return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));
18553     };
18554     return EveryOperator;
18555 }());
18556 var EverySubscriber = (function (_super) {
18557     __extends(EverySubscriber, _super);
18558     function EverySubscriber(destination, predicate, thisArg, source) {
18559         var _this = _super.call(this, destination) || this;
18560         _this.predicate = predicate;
18561         _this.thisArg = thisArg;
18562         _this.source = source;
18563         _this.index = 0;
18564         _this.thisArg = thisArg || _this;
18565         return _this;
18566     }
18567     EverySubscriber.prototype.notifyComplete = function (everyValueMatch) {
18568         this.destination.next(everyValueMatch);
18569         this.destination.complete();
18570     };
18571     EverySubscriber.prototype._next = function (value) {
18572         var result = false;
18573         try {
18574             result = this.predicate.call(this.thisArg, value, this.index++, this.source);
18575         }
18576         catch (err) {
18577             this.destination.error(err);
18578             return;
18579         }
18580         if (!result) {
18581             this.notifyComplete(false);
18582         }
18583     };
18584     EverySubscriber.prototype._complete = function () {
18585         this.notifyComplete(true);
18586     };
18587     return EverySubscriber;
18588 }(Subscriber_1.Subscriber));
18589
18590 },{"../Subscriber":55}],116:[function(require,module,exports){
18591 "use strict";
18592 var __extends = (this && this.__extends) || (function () {
18593     var extendStatics = function (d, b) {
18594         extendStatics = Object.setPrototypeOf ||
18595             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18596             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18597         return extendStatics(d, b);
18598     }
18599     return function (d, b) {
18600         extendStatics(d, b);
18601         function __() { this.constructor = d; }
18602         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18603     };
18604 })();
18605 Object.defineProperty(exports, "__esModule", { value: true });
18606 var OuterSubscriber_1 = require("../OuterSubscriber");
18607 var subscribeToResult_1 = require("../util/subscribeToResult");
18608 function exhaust() {
18609     return function (source) { return source.lift(new SwitchFirstOperator()); };
18610 }
18611 exports.exhaust = exhaust;
18612 var SwitchFirstOperator = (function () {
18613     function SwitchFirstOperator() {
18614     }
18615     SwitchFirstOperator.prototype.call = function (subscriber, source) {
18616         return source.subscribe(new SwitchFirstSubscriber(subscriber));
18617     };
18618     return SwitchFirstOperator;
18619 }());
18620 var SwitchFirstSubscriber = (function (_super) {
18621     __extends(SwitchFirstSubscriber, _super);
18622     function SwitchFirstSubscriber(destination) {
18623         var _this = _super.call(this, destination) || this;
18624         _this.hasCompleted = false;
18625         _this.hasSubscription = false;
18626         return _this;
18627     }
18628     SwitchFirstSubscriber.prototype._next = function (value) {
18629         if (!this.hasSubscription) {
18630             this.hasSubscription = true;
18631             this.add(subscribeToResult_1.subscribeToResult(this, value));
18632         }
18633     };
18634     SwitchFirstSubscriber.prototype._complete = function () {
18635         this.hasCompleted = true;
18636         if (!this.hasSubscription) {
18637             this.destination.complete();
18638         }
18639     };
18640     SwitchFirstSubscriber.prototype.notifyComplete = function (innerSub) {
18641         this.remove(innerSub);
18642         this.hasSubscription = false;
18643         if (this.hasCompleted) {
18644             this.destination.complete();
18645         }
18646     };
18647     return SwitchFirstSubscriber;
18648 }(OuterSubscriber_1.OuterSubscriber));
18649
18650 },{"../OuterSubscriber":50,"../util/subscribeToResult":238}],117:[function(require,module,exports){
18651 "use strict";
18652 var __extends = (this && this.__extends) || (function () {
18653     var extendStatics = function (d, b) {
18654         extendStatics = Object.setPrototypeOf ||
18655             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18656             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18657         return extendStatics(d, b);
18658     }
18659     return function (d, b) {
18660         extendStatics(d, b);
18661         function __() { this.constructor = d; }
18662         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18663     };
18664 })();
18665 Object.defineProperty(exports, "__esModule", { value: true });
18666 var OuterSubscriber_1 = require("../OuterSubscriber");
18667 var InnerSubscriber_1 = require("../InnerSubscriber");
18668 var subscribeToResult_1 = require("../util/subscribeToResult");
18669 var map_1 = require("./map");
18670 var from_1 = require("../observable/from");
18671 function exhaustMap(project, resultSelector) {
18672     if (resultSelector) {
18673         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); })); })); };
18674     }
18675     return function (source) {
18676         return source.lift(new ExhauseMapOperator(project));
18677     };
18678 }
18679 exports.exhaustMap = exhaustMap;
18680 var ExhauseMapOperator = (function () {
18681     function ExhauseMapOperator(project) {
18682         this.project = project;
18683     }
18684     ExhauseMapOperator.prototype.call = function (subscriber, source) {
18685         return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project));
18686     };
18687     return ExhauseMapOperator;
18688 }());
18689 var ExhaustMapSubscriber = (function (_super) {
18690     __extends(ExhaustMapSubscriber, _super);
18691     function ExhaustMapSubscriber(destination, project) {
18692         var _this = _super.call(this, destination) || this;
18693         _this.project = project;
18694         _this.hasSubscription = false;
18695         _this.hasCompleted = false;
18696         _this.index = 0;
18697         return _this;
18698     }
18699     ExhaustMapSubscriber.prototype._next = function (value) {
18700         if (!this.hasSubscription) {
18701             this.tryNext(value);
18702         }
18703     };
18704     ExhaustMapSubscriber.prototype.tryNext = function (value) {
18705         var result;
18706         var index = this.index++;
18707         try {
18708             result = this.project(value, index);
18709         }
18710         catch (err) {
18711             this.destination.error(err);
18712             return;
18713         }
18714         this.hasSubscription = true;
18715         this._innerSub(result, value, index);
18716     };
18717     ExhaustMapSubscriber.prototype._innerSub = function (result, value, index) {
18718         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
18719         var destination = this.destination;
18720         destination.add(innerSubscriber);
18721         subscribeToResult_1.subscribeToResult(this, result, value, index, innerSubscriber);
18722     };
18723     ExhaustMapSubscriber.prototype._complete = function () {
18724         this.hasCompleted = true;
18725         if (!this.hasSubscription) {
18726             this.destination.complete();
18727         }
18728         this.unsubscribe();
18729     };
18730     ExhaustMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
18731         this.destination.next(innerValue);
18732     };
18733     ExhaustMapSubscriber.prototype.notifyError = function (err) {
18734         this.destination.error(err);
18735     };
18736     ExhaustMapSubscriber.prototype.notifyComplete = function (innerSub) {
18737         var destination = this.destination;
18738         destination.remove(innerSub);
18739         this.hasSubscription = false;
18740         if (this.hasCompleted) {
18741             this.destination.complete();
18742         }
18743     };
18744     return ExhaustMapSubscriber;
18745 }(OuterSubscriber_1.OuterSubscriber));
18746
18747 },{"../InnerSubscriber":46,"../OuterSubscriber":50,"../observable/from":67,"../util/subscribeToResult":238,"./map":128}],118:[function(require,module,exports){
18748 "use strict";
18749 var __extends = (this && this.__extends) || (function () {
18750     var extendStatics = function (d, b) {
18751         extendStatics = Object.setPrototypeOf ||
18752             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18753             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18754         return extendStatics(d, b);
18755     }
18756     return function (d, b) {
18757         extendStatics(d, b);
18758         function __() { this.constructor = d; }
18759         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18760     };
18761 })();
18762 Object.defineProperty(exports, "__esModule", { value: true });
18763 var tryCatch_1 = require("../util/tryCatch");
18764 var errorObject_1 = require("../util/errorObject");
18765 var OuterSubscriber_1 = require("../OuterSubscriber");
18766 var subscribeToResult_1 = require("../util/subscribeToResult");
18767 function expand(project, concurrent, scheduler) {
18768     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
18769     if (scheduler === void 0) { scheduler = undefined; }
18770     concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
18771     return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); };
18772 }
18773 exports.expand = expand;
18774 var ExpandOperator = (function () {
18775     function ExpandOperator(project, concurrent, scheduler) {
18776         this.project = project;
18777         this.concurrent = concurrent;
18778         this.scheduler = scheduler;
18779     }
18780     ExpandOperator.prototype.call = function (subscriber, source) {
18781         return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
18782     };
18783     return ExpandOperator;
18784 }());
18785 exports.ExpandOperator = ExpandOperator;
18786 var ExpandSubscriber = (function (_super) {
18787     __extends(ExpandSubscriber, _super);
18788     function ExpandSubscriber(destination, project, concurrent, scheduler) {
18789         var _this = _super.call(this, destination) || this;
18790         _this.project = project;
18791         _this.concurrent = concurrent;
18792         _this.scheduler = scheduler;
18793         _this.index = 0;
18794         _this.active = 0;
18795         _this.hasCompleted = false;
18796         if (concurrent < Number.POSITIVE_INFINITY) {
18797             _this.buffer = [];
18798         }
18799         return _this;
18800     }
18801     ExpandSubscriber.dispatch = function (arg) {
18802         var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
18803         subscriber.subscribeToProjection(result, value, index);
18804     };
18805     ExpandSubscriber.prototype._next = function (value) {
18806         var destination = this.destination;
18807         if (destination.closed) {
18808             this._complete();
18809             return;
18810         }
18811         var index = this.index++;
18812         if (this.active < this.concurrent) {
18813             destination.next(value);
18814             var result = tryCatch_1.tryCatch(this.project)(value, index);
18815             if (result === errorObject_1.errorObject) {
18816                 destination.error(errorObject_1.errorObject.e);
18817             }
18818             else if (!this.scheduler) {
18819                 this.subscribeToProjection(result, value, index);
18820             }
18821             else {
18822                 var state = { subscriber: this, result: result, value: value, index: index };
18823                 var destination_1 = this.destination;
18824                 destination_1.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
18825             }
18826         }
18827         else {
18828             this.buffer.push(value);
18829         }
18830     };
18831     ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
18832         this.active++;
18833         var destination = this.destination;
18834         destination.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
18835     };
18836     ExpandSubscriber.prototype._complete = function () {
18837         this.hasCompleted = true;
18838         if (this.hasCompleted && this.active === 0) {
18839             this.destination.complete();
18840         }
18841         this.unsubscribe();
18842     };
18843     ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
18844         this._next(innerValue);
18845     };
18846     ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
18847         var buffer = this.buffer;
18848         var destination = this.destination;
18849         destination.remove(innerSub);
18850         this.active--;
18851         if (buffer && buffer.length > 0) {
18852             this._next(buffer.shift());
18853         }
18854         if (this.hasCompleted && this.active === 0) {
18855             this.destination.complete();
18856         }
18857     };
18858     return ExpandSubscriber;
18859 }(OuterSubscriber_1.OuterSubscriber));
18860 exports.ExpandSubscriber = ExpandSubscriber;
18861
18862 },{"../OuterSubscriber":50,"../util/errorObject":216,"../util/subscribeToResult":238,"../util/tryCatch":240}],119:[function(require,module,exports){
18863 "use strict";
18864 var __extends = (this && this.__extends) || (function () {
18865     var extendStatics = function (d, b) {
18866         extendStatics = Object.setPrototypeOf ||
18867             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18868             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18869         return extendStatics(d, b);
18870     }
18871     return function (d, b) {
18872         extendStatics(d, b);
18873         function __() { this.constructor = d; }
18874         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18875     };
18876 })();
18877 Object.defineProperty(exports, "__esModule", { value: true });
18878 var Subscriber_1 = require("../Subscriber");
18879 function filter(predicate, thisArg) {
18880     return function filterOperatorFunction(source) {
18881         return source.lift(new FilterOperator(predicate, thisArg));
18882     };
18883 }
18884 exports.filter = filter;
18885 var FilterOperator = (function () {
18886     function FilterOperator(predicate, thisArg) {
18887         this.predicate = predicate;
18888         this.thisArg = thisArg;
18889     }
18890     FilterOperator.prototype.call = function (subscriber, source) {
18891         return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
18892     };
18893     return FilterOperator;
18894 }());
18895 var FilterSubscriber = (function (_super) {
18896     __extends(FilterSubscriber, _super);
18897     function FilterSubscriber(destination, predicate, thisArg) {
18898         var _this = _super.call(this, destination) || this;
18899         _this.predicate = predicate;
18900         _this.thisArg = thisArg;
18901         _this.count = 0;
18902         return _this;
18903     }
18904     FilterSubscriber.prototype._next = function (value) {
18905         var result;
18906         try {
18907             result = this.predicate.call(this.thisArg, value, this.count++);
18908         }
18909         catch (err) {
18910             this.destination.error(err);
18911             return;
18912         }
18913         if (result) {
18914             this.destination.next(value);
18915         }
18916     };
18917     return FilterSubscriber;
18918 }(Subscriber_1.Subscriber));
18919
18920 },{"../Subscriber":55}],120:[function(require,module,exports){
18921 "use strict";
18922 var __extends = (this && this.__extends) || (function () {
18923     var extendStatics = function (d, b) {
18924         extendStatics = Object.setPrototypeOf ||
18925             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18926             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18927         return extendStatics(d, b);
18928     }
18929     return function (d, b) {
18930         extendStatics(d, b);
18931         function __() { this.constructor = d; }
18932         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18933     };
18934 })();
18935 Object.defineProperty(exports, "__esModule", { value: true });
18936 var Subscriber_1 = require("../Subscriber");
18937 var Subscription_1 = require("../Subscription");
18938 function finalize(callback) {
18939     return function (source) { return source.lift(new FinallyOperator(callback)); };
18940 }
18941 exports.finalize = finalize;
18942 var FinallyOperator = (function () {
18943     function FinallyOperator(callback) {
18944         this.callback = callback;
18945     }
18946     FinallyOperator.prototype.call = function (subscriber, source) {
18947         return source.subscribe(new FinallySubscriber(subscriber, this.callback));
18948     };
18949     return FinallyOperator;
18950 }());
18951 var FinallySubscriber = (function (_super) {
18952     __extends(FinallySubscriber, _super);
18953     function FinallySubscriber(destination, callback) {
18954         var _this = _super.call(this, destination) || this;
18955         _this.add(new Subscription_1.Subscription(callback));
18956         return _this;
18957     }
18958     return FinallySubscriber;
18959 }(Subscriber_1.Subscriber));
18960
18961 },{"../Subscriber":55,"../Subscription":56}],121:[function(require,module,exports){
18962 "use strict";
18963 var __extends = (this && this.__extends) || (function () {
18964     var extendStatics = function (d, b) {
18965         extendStatics = Object.setPrototypeOf ||
18966             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18967             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18968         return extendStatics(d, b);
18969     }
18970     return function (d, b) {
18971         extendStatics(d, b);
18972         function __() { this.constructor = d; }
18973         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
18974     };
18975 })();
18976 Object.defineProperty(exports, "__esModule", { value: true });
18977 var Subscriber_1 = require("../Subscriber");
18978 function find(predicate, thisArg) {
18979     if (typeof predicate !== 'function') {
18980         throw new TypeError('predicate is not a function');
18981     }
18982     return function (source) { return source.lift(new FindValueOperator(predicate, source, false, thisArg)); };
18983 }
18984 exports.find = find;
18985 var FindValueOperator = (function () {
18986     function FindValueOperator(predicate, source, yieldIndex, thisArg) {
18987         this.predicate = predicate;
18988         this.source = source;
18989         this.yieldIndex = yieldIndex;
18990         this.thisArg = thisArg;
18991     }
18992     FindValueOperator.prototype.call = function (observer, source) {
18993         return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));
18994     };
18995     return FindValueOperator;
18996 }());
18997 exports.FindValueOperator = FindValueOperator;
18998 var FindValueSubscriber = (function (_super) {
18999     __extends(FindValueSubscriber, _super);
19000     function FindValueSubscriber(destination, predicate, source, yieldIndex, thisArg) {
19001         var _this = _super.call(this, destination) || this;
19002         _this.predicate = predicate;
19003         _this.source = source;
19004         _this.yieldIndex = yieldIndex;
19005         _this.thisArg = thisArg;
19006         _this.index = 0;
19007         return _this;
19008     }
19009     FindValueSubscriber.prototype.notifyComplete = function (value) {
19010         var destination = this.destination;
19011         destination.next(value);
19012         destination.complete();
19013         this.unsubscribe();
19014     };
19015     FindValueSubscriber.prototype._next = function (value) {
19016         var _a = this, predicate = _a.predicate, thisArg = _a.thisArg;
19017         var index = this.index++;
19018         try {
19019             var result = predicate.call(thisArg || this, value, index, this.source);
19020             if (result) {
19021                 this.notifyComplete(this.yieldIndex ? index : value);
19022             }
19023         }
19024         catch (err) {
19025             this.destination.error(err);
19026         }
19027     };
19028     FindValueSubscriber.prototype._complete = function () {
19029         this.notifyComplete(this.yieldIndex ? -1 : undefined);
19030     };
19031     return FindValueSubscriber;
19032 }(Subscriber_1.Subscriber));
19033 exports.FindValueSubscriber = FindValueSubscriber;
19034
19035 },{"../Subscriber":55}],122:[function(require,module,exports){
19036 "use strict";
19037 Object.defineProperty(exports, "__esModule", { value: true });
19038 var find_1 = require("../operators/find");
19039 function findIndex(predicate, thisArg) {
19040     return function (source) { return source.lift(new find_1.FindValueOperator(predicate, source, true, thisArg)); };
19041 }
19042 exports.findIndex = findIndex;
19043
19044 },{"../operators/find":121}],123:[function(require,module,exports){
19045 "use strict";
19046 Object.defineProperty(exports, "__esModule", { value: true });
19047 var EmptyError_1 = require("../util/EmptyError");
19048 var filter_1 = require("./filter");
19049 var take_1 = require("./take");
19050 var defaultIfEmpty_1 = require("./defaultIfEmpty");
19051 var throwIfEmpty_1 = require("./throwIfEmpty");
19052 var identity_1 = require("../util/identity");
19053 function first(predicate, defaultValue) {
19054     var hasDefaultValue = arguments.length >= 2;
19055     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(); })); };
19056 }
19057 exports.first = first;
19058
19059 },{"../util/EmptyError":210,"../util/identity":218,"./defaultIfEmpty":106,"./filter":119,"./take":171,"./throwIfEmpty":178}],124:[function(require,module,exports){
19060 "use strict";
19061 var __extends = (this && this.__extends) || (function () {
19062     var extendStatics = function (d, b) {
19063         extendStatics = Object.setPrototypeOf ||
19064             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19065             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19066         return extendStatics(d, b);
19067     }
19068     return function (d, b) {
19069         extendStatics(d, b);
19070         function __() { this.constructor = d; }
19071         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19072     };
19073 })();
19074 Object.defineProperty(exports, "__esModule", { value: true });
19075 var Subscriber_1 = require("../Subscriber");
19076 var Subscription_1 = require("../Subscription");
19077 var Observable_1 = require("../Observable");
19078 var Subject_1 = require("../Subject");
19079 function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) {
19080     return function (source) {
19081         return source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));
19082     };
19083 }
19084 exports.groupBy = groupBy;
19085 var GroupByOperator = (function () {
19086     function GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector) {
19087         this.keySelector = keySelector;
19088         this.elementSelector = elementSelector;
19089         this.durationSelector = durationSelector;
19090         this.subjectSelector = subjectSelector;
19091     }
19092     GroupByOperator.prototype.call = function (subscriber, source) {
19093         return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector));
19094     };
19095     return GroupByOperator;
19096 }());
19097 var GroupBySubscriber = (function (_super) {
19098     __extends(GroupBySubscriber, _super);
19099     function GroupBySubscriber(destination, keySelector, elementSelector, durationSelector, subjectSelector) {
19100         var _this = _super.call(this, destination) || this;
19101         _this.keySelector = keySelector;
19102         _this.elementSelector = elementSelector;
19103         _this.durationSelector = durationSelector;
19104         _this.subjectSelector = subjectSelector;
19105         _this.groups = null;
19106         _this.attemptedToUnsubscribe = false;
19107         _this.count = 0;
19108         return _this;
19109     }
19110     GroupBySubscriber.prototype._next = function (value) {
19111         var key;
19112         try {
19113             key = this.keySelector(value);
19114         }
19115         catch (err) {
19116             this.error(err);
19117             return;
19118         }
19119         this._group(value, key);
19120     };
19121     GroupBySubscriber.prototype._group = function (value, key) {
19122         var groups = this.groups;
19123         if (!groups) {
19124             groups = this.groups = new Map();
19125         }
19126         var group = groups.get(key);
19127         var element;
19128         if (this.elementSelector) {
19129             try {
19130                 element = this.elementSelector(value);
19131             }
19132             catch (err) {
19133                 this.error(err);
19134             }
19135         }
19136         else {
19137             element = value;
19138         }
19139         if (!group) {
19140             group = (this.subjectSelector ? this.subjectSelector() : new Subject_1.Subject());
19141             groups.set(key, group);
19142             var groupedObservable = new GroupedObservable(key, group, this);
19143             this.destination.next(groupedObservable);
19144             if (this.durationSelector) {
19145                 var duration = void 0;
19146                 try {
19147                     duration = this.durationSelector(new GroupedObservable(key, group));
19148                 }
19149                 catch (err) {
19150                     this.error(err);
19151                     return;
19152                 }
19153                 this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));
19154             }
19155         }
19156         if (!group.closed) {
19157             group.next(element);
19158         }
19159     };
19160     GroupBySubscriber.prototype._error = function (err) {
19161         var groups = this.groups;
19162         if (groups) {
19163             groups.forEach(function (group, key) {
19164                 group.error(err);
19165             });
19166             groups.clear();
19167         }
19168         this.destination.error(err);
19169     };
19170     GroupBySubscriber.prototype._complete = function () {
19171         var groups = this.groups;
19172         if (groups) {
19173             groups.forEach(function (group, key) {
19174                 group.complete();
19175             });
19176             groups.clear();
19177         }
19178         this.destination.complete();
19179     };
19180     GroupBySubscriber.prototype.removeGroup = function (key) {
19181         this.groups.delete(key);
19182     };
19183     GroupBySubscriber.prototype.unsubscribe = function () {
19184         if (!this.closed) {
19185             this.attemptedToUnsubscribe = true;
19186             if (this.count === 0) {
19187                 _super.prototype.unsubscribe.call(this);
19188             }
19189         }
19190     };
19191     return GroupBySubscriber;
19192 }(Subscriber_1.Subscriber));
19193 var GroupDurationSubscriber = (function (_super) {
19194     __extends(GroupDurationSubscriber, _super);
19195     function GroupDurationSubscriber(key, group, parent) {
19196         var _this = _super.call(this, group) || this;
19197         _this.key = key;
19198         _this.group = group;
19199         _this.parent = parent;
19200         return _this;
19201     }
19202     GroupDurationSubscriber.prototype._next = function (value) {
19203         this.complete();
19204     };
19205     GroupDurationSubscriber.prototype._unsubscribe = function () {
19206         var _a = this, parent = _a.parent, key = _a.key;
19207         this.key = this.parent = null;
19208         if (parent) {
19209             parent.removeGroup(key);
19210         }
19211     };
19212     return GroupDurationSubscriber;
19213 }(Subscriber_1.Subscriber));
19214 var GroupedObservable = (function (_super) {
19215     __extends(GroupedObservable, _super);
19216     function GroupedObservable(key, groupSubject, refCountSubscription) {
19217         var _this = _super.call(this) || this;
19218         _this.key = key;
19219         _this.groupSubject = groupSubject;
19220         _this.refCountSubscription = refCountSubscription;
19221         return _this;
19222     }
19223     GroupedObservable.prototype._subscribe = function (subscriber) {
19224         var subscription = new Subscription_1.Subscription();
19225         var _a = this, refCountSubscription = _a.refCountSubscription, groupSubject = _a.groupSubject;
19226         if (refCountSubscription && !refCountSubscription.closed) {
19227             subscription.add(new InnerRefCountSubscription(refCountSubscription));
19228         }
19229         subscription.add(groupSubject.subscribe(subscriber));
19230         return subscription;
19231     };
19232     return GroupedObservable;
19233 }(Observable_1.Observable));
19234 exports.GroupedObservable = GroupedObservable;
19235 var InnerRefCountSubscription = (function (_super) {
19236     __extends(InnerRefCountSubscription, _super);
19237     function InnerRefCountSubscription(parent) {
19238         var _this = _super.call(this) || this;
19239         _this.parent = parent;
19240         parent.count++;
19241         return _this;
19242     }
19243     InnerRefCountSubscription.prototype.unsubscribe = function () {
19244         var parent = this.parent;
19245         if (!parent.closed && !this.closed) {
19246             _super.prototype.unsubscribe.call(this);
19247             parent.count -= 1;
19248             if (parent.count === 0 && parent.attemptedToUnsubscribe) {
19249                 parent.unsubscribe();
19250             }
19251         }
19252     };
19253     return InnerRefCountSubscription;
19254 }(Subscription_1.Subscription));
19255
19256 },{"../Observable":48,"../Subject":53,"../Subscriber":55,"../Subscription":56}],125:[function(require,module,exports){
19257 "use strict";
19258 var __extends = (this && this.__extends) || (function () {
19259     var extendStatics = function (d, b) {
19260         extendStatics = Object.setPrototypeOf ||
19261             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19262             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19263         return extendStatics(d, b);
19264     }
19265     return function (d, b) {
19266         extendStatics(d, b);
19267         function __() { this.constructor = d; }
19268         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19269     };
19270 })();
19271 Object.defineProperty(exports, "__esModule", { value: true });
19272 var Subscriber_1 = require("../Subscriber");
19273 function ignoreElements() {
19274     return function ignoreElementsOperatorFunction(source) {
19275         return source.lift(new IgnoreElementsOperator());
19276     };
19277 }
19278 exports.ignoreElements = ignoreElements;
19279 var IgnoreElementsOperator = (function () {
19280     function IgnoreElementsOperator() {
19281     }
19282     IgnoreElementsOperator.prototype.call = function (subscriber, source) {
19283         return source.subscribe(new IgnoreElementsSubscriber(subscriber));
19284     };
19285     return IgnoreElementsOperator;
19286 }());
19287 var IgnoreElementsSubscriber = (function (_super) {
19288     __extends(IgnoreElementsSubscriber, _super);
19289     function IgnoreElementsSubscriber() {
19290         return _super !== null && _super.apply(this, arguments) || this;
19291     }
19292     IgnoreElementsSubscriber.prototype._next = function (unused) {
19293     };
19294     return IgnoreElementsSubscriber;
19295 }(Subscriber_1.Subscriber));
19296
19297 },{"../Subscriber":55}],126:[function(require,module,exports){
19298 "use strict";
19299 var __extends = (this && this.__extends) || (function () {
19300     var extendStatics = function (d, b) {
19301         extendStatics = Object.setPrototypeOf ||
19302             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19303             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19304         return extendStatics(d, b);
19305     }
19306     return function (d, b) {
19307         extendStatics(d, b);
19308         function __() { this.constructor = d; }
19309         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19310     };
19311 })();
19312 Object.defineProperty(exports, "__esModule", { value: true });
19313 var Subscriber_1 = require("../Subscriber");
19314 function isEmpty() {
19315     return function (source) { return source.lift(new IsEmptyOperator()); };
19316 }
19317 exports.isEmpty = isEmpty;
19318 var IsEmptyOperator = (function () {
19319     function IsEmptyOperator() {
19320     }
19321     IsEmptyOperator.prototype.call = function (observer, source) {
19322         return source.subscribe(new IsEmptySubscriber(observer));
19323     };
19324     return IsEmptyOperator;
19325 }());
19326 var IsEmptySubscriber = (function (_super) {
19327     __extends(IsEmptySubscriber, _super);
19328     function IsEmptySubscriber(destination) {
19329         return _super.call(this, destination) || this;
19330     }
19331     IsEmptySubscriber.prototype.notifyComplete = function (isEmpty) {
19332         var destination = this.destination;
19333         destination.next(isEmpty);
19334         destination.complete();
19335     };
19336     IsEmptySubscriber.prototype._next = function (value) {
19337         this.notifyComplete(false);
19338     };
19339     IsEmptySubscriber.prototype._complete = function () {
19340         this.notifyComplete(true);
19341     };
19342     return IsEmptySubscriber;
19343 }(Subscriber_1.Subscriber));
19344
19345 },{"../Subscriber":55}],127:[function(require,module,exports){
19346 "use strict";
19347 Object.defineProperty(exports, "__esModule", { value: true });
19348 var EmptyError_1 = require("../util/EmptyError");
19349 var filter_1 = require("./filter");
19350 var takeLast_1 = require("./takeLast");
19351 var throwIfEmpty_1 = require("./throwIfEmpty");
19352 var defaultIfEmpty_1 = require("./defaultIfEmpty");
19353 var identity_1 = require("../util/identity");
19354 function last(predicate, defaultValue) {
19355     var hasDefaultValue = arguments.length >= 2;
19356     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(); })); };
19357 }
19358 exports.last = last;
19359
19360 },{"../util/EmptyError":210,"../util/identity":218,"./defaultIfEmpty":106,"./filter":119,"./takeLast":172,"./throwIfEmpty":178}],128:[function(require,module,exports){
19361 "use strict";
19362 var __extends = (this && this.__extends) || (function () {
19363     var extendStatics = function (d, b) {
19364         extendStatics = Object.setPrototypeOf ||
19365             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19366             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19367         return extendStatics(d, b);
19368     }
19369     return function (d, b) {
19370         extendStatics(d, b);
19371         function __() { this.constructor = d; }
19372         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19373     };
19374 })();
19375 Object.defineProperty(exports, "__esModule", { value: true });
19376 var Subscriber_1 = require("../Subscriber");
19377 function map(project, thisArg) {
19378     return function mapOperation(source) {
19379         if (typeof project !== 'function') {
19380             throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
19381         }
19382         return source.lift(new MapOperator(project, thisArg));
19383     };
19384 }
19385 exports.map = map;
19386 var MapOperator = (function () {
19387     function MapOperator(project, thisArg) {
19388         this.project = project;
19389         this.thisArg = thisArg;
19390     }
19391     MapOperator.prototype.call = function (subscriber, source) {
19392         return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
19393     };
19394     return MapOperator;
19395 }());
19396 exports.MapOperator = MapOperator;
19397 var MapSubscriber = (function (_super) {
19398     __extends(MapSubscriber, _super);
19399     function MapSubscriber(destination, project, thisArg) {
19400         var _this = _super.call(this, destination) || this;
19401         _this.project = project;
19402         _this.count = 0;
19403         _this.thisArg = thisArg || _this;
19404         return _this;
19405     }
19406     MapSubscriber.prototype._next = function (value) {
19407         var result;
19408         try {
19409             result = this.project.call(this.thisArg, value, this.count++);
19410         }
19411         catch (err) {
19412             this.destination.error(err);
19413             return;
19414         }
19415         this.destination.next(result);
19416     };
19417     return MapSubscriber;
19418 }(Subscriber_1.Subscriber));
19419
19420 },{"../Subscriber":55}],129:[function(require,module,exports){
19421 "use strict";
19422 var __extends = (this && this.__extends) || (function () {
19423     var extendStatics = function (d, b) {
19424         extendStatics = Object.setPrototypeOf ||
19425             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19426             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19427         return extendStatics(d, b);
19428     }
19429     return function (d, b) {
19430         extendStatics(d, b);
19431         function __() { this.constructor = d; }
19432         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19433     };
19434 })();
19435 Object.defineProperty(exports, "__esModule", { value: true });
19436 var Subscriber_1 = require("../Subscriber");
19437 function mapTo(value) {
19438     return function (source) { return source.lift(new MapToOperator(value)); };
19439 }
19440 exports.mapTo = mapTo;
19441 var MapToOperator = (function () {
19442     function MapToOperator(value) {
19443         this.value = value;
19444     }
19445     MapToOperator.prototype.call = function (subscriber, source) {
19446         return source.subscribe(new MapToSubscriber(subscriber, this.value));
19447     };
19448     return MapToOperator;
19449 }());
19450 var MapToSubscriber = (function (_super) {
19451     __extends(MapToSubscriber, _super);
19452     function MapToSubscriber(destination, value) {
19453         var _this = _super.call(this, destination) || this;
19454         _this.value = value;
19455         return _this;
19456     }
19457     MapToSubscriber.prototype._next = function (x) {
19458         this.destination.next(this.value);
19459     };
19460     return MapToSubscriber;
19461 }(Subscriber_1.Subscriber));
19462
19463 },{"../Subscriber":55}],130:[function(require,module,exports){
19464 "use strict";
19465 var __extends = (this && this.__extends) || (function () {
19466     var extendStatics = function (d, b) {
19467         extendStatics = Object.setPrototypeOf ||
19468             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19469             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19470         return extendStatics(d, b);
19471     }
19472     return function (d, b) {
19473         extendStatics(d, b);
19474         function __() { this.constructor = d; }
19475         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19476     };
19477 })();
19478 Object.defineProperty(exports, "__esModule", { value: true });
19479 var Subscriber_1 = require("../Subscriber");
19480 var Notification_1 = require("../Notification");
19481 function materialize() {
19482     return function materializeOperatorFunction(source) {
19483         return source.lift(new MaterializeOperator());
19484     };
19485 }
19486 exports.materialize = materialize;
19487 var MaterializeOperator = (function () {
19488     function MaterializeOperator() {
19489     }
19490     MaterializeOperator.prototype.call = function (subscriber, source) {
19491         return source.subscribe(new MaterializeSubscriber(subscriber));
19492     };
19493     return MaterializeOperator;
19494 }());
19495 var MaterializeSubscriber = (function (_super) {
19496     __extends(MaterializeSubscriber, _super);
19497     function MaterializeSubscriber(destination) {
19498         return _super.call(this, destination) || this;
19499     }
19500     MaterializeSubscriber.prototype._next = function (value) {
19501         this.destination.next(Notification_1.Notification.createNext(value));
19502     };
19503     MaterializeSubscriber.prototype._error = function (err) {
19504         var destination = this.destination;
19505         destination.next(Notification_1.Notification.createError(err));
19506         destination.complete();
19507     };
19508     MaterializeSubscriber.prototype._complete = function () {
19509         var destination = this.destination;
19510         destination.next(Notification_1.Notification.createComplete());
19511         destination.complete();
19512     };
19513     return MaterializeSubscriber;
19514 }(Subscriber_1.Subscriber));
19515
19516 },{"../Notification":47,"../Subscriber":55}],131:[function(require,module,exports){
19517 "use strict";
19518 Object.defineProperty(exports, "__esModule", { value: true });
19519 var reduce_1 = require("./reduce");
19520 function max(comparer) {
19521     var max = (typeof comparer === 'function')
19522         ? function (x, y) { return comparer(x, y) > 0 ? x : y; }
19523         : function (x, y) { return x > y ? x : y; };
19524     return reduce_1.reduce(max);
19525 }
19526 exports.max = max;
19527
19528 },{"./reduce":149}],132:[function(require,module,exports){
19529 "use strict";
19530 Object.defineProperty(exports, "__esModule", { value: true });
19531 var merge_1 = require("../observable/merge");
19532 function merge() {
19533     var observables = [];
19534     for (var _i = 0; _i < arguments.length; _i++) {
19535         observables[_i] = arguments[_i];
19536     }
19537     return function (source) { return source.lift.call(merge_1.merge.apply(void 0, [source].concat(observables))); };
19538 }
19539 exports.merge = merge;
19540
19541 },{"../observable/merge":77}],133:[function(require,module,exports){
19542 "use strict";
19543 Object.defineProperty(exports, "__esModule", { value: true });
19544 var mergeMap_1 = require("./mergeMap");
19545 var identity_1 = require("../util/identity");
19546 function mergeAll(concurrent) {
19547     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
19548     return mergeMap_1.mergeMap(identity_1.identity, concurrent);
19549 }
19550 exports.mergeAll = mergeAll;
19551
19552 },{"../util/identity":218,"./mergeMap":134}],134:[function(require,module,exports){
19553 "use strict";
19554 var __extends = (this && this.__extends) || (function () {
19555     var extendStatics = function (d, b) {
19556         extendStatics = Object.setPrototypeOf ||
19557             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19558             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19559         return extendStatics(d, b);
19560     }
19561     return function (d, b) {
19562         extendStatics(d, b);
19563         function __() { this.constructor = d; }
19564         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19565     };
19566 })();
19567 Object.defineProperty(exports, "__esModule", { value: true });
19568 var subscribeToResult_1 = require("../util/subscribeToResult");
19569 var OuterSubscriber_1 = require("../OuterSubscriber");
19570 var InnerSubscriber_1 = require("../InnerSubscriber");
19571 var map_1 = require("./map");
19572 var from_1 = require("../observable/from");
19573 function mergeMap(project, resultSelector, concurrent) {
19574     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
19575     if (typeof resultSelector === 'function') {
19576         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)); };
19577     }
19578     else if (typeof resultSelector === 'number') {
19579         concurrent = resultSelector;
19580     }
19581     return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); };
19582 }
19583 exports.mergeMap = mergeMap;
19584 var MergeMapOperator = (function () {
19585     function MergeMapOperator(project, concurrent) {
19586         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
19587         this.project = project;
19588         this.concurrent = concurrent;
19589     }
19590     MergeMapOperator.prototype.call = function (observer, source) {
19591         return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));
19592     };
19593     return MergeMapOperator;
19594 }());
19595 exports.MergeMapOperator = MergeMapOperator;
19596 var MergeMapSubscriber = (function (_super) {
19597     __extends(MergeMapSubscriber, _super);
19598     function MergeMapSubscriber(destination, project, concurrent) {
19599         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
19600         var _this = _super.call(this, destination) || this;
19601         _this.project = project;
19602         _this.concurrent = concurrent;
19603         _this.hasCompleted = false;
19604         _this.buffer = [];
19605         _this.active = 0;
19606         _this.index = 0;
19607         return _this;
19608     }
19609     MergeMapSubscriber.prototype._next = function (value) {
19610         if (this.active < this.concurrent) {
19611             this._tryNext(value);
19612         }
19613         else {
19614             this.buffer.push(value);
19615         }
19616     };
19617     MergeMapSubscriber.prototype._tryNext = function (value) {
19618         var result;
19619         var index = this.index++;
19620         try {
19621             result = this.project(value, index);
19622         }
19623         catch (err) {
19624             this.destination.error(err);
19625             return;
19626         }
19627         this.active++;
19628         this._innerSub(result, value, index);
19629     };
19630     MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
19631         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
19632         var destination = this.destination;
19633         destination.add(innerSubscriber);
19634         subscribeToResult_1.subscribeToResult(this, ish, value, index, innerSubscriber);
19635     };
19636     MergeMapSubscriber.prototype._complete = function () {
19637         this.hasCompleted = true;
19638         if (this.active === 0 && this.buffer.length === 0) {
19639             this.destination.complete();
19640         }
19641         this.unsubscribe();
19642     };
19643     MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
19644         this.destination.next(innerValue);
19645     };
19646     MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
19647         var buffer = this.buffer;
19648         this.remove(innerSub);
19649         this.active--;
19650         if (buffer.length > 0) {
19651             this._next(buffer.shift());
19652         }
19653         else if (this.active === 0 && this.hasCompleted) {
19654             this.destination.complete();
19655         }
19656     };
19657     return MergeMapSubscriber;
19658 }(OuterSubscriber_1.OuterSubscriber));
19659 exports.MergeMapSubscriber = MergeMapSubscriber;
19660
19661 },{"../InnerSubscriber":46,"../OuterSubscriber":50,"../observable/from":67,"../util/subscribeToResult":238,"./map":128}],135:[function(require,module,exports){
19662 "use strict";
19663 Object.defineProperty(exports, "__esModule", { value: true });
19664 var mergeMap_1 = require("./mergeMap");
19665 function mergeMapTo(innerObservable, resultSelector, concurrent) {
19666     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
19667     if (typeof resultSelector === 'function') {
19668         return mergeMap_1.mergeMap(function () { return innerObservable; }, resultSelector, concurrent);
19669     }
19670     if (typeof resultSelector === 'number') {
19671         concurrent = resultSelector;
19672     }
19673     return mergeMap_1.mergeMap(function () { return innerObservable; }, concurrent);
19674 }
19675 exports.mergeMapTo = mergeMapTo;
19676
19677 },{"./mergeMap":134}],136:[function(require,module,exports){
19678 "use strict";
19679 var __extends = (this && this.__extends) || (function () {
19680     var extendStatics = function (d, b) {
19681         extendStatics = Object.setPrototypeOf ||
19682             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19683             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19684         return extendStatics(d, b);
19685     }
19686     return function (d, b) {
19687         extendStatics(d, b);
19688         function __() { this.constructor = d; }
19689         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19690     };
19691 })();
19692 Object.defineProperty(exports, "__esModule", { value: true });
19693 var tryCatch_1 = require("../util/tryCatch");
19694 var errorObject_1 = require("../util/errorObject");
19695 var subscribeToResult_1 = require("../util/subscribeToResult");
19696 var OuterSubscriber_1 = require("../OuterSubscriber");
19697 var InnerSubscriber_1 = require("../InnerSubscriber");
19698 function mergeScan(accumulator, seed, concurrent) {
19699     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
19700     return function (source) { return source.lift(new MergeScanOperator(accumulator, seed, concurrent)); };
19701 }
19702 exports.mergeScan = mergeScan;
19703 var MergeScanOperator = (function () {
19704     function MergeScanOperator(accumulator, seed, concurrent) {
19705         this.accumulator = accumulator;
19706         this.seed = seed;
19707         this.concurrent = concurrent;
19708     }
19709     MergeScanOperator.prototype.call = function (subscriber, source) {
19710         return source.subscribe(new MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent));
19711     };
19712     return MergeScanOperator;
19713 }());
19714 exports.MergeScanOperator = MergeScanOperator;
19715 var MergeScanSubscriber = (function (_super) {
19716     __extends(MergeScanSubscriber, _super);
19717     function MergeScanSubscriber(destination, accumulator, acc, concurrent) {
19718         var _this = _super.call(this, destination) || this;
19719         _this.accumulator = accumulator;
19720         _this.acc = acc;
19721         _this.concurrent = concurrent;
19722         _this.hasValue = false;
19723         _this.hasCompleted = false;
19724         _this.buffer = [];
19725         _this.active = 0;
19726         _this.index = 0;
19727         return _this;
19728     }
19729     MergeScanSubscriber.prototype._next = function (value) {
19730         if (this.active < this.concurrent) {
19731             var index = this.index++;
19732             var ish = tryCatch_1.tryCatch(this.accumulator)(this.acc, value);
19733             var destination = this.destination;
19734             if (ish === errorObject_1.errorObject) {
19735                 destination.error(errorObject_1.errorObject.e);
19736             }
19737             else {
19738                 this.active++;
19739                 this._innerSub(ish, value, index);
19740             }
19741         }
19742         else {
19743             this.buffer.push(value);
19744         }
19745     };
19746     MergeScanSubscriber.prototype._innerSub = function (ish, value, index) {
19747         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
19748         var destination = this.destination;
19749         destination.add(innerSubscriber);
19750         subscribeToResult_1.subscribeToResult(this, ish, value, index, innerSubscriber);
19751     };
19752     MergeScanSubscriber.prototype._complete = function () {
19753         this.hasCompleted = true;
19754         if (this.active === 0 && this.buffer.length === 0) {
19755             if (this.hasValue === false) {
19756                 this.destination.next(this.acc);
19757             }
19758             this.destination.complete();
19759         }
19760         this.unsubscribe();
19761     };
19762     MergeScanSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
19763         var destination = this.destination;
19764         this.acc = innerValue;
19765         this.hasValue = true;
19766         destination.next(innerValue);
19767     };
19768     MergeScanSubscriber.prototype.notifyComplete = function (innerSub) {
19769         var buffer = this.buffer;
19770         var destination = this.destination;
19771         destination.remove(innerSub);
19772         this.active--;
19773         if (buffer.length > 0) {
19774             this._next(buffer.shift());
19775         }
19776         else if (this.active === 0 && this.hasCompleted) {
19777             if (this.hasValue === false) {
19778                 this.destination.next(this.acc);
19779             }
19780             this.destination.complete();
19781         }
19782     };
19783     return MergeScanSubscriber;
19784 }(OuterSubscriber_1.OuterSubscriber));
19785 exports.MergeScanSubscriber = MergeScanSubscriber;
19786
19787 },{"../InnerSubscriber":46,"../OuterSubscriber":50,"../util/errorObject":216,"../util/subscribeToResult":238,"../util/tryCatch":240}],137:[function(require,module,exports){
19788 "use strict";
19789 Object.defineProperty(exports, "__esModule", { value: true });
19790 var reduce_1 = require("./reduce");
19791 function min(comparer) {
19792     var min = (typeof comparer === 'function')
19793         ? function (x, y) { return comparer(x, y) < 0 ? x : y; }
19794         : function (x, y) { return x < y ? x : y; };
19795     return reduce_1.reduce(min);
19796 }
19797 exports.min = min;
19798
19799 },{"./reduce":149}],138:[function(require,module,exports){
19800 "use strict";
19801 Object.defineProperty(exports, "__esModule", { value: true });
19802 var ConnectableObservable_1 = require("../observable/ConnectableObservable");
19803 function multicast(subjectOrSubjectFactory, selector) {
19804     return function multicastOperatorFunction(source) {
19805         var subjectFactory;
19806         if (typeof subjectOrSubjectFactory === 'function') {
19807             subjectFactory = subjectOrSubjectFactory;
19808         }
19809         else {
19810             subjectFactory = function subjectFactory() {
19811                 return subjectOrSubjectFactory;
19812             };
19813         }
19814         if (typeof selector === 'function') {
19815             return source.lift(new MulticastOperator(subjectFactory, selector));
19816         }
19817         var connectable = Object.create(source, ConnectableObservable_1.connectableObservableDescriptor);
19818         connectable.source = source;
19819         connectable.subjectFactory = subjectFactory;
19820         return connectable;
19821     };
19822 }
19823 exports.multicast = multicast;
19824 var MulticastOperator = (function () {
19825     function MulticastOperator(subjectFactory, selector) {
19826         this.subjectFactory = subjectFactory;
19827         this.selector = selector;
19828     }
19829     MulticastOperator.prototype.call = function (subscriber, source) {
19830         var selector = this.selector;
19831         var subject = this.subjectFactory();
19832         var subscription = selector(subject).subscribe(subscriber);
19833         subscription.add(source.subscribe(subject));
19834         return subscription;
19835     };
19836     return MulticastOperator;
19837 }());
19838 exports.MulticastOperator = MulticastOperator;
19839
19840 },{"../observable/ConnectableObservable":58}],139:[function(require,module,exports){
19841 "use strict";
19842 var __extends = (this && this.__extends) || (function () {
19843     var extendStatics = function (d, b) {
19844         extendStatics = Object.setPrototypeOf ||
19845             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19846             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19847         return extendStatics(d, b);
19848     }
19849     return function (d, b) {
19850         extendStatics(d, b);
19851         function __() { this.constructor = d; }
19852         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19853     };
19854 })();
19855 Object.defineProperty(exports, "__esModule", { value: true });
19856 var Subscriber_1 = require("../Subscriber");
19857 var Notification_1 = require("../Notification");
19858 function observeOn(scheduler, delay) {
19859     if (delay === void 0) { delay = 0; }
19860     return function observeOnOperatorFunction(source) {
19861         return source.lift(new ObserveOnOperator(scheduler, delay));
19862     };
19863 }
19864 exports.observeOn = observeOn;
19865 var ObserveOnOperator = (function () {
19866     function ObserveOnOperator(scheduler, delay) {
19867         if (delay === void 0) { delay = 0; }
19868         this.scheduler = scheduler;
19869         this.delay = delay;
19870     }
19871     ObserveOnOperator.prototype.call = function (subscriber, source) {
19872         return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
19873     };
19874     return ObserveOnOperator;
19875 }());
19876 exports.ObserveOnOperator = ObserveOnOperator;
19877 var ObserveOnSubscriber = (function (_super) {
19878     __extends(ObserveOnSubscriber, _super);
19879     function ObserveOnSubscriber(destination, scheduler, delay) {
19880         if (delay === void 0) { delay = 0; }
19881         var _this = _super.call(this, destination) || this;
19882         _this.scheduler = scheduler;
19883         _this.delay = delay;
19884         return _this;
19885     }
19886     ObserveOnSubscriber.dispatch = function (arg) {
19887         var notification = arg.notification, destination = arg.destination;
19888         notification.observe(destination);
19889         this.unsubscribe();
19890     };
19891     ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
19892         var destination = this.destination;
19893         destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
19894     };
19895     ObserveOnSubscriber.prototype._next = function (value) {
19896         this.scheduleMessage(Notification_1.Notification.createNext(value));
19897     };
19898     ObserveOnSubscriber.prototype._error = function (err) {
19899         this.scheduleMessage(Notification_1.Notification.createError(err));
19900         this.unsubscribe();
19901     };
19902     ObserveOnSubscriber.prototype._complete = function () {
19903         this.scheduleMessage(Notification_1.Notification.createComplete());
19904         this.unsubscribe();
19905     };
19906     return ObserveOnSubscriber;
19907 }(Subscriber_1.Subscriber));
19908 exports.ObserveOnSubscriber = ObserveOnSubscriber;
19909 var ObserveOnMessage = (function () {
19910     function ObserveOnMessage(notification, destination) {
19911         this.notification = notification;
19912         this.destination = destination;
19913     }
19914     return ObserveOnMessage;
19915 }());
19916 exports.ObserveOnMessage = ObserveOnMessage;
19917
19918 },{"../Notification":47,"../Subscriber":55}],140:[function(require,module,exports){
19919 "use strict";
19920 var __extends = (this && this.__extends) || (function () {
19921     var extendStatics = function (d, b) {
19922         extendStatics = Object.setPrototypeOf ||
19923             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19924             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19925         return extendStatics(d, b);
19926     }
19927     return function (d, b) {
19928         extendStatics(d, b);
19929         function __() { this.constructor = d; }
19930         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
19931     };
19932 })();
19933 Object.defineProperty(exports, "__esModule", { value: true });
19934 var from_1 = require("../observable/from");
19935 var isArray_1 = require("../util/isArray");
19936 var OuterSubscriber_1 = require("../OuterSubscriber");
19937 var InnerSubscriber_1 = require("../InnerSubscriber");
19938 var subscribeToResult_1 = require("../util/subscribeToResult");
19939 function onErrorResumeNext() {
19940     var nextSources = [];
19941     for (var _i = 0; _i < arguments.length; _i++) {
19942         nextSources[_i] = arguments[_i];
19943     }
19944     if (nextSources.length === 1 && isArray_1.isArray(nextSources[0])) {
19945         nextSources = nextSources[0];
19946     }
19947     return function (source) { return source.lift(new OnErrorResumeNextOperator(nextSources)); };
19948 }
19949 exports.onErrorResumeNext = onErrorResumeNext;
19950 function onErrorResumeNextStatic() {
19951     var nextSources = [];
19952     for (var _i = 0; _i < arguments.length; _i++) {
19953         nextSources[_i] = arguments[_i];
19954     }
19955     var source = null;
19956     if (nextSources.length === 1 && isArray_1.isArray(nextSources[0])) {
19957         nextSources = nextSources[0];
19958     }
19959     source = nextSources.shift();
19960     return from_1.from(source, null).lift(new OnErrorResumeNextOperator(nextSources));
19961 }
19962 exports.onErrorResumeNextStatic = onErrorResumeNextStatic;
19963 var OnErrorResumeNextOperator = (function () {
19964     function OnErrorResumeNextOperator(nextSources) {
19965         this.nextSources = nextSources;
19966     }
19967     OnErrorResumeNextOperator.prototype.call = function (subscriber, source) {
19968         return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources));
19969     };
19970     return OnErrorResumeNextOperator;
19971 }());
19972 var OnErrorResumeNextSubscriber = (function (_super) {
19973     __extends(OnErrorResumeNextSubscriber, _super);
19974     function OnErrorResumeNextSubscriber(destination, nextSources) {
19975         var _this = _super.call(this, destination) || this;
19976         _this.destination = destination;
19977         _this.nextSources = nextSources;
19978         return _this;
19979     }
19980     OnErrorResumeNextSubscriber.prototype.notifyError = function (error, innerSub) {
19981         this.subscribeToNextSource();
19982     };
19983     OnErrorResumeNextSubscriber.prototype.notifyComplete = function (innerSub) {
19984         this.subscribeToNextSource();
19985     };
19986     OnErrorResumeNextSubscriber.prototype._error = function (err) {
19987         this.subscribeToNextSource();
19988         this.unsubscribe();
19989     };
19990     OnErrorResumeNextSubscriber.prototype._complete = function () {
19991         this.subscribeToNextSource();
19992         this.unsubscribe();
19993     };
19994     OnErrorResumeNextSubscriber.prototype.subscribeToNextSource = function () {
19995         var next = this.nextSources.shift();
19996         if (next) {
19997             var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
19998             var destination = this.destination;
19999             destination.add(innerSubscriber);
20000             subscribeToResult_1.subscribeToResult(this, next, undefined, undefined, innerSubscriber);
20001         }
20002         else {
20003             this.destination.complete();
20004         }
20005     };
20006     return OnErrorResumeNextSubscriber;
20007 }(OuterSubscriber_1.OuterSubscriber));
20008
20009 },{"../InnerSubscriber":46,"../OuterSubscriber":50,"../observable/from":67,"../util/isArray":219,"../util/subscribeToResult":238}],141:[function(require,module,exports){
20010 "use strict";
20011 var __extends = (this && this.__extends) || (function () {
20012     var extendStatics = function (d, b) {
20013         extendStatics = Object.setPrototypeOf ||
20014             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20015             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20016         return extendStatics(d, b);
20017     }
20018     return function (d, b) {
20019         extendStatics(d, b);
20020         function __() { this.constructor = d; }
20021         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20022     };
20023 })();
20024 Object.defineProperty(exports, "__esModule", { value: true });
20025 var Subscriber_1 = require("../Subscriber");
20026 function pairwise() {
20027     return function (source) { return source.lift(new PairwiseOperator()); };
20028 }
20029 exports.pairwise = pairwise;
20030 var PairwiseOperator = (function () {
20031     function PairwiseOperator() {
20032     }
20033     PairwiseOperator.prototype.call = function (subscriber, source) {
20034         return source.subscribe(new PairwiseSubscriber(subscriber));
20035     };
20036     return PairwiseOperator;
20037 }());
20038 var PairwiseSubscriber = (function (_super) {
20039     __extends(PairwiseSubscriber, _super);
20040     function PairwiseSubscriber(destination) {
20041         var _this = _super.call(this, destination) || this;
20042         _this.hasPrev = false;
20043         return _this;
20044     }
20045     PairwiseSubscriber.prototype._next = function (value) {
20046         if (this.hasPrev) {
20047             this.destination.next([this.prev, value]);
20048         }
20049         else {
20050             this.hasPrev = true;
20051         }
20052         this.prev = value;
20053     };
20054     return PairwiseSubscriber;
20055 }(Subscriber_1.Subscriber));
20056
20057 },{"../Subscriber":55}],142:[function(require,module,exports){
20058 "use strict";
20059 Object.defineProperty(exports, "__esModule", { value: true });
20060 var not_1 = require("../util/not");
20061 var filter_1 = require("./filter");
20062 function partition(predicate, thisArg) {
20063     return function (source) { return [
20064         filter_1.filter(predicate, thisArg)(source),
20065         filter_1.filter(not_1.not(predicate, thisArg))(source)
20066     ]; };
20067 }
20068 exports.partition = partition;
20069
20070 },{"../util/not":231,"./filter":119}],143:[function(require,module,exports){
20071 "use strict";
20072 Object.defineProperty(exports, "__esModule", { value: true });
20073 var map_1 = require("./map");
20074 function pluck() {
20075     var properties = [];
20076     for (var _i = 0; _i < arguments.length; _i++) {
20077         properties[_i] = arguments[_i];
20078     }
20079     var length = properties.length;
20080     if (length === 0) {
20081         throw new Error('list of properties cannot be empty.');
20082     }
20083     return function (source) { return map_1.map(plucker(properties, length))(source); };
20084 }
20085 exports.pluck = pluck;
20086 function plucker(props, length) {
20087     var mapper = function (x) {
20088         var currentProp = x;
20089         for (var i = 0; i < length; i++) {
20090             var p = currentProp[props[i]];
20091             if (typeof p !== 'undefined') {
20092                 currentProp = p;
20093             }
20094             else {
20095                 return undefined;
20096             }
20097         }
20098         return currentProp;
20099     };
20100     return mapper;
20101 }
20102
20103 },{"./map":128}],144:[function(require,module,exports){
20104 "use strict";
20105 Object.defineProperty(exports, "__esModule", { value: true });
20106 var Subject_1 = require("../Subject");
20107 var multicast_1 = require("./multicast");
20108 function publish(selector) {
20109     return selector ?
20110         multicast_1.multicast(function () { return new Subject_1.Subject(); }, selector) :
20111         multicast_1.multicast(new Subject_1.Subject());
20112 }
20113 exports.publish = publish;
20114
20115 },{"../Subject":53,"./multicast":138}],145:[function(require,module,exports){
20116 "use strict";
20117 Object.defineProperty(exports, "__esModule", { value: true });
20118 var BehaviorSubject_1 = require("../BehaviorSubject");
20119 var multicast_1 = require("./multicast");
20120 function publishBehavior(value) {
20121     return function (source) { return multicast_1.multicast(new BehaviorSubject_1.BehaviorSubject(value))(source); };
20122 }
20123 exports.publishBehavior = publishBehavior;
20124
20125 },{"../BehaviorSubject":45,"./multicast":138}],146:[function(require,module,exports){
20126 "use strict";
20127 Object.defineProperty(exports, "__esModule", { value: true });
20128 var AsyncSubject_1 = require("../AsyncSubject");
20129 var multicast_1 = require("./multicast");
20130 function publishLast() {
20131     return function (source) { return multicast_1.multicast(new AsyncSubject_1.AsyncSubject())(source); };
20132 }
20133 exports.publishLast = publishLast;
20134
20135 },{"../AsyncSubject":44,"./multicast":138}],147:[function(require,module,exports){
20136 "use strict";
20137 Object.defineProperty(exports, "__esModule", { value: true });
20138 var ReplaySubject_1 = require("../ReplaySubject");
20139 var multicast_1 = require("./multicast");
20140 function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
20141     if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {
20142         scheduler = selectorOrScheduler;
20143     }
20144     var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;
20145     var subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler);
20146     return function (source) { return multicast_1.multicast(function () { return subject; }, selector)(source); };
20147 }
20148 exports.publishReplay = publishReplay;
20149
20150 },{"../ReplaySubject":51,"./multicast":138}],148:[function(require,module,exports){
20151 "use strict";
20152 Object.defineProperty(exports, "__esModule", { value: true });
20153 var isArray_1 = require("../util/isArray");
20154 var race_1 = require("../observable/race");
20155 function race() {
20156     var observables = [];
20157     for (var _i = 0; _i < arguments.length; _i++) {
20158         observables[_i] = arguments[_i];
20159     }
20160     return function raceOperatorFunction(source) {
20161         if (observables.length === 1 && isArray_1.isArray(observables[0])) {
20162             observables = observables[0];
20163         }
20164         return source.lift.call(race_1.race.apply(void 0, [source].concat(observables)));
20165     };
20166 }
20167 exports.race = race;
20168
20169 },{"../observable/race":82,"../util/isArray":219}],149:[function(require,module,exports){
20170 "use strict";
20171 Object.defineProperty(exports, "__esModule", { value: true });
20172 var scan_1 = require("./scan");
20173 var takeLast_1 = require("./takeLast");
20174 var defaultIfEmpty_1 = require("./defaultIfEmpty");
20175 var pipe_1 = require("../util/pipe");
20176 function reduce(accumulator, seed) {
20177     if (arguments.length >= 2) {
20178         return function reduceOperatorFunctionWithSeed(source) {
20179             return pipe_1.pipe(scan_1.scan(accumulator, seed), takeLast_1.takeLast(1), defaultIfEmpty_1.defaultIfEmpty(seed))(source);
20180         };
20181     }
20182     return function reduceOperatorFunction(source) {
20183         return pipe_1.pipe(scan_1.scan(function (acc, value, index) { return accumulator(acc, value, index + 1); }), takeLast_1.takeLast(1))(source);
20184     };
20185 }
20186 exports.reduce = reduce;
20187
20188 },{"../util/pipe":232,"./defaultIfEmpty":106,"./scan":157,"./takeLast":172}],150:[function(require,module,exports){
20189 "use strict";
20190 var __extends = (this && this.__extends) || (function () {
20191     var extendStatics = function (d, b) {
20192         extendStatics = Object.setPrototypeOf ||
20193             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20194             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20195         return extendStatics(d, b);
20196     }
20197     return function (d, b) {
20198         extendStatics(d, b);
20199         function __() { this.constructor = d; }
20200         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20201     };
20202 })();
20203 Object.defineProperty(exports, "__esModule", { value: true });
20204 var Subscriber_1 = require("../Subscriber");
20205 function refCount() {
20206     return function refCountOperatorFunction(source) {
20207         return source.lift(new RefCountOperator(source));
20208     };
20209 }
20210 exports.refCount = refCount;
20211 var RefCountOperator = (function () {
20212     function RefCountOperator(connectable) {
20213         this.connectable = connectable;
20214     }
20215     RefCountOperator.prototype.call = function (subscriber, source) {
20216         var connectable = this.connectable;
20217         connectable._refCount++;
20218         var refCounter = new RefCountSubscriber(subscriber, connectable);
20219         var subscription = source.subscribe(refCounter);
20220         if (!refCounter.closed) {
20221             refCounter.connection = connectable.connect();
20222         }
20223         return subscription;
20224     };
20225     return RefCountOperator;
20226 }());
20227 var RefCountSubscriber = (function (_super) {
20228     __extends(RefCountSubscriber, _super);
20229     function RefCountSubscriber(destination, connectable) {
20230         var _this = _super.call(this, destination) || this;
20231         _this.connectable = connectable;
20232         return _this;
20233     }
20234     RefCountSubscriber.prototype._unsubscribe = function () {
20235         var connectable = this.connectable;
20236         if (!connectable) {
20237             this.connection = null;
20238             return;
20239         }
20240         this.connectable = null;
20241         var refCount = connectable._refCount;
20242         if (refCount <= 0) {
20243             this.connection = null;
20244             return;
20245         }
20246         connectable._refCount = refCount - 1;
20247         if (refCount > 1) {
20248             this.connection = null;
20249             return;
20250         }
20251         var connection = this.connection;
20252         var sharedConnection = connectable._connection;
20253         this.connection = null;
20254         if (sharedConnection && (!connection || sharedConnection === connection)) {
20255             sharedConnection.unsubscribe();
20256         }
20257     };
20258     return RefCountSubscriber;
20259 }(Subscriber_1.Subscriber));
20260
20261 },{"../Subscriber":55}],151:[function(require,module,exports){
20262 "use strict";
20263 var __extends = (this && this.__extends) || (function () {
20264     var extendStatics = function (d, b) {
20265         extendStatics = Object.setPrototypeOf ||
20266             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20267             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20268         return extendStatics(d, b);
20269     }
20270     return function (d, b) {
20271         extendStatics(d, b);
20272         function __() { this.constructor = d; }
20273         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20274     };
20275 })();
20276 Object.defineProperty(exports, "__esModule", { value: true });
20277 var Subscriber_1 = require("../Subscriber");
20278 var empty_1 = require("../observable/empty");
20279 function repeat(count) {
20280     if (count === void 0) { count = -1; }
20281     return function (source) {
20282         if (count === 0) {
20283             return empty_1.empty();
20284         }
20285         else if (count < 0) {
20286             return source.lift(new RepeatOperator(-1, source));
20287         }
20288         else {
20289             return source.lift(new RepeatOperator(count - 1, source));
20290         }
20291     };
20292 }
20293 exports.repeat = repeat;
20294 var RepeatOperator = (function () {
20295     function RepeatOperator(count, source) {
20296         this.count = count;
20297         this.source = source;
20298     }
20299     RepeatOperator.prototype.call = function (subscriber, source) {
20300         return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source));
20301     };
20302     return RepeatOperator;
20303 }());
20304 var RepeatSubscriber = (function (_super) {
20305     __extends(RepeatSubscriber, _super);
20306     function RepeatSubscriber(destination, count, source) {
20307         var _this = _super.call(this, destination) || this;
20308         _this.count = count;
20309         _this.source = source;
20310         return _this;
20311     }
20312     RepeatSubscriber.prototype.complete = function () {
20313         if (!this.isStopped) {
20314             var _a = this, source = _a.source, count = _a.count;
20315             if (count === 0) {
20316                 return _super.prototype.complete.call(this);
20317             }
20318             else if (count > -1) {
20319                 this.count = count - 1;
20320             }
20321             source.subscribe(this._unsubscribeAndRecycle());
20322         }
20323     };
20324     return RepeatSubscriber;
20325 }(Subscriber_1.Subscriber));
20326
20327 },{"../Subscriber":55,"../observable/empty":65}],152:[function(require,module,exports){
20328 "use strict";
20329 var __extends = (this && this.__extends) || (function () {
20330     var extendStatics = function (d, b) {
20331         extendStatics = Object.setPrototypeOf ||
20332             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20333             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20334         return extendStatics(d, b);
20335     }
20336     return function (d, b) {
20337         extendStatics(d, b);
20338         function __() { this.constructor = d; }
20339         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20340     };
20341 })();
20342 Object.defineProperty(exports, "__esModule", { value: true });
20343 var Subject_1 = require("../Subject");
20344 var tryCatch_1 = require("../util/tryCatch");
20345 var errorObject_1 = require("../util/errorObject");
20346 var OuterSubscriber_1 = require("../OuterSubscriber");
20347 var subscribeToResult_1 = require("../util/subscribeToResult");
20348 function repeatWhen(notifier) {
20349     return function (source) { return source.lift(new RepeatWhenOperator(notifier)); };
20350 }
20351 exports.repeatWhen = repeatWhen;
20352 var RepeatWhenOperator = (function () {
20353     function RepeatWhenOperator(notifier) {
20354         this.notifier = notifier;
20355     }
20356     RepeatWhenOperator.prototype.call = function (subscriber, source) {
20357         return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source));
20358     };
20359     return RepeatWhenOperator;
20360 }());
20361 var RepeatWhenSubscriber = (function (_super) {
20362     __extends(RepeatWhenSubscriber, _super);
20363     function RepeatWhenSubscriber(destination, notifier, source) {
20364         var _this = _super.call(this, destination) || this;
20365         _this.notifier = notifier;
20366         _this.source = source;
20367         _this.sourceIsBeingSubscribedTo = true;
20368         return _this;
20369     }
20370     RepeatWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
20371         this.sourceIsBeingSubscribedTo = true;
20372         this.source.subscribe(this);
20373     };
20374     RepeatWhenSubscriber.prototype.notifyComplete = function (innerSub) {
20375         if (this.sourceIsBeingSubscribedTo === false) {
20376             return _super.prototype.complete.call(this);
20377         }
20378     };
20379     RepeatWhenSubscriber.prototype.complete = function () {
20380         this.sourceIsBeingSubscribedTo = false;
20381         if (!this.isStopped) {
20382             if (!this.retries) {
20383                 this.subscribeToRetries();
20384             }
20385             if (!this.retriesSubscription || this.retriesSubscription.closed) {
20386                 return _super.prototype.complete.call(this);
20387             }
20388             this._unsubscribeAndRecycle();
20389             this.notifications.next();
20390         }
20391     };
20392     RepeatWhenSubscriber.prototype._unsubscribe = function () {
20393         var _a = this, notifications = _a.notifications, retriesSubscription = _a.retriesSubscription;
20394         if (notifications) {
20395             notifications.unsubscribe();
20396             this.notifications = null;
20397         }
20398         if (retriesSubscription) {
20399             retriesSubscription.unsubscribe();
20400             this.retriesSubscription = null;
20401         }
20402         this.retries = null;
20403     };
20404     RepeatWhenSubscriber.prototype._unsubscribeAndRecycle = function () {
20405         var _unsubscribe = this._unsubscribe;
20406         this._unsubscribe = null;
20407         _super.prototype._unsubscribeAndRecycle.call(this);
20408         this._unsubscribe = _unsubscribe;
20409         return this;
20410     };
20411     RepeatWhenSubscriber.prototype.subscribeToRetries = function () {
20412         this.notifications = new Subject_1.Subject();
20413         var retries = tryCatch_1.tryCatch(this.notifier)(this.notifications);
20414         if (retries === errorObject_1.errorObject) {
20415             return _super.prototype.complete.call(this);
20416         }
20417         this.retries = retries;
20418         this.retriesSubscription = subscribeToResult_1.subscribeToResult(this, retries);
20419     };
20420     return RepeatWhenSubscriber;
20421 }(OuterSubscriber_1.OuterSubscriber));
20422
20423 },{"../OuterSubscriber":50,"../Subject":53,"../util/errorObject":216,"../util/subscribeToResult":238,"../util/tryCatch":240}],153:[function(require,module,exports){
20424 "use strict";
20425 var __extends = (this && this.__extends) || (function () {
20426     var extendStatics = function (d, b) {
20427         extendStatics = Object.setPrototypeOf ||
20428             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20429             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20430         return extendStatics(d, b);
20431     }
20432     return function (d, b) {
20433         extendStatics(d, b);
20434         function __() { this.constructor = d; }
20435         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20436     };
20437 })();
20438 Object.defineProperty(exports, "__esModule", { value: true });
20439 var Subscriber_1 = require("../Subscriber");
20440 function retry(count) {
20441     if (count === void 0) { count = -1; }
20442     return function (source) { return source.lift(new RetryOperator(count, source)); };
20443 }
20444 exports.retry = retry;
20445 var RetryOperator = (function () {
20446     function RetryOperator(count, source) {
20447         this.count = count;
20448         this.source = source;
20449     }
20450     RetryOperator.prototype.call = function (subscriber, source) {
20451         return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
20452     };
20453     return RetryOperator;
20454 }());
20455 var RetrySubscriber = (function (_super) {
20456     __extends(RetrySubscriber, _super);
20457     function RetrySubscriber(destination, count, source) {
20458         var _this = _super.call(this, destination) || this;
20459         _this.count = count;
20460         _this.source = source;
20461         return _this;
20462     }
20463     RetrySubscriber.prototype.error = function (err) {
20464         if (!this.isStopped) {
20465             var _a = this, source = _a.source, count = _a.count;
20466             if (count === 0) {
20467                 return _super.prototype.error.call(this, err);
20468             }
20469             else if (count > -1) {
20470                 this.count = count - 1;
20471             }
20472             source.subscribe(this._unsubscribeAndRecycle());
20473         }
20474     };
20475     return RetrySubscriber;
20476 }(Subscriber_1.Subscriber));
20477
20478 },{"../Subscriber":55}],154:[function(require,module,exports){
20479 "use strict";
20480 var __extends = (this && this.__extends) || (function () {
20481     var extendStatics = function (d, b) {
20482         extendStatics = Object.setPrototypeOf ||
20483             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20484             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20485         return extendStatics(d, b);
20486     }
20487     return function (d, b) {
20488         extendStatics(d, b);
20489         function __() { this.constructor = d; }
20490         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20491     };
20492 })();
20493 Object.defineProperty(exports, "__esModule", { value: true });
20494 var Subject_1 = require("../Subject");
20495 var tryCatch_1 = require("../util/tryCatch");
20496 var errorObject_1 = require("../util/errorObject");
20497 var OuterSubscriber_1 = require("../OuterSubscriber");
20498 var subscribeToResult_1 = require("../util/subscribeToResult");
20499 function retryWhen(notifier) {
20500     return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); };
20501 }
20502 exports.retryWhen = retryWhen;
20503 var RetryWhenOperator = (function () {
20504     function RetryWhenOperator(notifier, source) {
20505         this.notifier = notifier;
20506         this.source = source;
20507     }
20508     RetryWhenOperator.prototype.call = function (subscriber, source) {
20509         return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));
20510     };
20511     return RetryWhenOperator;
20512 }());
20513 var RetryWhenSubscriber = (function (_super) {
20514     __extends(RetryWhenSubscriber, _super);
20515     function RetryWhenSubscriber(destination, notifier, source) {
20516         var _this = _super.call(this, destination) || this;
20517         _this.notifier = notifier;
20518         _this.source = source;
20519         return _this;
20520     }
20521     RetryWhenSubscriber.prototype.error = function (err) {
20522         if (!this.isStopped) {
20523             var errors = this.errors;
20524             var retries = this.retries;
20525             var retriesSubscription = this.retriesSubscription;
20526             if (!retries) {
20527                 errors = new Subject_1.Subject();
20528                 retries = tryCatch_1.tryCatch(this.notifier)(errors);
20529                 if (retries === errorObject_1.errorObject) {
20530                     return _super.prototype.error.call(this, errorObject_1.errorObject.e);
20531                 }
20532                 retriesSubscription = subscribeToResult_1.subscribeToResult(this, retries);
20533             }
20534             else {
20535                 this.errors = null;
20536                 this.retriesSubscription = null;
20537             }
20538             this._unsubscribeAndRecycle();
20539             this.errors = errors;
20540             this.retries = retries;
20541             this.retriesSubscription = retriesSubscription;
20542             errors.next(err);
20543         }
20544     };
20545     RetryWhenSubscriber.prototype._unsubscribe = function () {
20546         var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription;
20547         if (errors) {
20548             errors.unsubscribe();
20549             this.errors = null;
20550         }
20551         if (retriesSubscription) {
20552             retriesSubscription.unsubscribe();
20553             this.retriesSubscription = null;
20554         }
20555         this.retries = null;
20556     };
20557     RetryWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
20558         var _unsubscribe = this._unsubscribe;
20559         this._unsubscribe = null;
20560         this._unsubscribeAndRecycle();
20561         this._unsubscribe = _unsubscribe;
20562         this.source.subscribe(this);
20563     };
20564     return RetryWhenSubscriber;
20565 }(OuterSubscriber_1.OuterSubscriber));
20566
20567 },{"../OuterSubscriber":50,"../Subject":53,"../util/errorObject":216,"../util/subscribeToResult":238,"../util/tryCatch":240}],155:[function(require,module,exports){
20568 "use strict";
20569 var __extends = (this && this.__extends) || (function () {
20570     var extendStatics = function (d, b) {
20571         extendStatics = Object.setPrototypeOf ||
20572             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20573             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20574         return extendStatics(d, b);
20575     }
20576     return function (d, b) {
20577         extendStatics(d, b);
20578         function __() { this.constructor = d; }
20579         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20580     };
20581 })();
20582 Object.defineProperty(exports, "__esModule", { value: true });
20583 var OuterSubscriber_1 = require("../OuterSubscriber");
20584 var subscribeToResult_1 = require("../util/subscribeToResult");
20585 function sample(notifier) {
20586     return function (source) { return source.lift(new SampleOperator(notifier)); };
20587 }
20588 exports.sample = sample;
20589 var SampleOperator = (function () {
20590     function SampleOperator(notifier) {
20591         this.notifier = notifier;
20592     }
20593     SampleOperator.prototype.call = function (subscriber, source) {
20594         var sampleSubscriber = new SampleSubscriber(subscriber);
20595         var subscription = source.subscribe(sampleSubscriber);
20596         subscription.add(subscribeToResult_1.subscribeToResult(sampleSubscriber, this.notifier));
20597         return subscription;
20598     };
20599     return SampleOperator;
20600 }());
20601 var SampleSubscriber = (function (_super) {
20602     __extends(SampleSubscriber, _super);
20603     function SampleSubscriber() {
20604         var _this = _super !== null && _super.apply(this, arguments) || this;
20605         _this.hasValue = false;
20606         return _this;
20607     }
20608     SampleSubscriber.prototype._next = function (value) {
20609         this.value = value;
20610         this.hasValue = true;
20611     };
20612     SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
20613         this.emitValue();
20614     };
20615     SampleSubscriber.prototype.notifyComplete = function () {
20616         this.emitValue();
20617     };
20618     SampleSubscriber.prototype.emitValue = function () {
20619         if (this.hasValue) {
20620             this.hasValue = false;
20621             this.destination.next(this.value);
20622         }
20623     };
20624     return SampleSubscriber;
20625 }(OuterSubscriber_1.OuterSubscriber));
20626
20627 },{"../OuterSubscriber":50,"../util/subscribeToResult":238}],156:[function(require,module,exports){
20628 "use strict";
20629 var __extends = (this && this.__extends) || (function () {
20630     var extendStatics = function (d, b) {
20631         extendStatics = Object.setPrototypeOf ||
20632             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20633             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20634         return extendStatics(d, b);
20635     }
20636     return function (d, b) {
20637         extendStatics(d, b);
20638         function __() { this.constructor = d; }
20639         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20640     };
20641 })();
20642 Object.defineProperty(exports, "__esModule", { value: true });
20643 var Subscriber_1 = require("../Subscriber");
20644 var async_1 = require("../scheduler/async");
20645 function sampleTime(period, scheduler) {
20646     if (scheduler === void 0) { scheduler = async_1.async; }
20647     return function (source) { return source.lift(new SampleTimeOperator(period, scheduler)); };
20648 }
20649 exports.sampleTime = sampleTime;
20650 var SampleTimeOperator = (function () {
20651     function SampleTimeOperator(period, scheduler) {
20652         this.period = period;
20653         this.scheduler = scheduler;
20654     }
20655     SampleTimeOperator.prototype.call = function (subscriber, source) {
20656         return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler));
20657     };
20658     return SampleTimeOperator;
20659 }());
20660 var SampleTimeSubscriber = (function (_super) {
20661     __extends(SampleTimeSubscriber, _super);
20662     function SampleTimeSubscriber(destination, period, scheduler) {
20663         var _this = _super.call(this, destination) || this;
20664         _this.period = period;
20665         _this.scheduler = scheduler;
20666         _this.hasValue = false;
20667         _this.add(scheduler.schedule(dispatchNotification, period, { subscriber: _this, period: period }));
20668         return _this;
20669     }
20670     SampleTimeSubscriber.prototype._next = function (value) {
20671         this.lastValue = value;
20672         this.hasValue = true;
20673     };
20674     SampleTimeSubscriber.prototype.notifyNext = function () {
20675         if (this.hasValue) {
20676             this.hasValue = false;
20677             this.destination.next(this.lastValue);
20678         }
20679     };
20680     return SampleTimeSubscriber;
20681 }(Subscriber_1.Subscriber));
20682 function dispatchNotification(state) {
20683     var subscriber = state.subscriber, period = state.period;
20684     subscriber.notifyNext();
20685     this.schedule(state, period);
20686 }
20687
20688 },{"../Subscriber":55,"../scheduler/async":204}],157:[function(require,module,exports){
20689 "use strict";
20690 var __extends = (this && this.__extends) || (function () {
20691     var extendStatics = function (d, b) {
20692         extendStatics = Object.setPrototypeOf ||
20693             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20694             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20695         return extendStatics(d, b);
20696     }
20697     return function (d, b) {
20698         extendStatics(d, b);
20699         function __() { this.constructor = d; }
20700         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20701     };
20702 })();
20703 Object.defineProperty(exports, "__esModule", { value: true });
20704 var Subscriber_1 = require("../Subscriber");
20705 function scan(accumulator, seed) {
20706     var hasSeed = false;
20707     if (arguments.length >= 2) {
20708         hasSeed = true;
20709     }
20710     return function scanOperatorFunction(source) {
20711         return source.lift(new ScanOperator(accumulator, seed, hasSeed));
20712     };
20713 }
20714 exports.scan = scan;
20715 var ScanOperator = (function () {
20716     function ScanOperator(accumulator, seed, hasSeed) {
20717         if (hasSeed === void 0) { hasSeed = false; }
20718         this.accumulator = accumulator;
20719         this.seed = seed;
20720         this.hasSeed = hasSeed;
20721     }
20722     ScanOperator.prototype.call = function (subscriber, source) {
20723         return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
20724     };
20725     return ScanOperator;
20726 }());
20727 var ScanSubscriber = (function (_super) {
20728     __extends(ScanSubscriber, _super);
20729     function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
20730         var _this = _super.call(this, destination) || this;
20731         _this.accumulator = accumulator;
20732         _this._seed = _seed;
20733         _this.hasSeed = hasSeed;
20734         _this.index = 0;
20735         return _this;
20736     }
20737     Object.defineProperty(ScanSubscriber.prototype, "seed", {
20738         get: function () {
20739             return this._seed;
20740         },
20741         set: function (value) {
20742             this.hasSeed = true;
20743             this._seed = value;
20744         },
20745         enumerable: true,
20746         configurable: true
20747     });
20748     ScanSubscriber.prototype._next = function (value) {
20749         if (!this.hasSeed) {
20750             this.seed = value;
20751             this.destination.next(value);
20752         }
20753         else {
20754             return this._tryNext(value);
20755         }
20756     };
20757     ScanSubscriber.prototype._tryNext = function (value) {
20758         var index = this.index++;
20759         var result;
20760         try {
20761             result = this.accumulator(this.seed, value, index);
20762         }
20763         catch (err) {
20764             this.destination.error(err);
20765         }
20766         this.seed = result;
20767         this.destination.next(result);
20768     };
20769     return ScanSubscriber;
20770 }(Subscriber_1.Subscriber));
20771
20772 },{"../Subscriber":55}],158:[function(require,module,exports){
20773 "use strict";
20774 var __extends = (this && this.__extends) || (function () {
20775     var extendStatics = function (d, b) {
20776         extendStatics = Object.setPrototypeOf ||
20777             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20778             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20779         return extendStatics(d, b);
20780     }
20781     return function (d, b) {
20782         extendStatics(d, b);
20783         function __() { this.constructor = d; }
20784         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20785     };
20786 })();
20787 Object.defineProperty(exports, "__esModule", { value: true });
20788 var Subscriber_1 = require("../Subscriber");
20789 var tryCatch_1 = require("../util/tryCatch");
20790 var errorObject_1 = require("../util/errorObject");
20791 function sequenceEqual(compareTo, comparor) {
20792     return function (source) { return source.lift(new SequenceEqualOperator(compareTo, comparor)); };
20793 }
20794 exports.sequenceEqual = sequenceEqual;
20795 var SequenceEqualOperator = (function () {
20796     function SequenceEqualOperator(compareTo, comparor) {
20797         this.compareTo = compareTo;
20798         this.comparor = comparor;
20799     }
20800     SequenceEqualOperator.prototype.call = function (subscriber, source) {
20801         return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparor));
20802     };
20803     return SequenceEqualOperator;
20804 }());
20805 exports.SequenceEqualOperator = SequenceEqualOperator;
20806 var SequenceEqualSubscriber = (function (_super) {
20807     __extends(SequenceEqualSubscriber, _super);
20808     function SequenceEqualSubscriber(destination, compareTo, comparor) {
20809         var _this = _super.call(this, destination) || this;
20810         _this.compareTo = compareTo;
20811         _this.comparor = comparor;
20812         _this._a = [];
20813         _this._b = [];
20814         _this._oneComplete = false;
20815         _this.destination.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, _this)));
20816         return _this;
20817     }
20818     SequenceEqualSubscriber.prototype._next = function (value) {
20819         if (this._oneComplete && this._b.length === 0) {
20820             this.emit(false);
20821         }
20822         else {
20823             this._a.push(value);
20824             this.checkValues();
20825         }
20826     };
20827     SequenceEqualSubscriber.prototype._complete = function () {
20828         if (this._oneComplete) {
20829             this.emit(this._a.length === 0 && this._b.length === 0);
20830         }
20831         else {
20832             this._oneComplete = true;
20833         }
20834         this.unsubscribe();
20835     };
20836     SequenceEqualSubscriber.prototype.checkValues = function () {
20837         var _c = this, _a = _c._a, _b = _c._b, comparor = _c.comparor;
20838         while (_a.length > 0 && _b.length > 0) {
20839             var a = _a.shift();
20840             var b = _b.shift();
20841             var areEqual = false;
20842             if (comparor) {
20843                 areEqual = tryCatch_1.tryCatch(comparor)(a, b);
20844                 if (areEqual === errorObject_1.errorObject) {
20845                     this.destination.error(errorObject_1.errorObject.e);
20846                 }
20847             }
20848             else {
20849                 areEqual = a === b;
20850             }
20851             if (!areEqual) {
20852                 this.emit(false);
20853             }
20854         }
20855     };
20856     SequenceEqualSubscriber.prototype.emit = function (value) {
20857         var destination = this.destination;
20858         destination.next(value);
20859         destination.complete();
20860     };
20861     SequenceEqualSubscriber.prototype.nextB = function (value) {
20862         if (this._oneComplete && this._a.length === 0) {
20863             this.emit(false);
20864         }
20865         else {
20866             this._b.push(value);
20867             this.checkValues();
20868         }
20869     };
20870     SequenceEqualSubscriber.prototype.completeB = function () {
20871         if (this._oneComplete) {
20872             this.emit(this._a.length === 0 && this._b.length === 0);
20873         }
20874         else {
20875             this._oneComplete = true;
20876         }
20877     };
20878     return SequenceEqualSubscriber;
20879 }(Subscriber_1.Subscriber));
20880 exports.SequenceEqualSubscriber = SequenceEqualSubscriber;
20881 var SequenceEqualCompareToSubscriber = (function (_super) {
20882     __extends(SequenceEqualCompareToSubscriber, _super);
20883     function SequenceEqualCompareToSubscriber(destination, parent) {
20884         var _this = _super.call(this, destination) || this;
20885         _this.parent = parent;
20886         return _this;
20887     }
20888     SequenceEqualCompareToSubscriber.prototype._next = function (value) {
20889         this.parent.nextB(value);
20890     };
20891     SequenceEqualCompareToSubscriber.prototype._error = function (err) {
20892         this.parent.error(err);
20893         this.unsubscribe();
20894     };
20895     SequenceEqualCompareToSubscriber.prototype._complete = function () {
20896         this.parent.completeB();
20897         this.unsubscribe();
20898     };
20899     return SequenceEqualCompareToSubscriber;
20900 }(Subscriber_1.Subscriber));
20901
20902 },{"../Subscriber":55,"../util/errorObject":216,"../util/tryCatch":240}],159:[function(require,module,exports){
20903 "use strict";
20904 Object.defineProperty(exports, "__esModule", { value: true });
20905 var multicast_1 = require("./multicast");
20906 var refCount_1 = require("./refCount");
20907 var Subject_1 = require("../Subject");
20908 function shareSubjectFactory() {
20909     return new Subject_1.Subject();
20910 }
20911 function share() {
20912     return function (source) { return refCount_1.refCount()(multicast_1.multicast(shareSubjectFactory)(source)); };
20913 }
20914 exports.share = share;
20915
20916 },{"../Subject":53,"./multicast":138,"./refCount":150}],160:[function(require,module,exports){
20917 "use strict";
20918 Object.defineProperty(exports, "__esModule", { value: true });
20919 var ReplaySubject_1 = require("../ReplaySubject");
20920 function shareReplay(bufferSize, windowTime, scheduler) {
20921     if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
20922     if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
20923     return function (source) { return source.lift(shareReplayOperator(bufferSize, windowTime, scheduler)); };
20924 }
20925 exports.shareReplay = shareReplay;
20926 function shareReplayOperator(bufferSize, windowTime, scheduler) {
20927     var subject;
20928     var refCount = 0;
20929     var subscription;
20930     var hasError = false;
20931     var isComplete = false;
20932     return function shareReplayOperation(source) {
20933         refCount++;
20934         if (!subject || hasError) {
20935             hasError = false;
20936             subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler);
20937             subscription = source.subscribe({
20938                 next: function (value) { subject.next(value); },
20939                 error: function (err) {
20940                     hasError = true;
20941                     subject.error(err);
20942                 },
20943                 complete: function () {
20944                     isComplete = true;
20945                     subject.complete();
20946                 },
20947             });
20948         }
20949         var innerSub = subject.subscribe(this);
20950         return function () {
20951             refCount--;
20952             innerSub.unsubscribe();
20953             if (subscription && refCount === 0 && isComplete) {
20954                 subscription.unsubscribe();
20955             }
20956         };
20957     };
20958 }
20959
20960 },{"../ReplaySubject":51}],161:[function(require,module,exports){
20961 "use strict";
20962 var __extends = (this && this.__extends) || (function () {
20963     var extendStatics = function (d, b) {
20964         extendStatics = Object.setPrototypeOf ||
20965             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20966             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20967         return extendStatics(d, b);
20968     }
20969     return function (d, b) {
20970         extendStatics(d, b);
20971         function __() { this.constructor = d; }
20972         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20973     };
20974 })();
20975 Object.defineProperty(exports, "__esModule", { value: true });
20976 var Subscriber_1 = require("../Subscriber");
20977 var EmptyError_1 = require("../util/EmptyError");
20978 function single(predicate) {
20979     return function (source) { return source.lift(new SingleOperator(predicate, source)); };
20980 }
20981 exports.single = single;
20982 var SingleOperator = (function () {
20983     function SingleOperator(predicate, source) {
20984         this.predicate = predicate;
20985         this.source = source;
20986     }
20987     SingleOperator.prototype.call = function (subscriber, source) {
20988         return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source));
20989     };
20990     return SingleOperator;
20991 }());
20992 var SingleSubscriber = (function (_super) {
20993     __extends(SingleSubscriber, _super);
20994     function SingleSubscriber(destination, predicate, source) {
20995         var _this = _super.call(this, destination) || this;
20996         _this.predicate = predicate;
20997         _this.source = source;
20998         _this.seenValue = false;
20999         _this.index = 0;
21000         return _this;
21001     }
21002     SingleSubscriber.prototype.applySingleValue = function (value) {
21003         if (this.seenValue) {
21004             this.destination.error('Sequence contains more than one element');
21005         }
21006         else {
21007             this.seenValue = true;
21008             this.singleValue = value;
21009         }
21010     };
21011     SingleSubscriber.prototype._next = function (value) {
21012         var index = this.index++;
21013         if (this.predicate) {
21014             this.tryNext(value, index);
21015         }
21016         else {
21017             this.applySingleValue(value);
21018         }
21019     };
21020     SingleSubscriber.prototype.tryNext = function (value, index) {
21021         try {
21022             if (this.predicate(value, index, this.source)) {
21023                 this.applySingleValue(value);
21024             }
21025         }
21026         catch (err) {
21027             this.destination.error(err);
21028         }
21029     };
21030     SingleSubscriber.prototype._complete = function () {
21031         var destination = this.destination;
21032         if (this.index > 0) {
21033             destination.next(this.seenValue ? this.singleValue : undefined);
21034             destination.complete();
21035         }
21036         else {
21037             destination.error(new EmptyError_1.EmptyError);
21038         }
21039     };
21040     return SingleSubscriber;
21041 }(Subscriber_1.Subscriber));
21042
21043 },{"../Subscriber":55,"../util/EmptyError":210}],162:[function(require,module,exports){
21044 "use strict";
21045 var __extends = (this && this.__extends) || (function () {
21046     var extendStatics = function (d, b) {
21047         extendStatics = Object.setPrototypeOf ||
21048             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21049             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21050         return extendStatics(d, b);
21051     }
21052     return function (d, b) {
21053         extendStatics(d, b);
21054         function __() { this.constructor = d; }
21055         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21056     };
21057 })();
21058 Object.defineProperty(exports, "__esModule", { value: true });
21059 var Subscriber_1 = require("../Subscriber");
21060 function skip(count) {
21061     return function (source) { return source.lift(new SkipOperator(count)); };
21062 }
21063 exports.skip = skip;
21064 var SkipOperator = (function () {
21065     function SkipOperator(total) {
21066         this.total = total;
21067     }
21068     SkipOperator.prototype.call = function (subscriber, source) {
21069         return source.subscribe(new SkipSubscriber(subscriber, this.total));
21070     };
21071     return SkipOperator;
21072 }());
21073 var SkipSubscriber = (function (_super) {
21074     __extends(SkipSubscriber, _super);
21075     function SkipSubscriber(destination, total) {
21076         var _this = _super.call(this, destination) || this;
21077         _this.total = total;
21078         _this.count = 0;
21079         return _this;
21080     }
21081     SkipSubscriber.prototype._next = function (x) {
21082         if (++this.count > this.total) {
21083             this.destination.next(x);
21084         }
21085     };
21086     return SkipSubscriber;
21087 }(Subscriber_1.Subscriber));
21088
21089 },{"../Subscriber":55}],163:[function(require,module,exports){
21090 "use strict";
21091 var __extends = (this && this.__extends) || (function () {
21092     var extendStatics = function (d, b) {
21093         extendStatics = Object.setPrototypeOf ||
21094             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21095             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21096         return extendStatics(d, b);
21097     }
21098     return function (d, b) {
21099         extendStatics(d, b);
21100         function __() { this.constructor = d; }
21101         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21102     };
21103 })();
21104 Object.defineProperty(exports, "__esModule", { value: true });
21105 var Subscriber_1 = require("../Subscriber");
21106 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
21107 function skipLast(count) {
21108     return function (source) { return source.lift(new SkipLastOperator(count)); };
21109 }
21110 exports.skipLast = skipLast;
21111 var SkipLastOperator = (function () {
21112     function SkipLastOperator(_skipCount) {
21113         this._skipCount = _skipCount;
21114         if (this._skipCount < 0) {
21115             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
21116         }
21117     }
21118     SkipLastOperator.prototype.call = function (subscriber, source) {
21119         if (this._skipCount === 0) {
21120             return source.subscribe(new Subscriber_1.Subscriber(subscriber));
21121         }
21122         else {
21123             return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount));
21124         }
21125     };
21126     return SkipLastOperator;
21127 }());
21128 var SkipLastSubscriber = (function (_super) {
21129     __extends(SkipLastSubscriber, _super);
21130     function SkipLastSubscriber(destination, _skipCount) {
21131         var _this = _super.call(this, destination) || this;
21132         _this._skipCount = _skipCount;
21133         _this._count = 0;
21134         _this._ring = new Array(_skipCount);
21135         return _this;
21136     }
21137     SkipLastSubscriber.prototype._next = function (value) {
21138         var skipCount = this._skipCount;
21139         var count = this._count++;
21140         if (count < skipCount) {
21141             this._ring[count] = value;
21142         }
21143         else {
21144             var currentIndex = count % skipCount;
21145             var ring = this._ring;
21146             var oldValue = ring[currentIndex];
21147             ring[currentIndex] = value;
21148             this.destination.next(oldValue);
21149         }
21150     };
21151     return SkipLastSubscriber;
21152 }(Subscriber_1.Subscriber));
21153
21154 },{"../Subscriber":55,"../util/ArgumentOutOfRangeError":209}],164:[function(require,module,exports){
21155 "use strict";
21156 var __extends = (this && this.__extends) || (function () {
21157     var extendStatics = function (d, b) {
21158         extendStatics = Object.setPrototypeOf ||
21159             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21160             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21161         return extendStatics(d, b);
21162     }
21163     return function (d, b) {
21164         extendStatics(d, b);
21165         function __() { this.constructor = d; }
21166         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21167     };
21168 })();
21169 Object.defineProperty(exports, "__esModule", { value: true });
21170 var OuterSubscriber_1 = require("../OuterSubscriber");
21171 var InnerSubscriber_1 = require("../InnerSubscriber");
21172 var subscribeToResult_1 = require("../util/subscribeToResult");
21173 function skipUntil(notifier) {
21174     return function (source) { return source.lift(new SkipUntilOperator(notifier)); };
21175 }
21176 exports.skipUntil = skipUntil;
21177 var SkipUntilOperator = (function () {
21178     function SkipUntilOperator(notifier) {
21179         this.notifier = notifier;
21180     }
21181     SkipUntilOperator.prototype.call = function (destination, source) {
21182         return source.subscribe(new SkipUntilSubscriber(destination, this.notifier));
21183     };
21184     return SkipUntilOperator;
21185 }());
21186 var SkipUntilSubscriber = (function (_super) {
21187     __extends(SkipUntilSubscriber, _super);
21188     function SkipUntilSubscriber(destination, notifier) {
21189         var _this = _super.call(this, destination) || this;
21190         _this.hasValue = false;
21191         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(_this, undefined, undefined);
21192         _this.add(innerSubscriber);
21193         _this.innerSubscription = innerSubscriber;
21194         subscribeToResult_1.subscribeToResult(_this, notifier, undefined, undefined, innerSubscriber);
21195         return _this;
21196     }
21197     SkipUntilSubscriber.prototype._next = function (value) {
21198         if (this.hasValue) {
21199             _super.prototype._next.call(this, value);
21200         }
21201     };
21202     SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
21203         this.hasValue = true;
21204         if (this.innerSubscription) {
21205             this.innerSubscription.unsubscribe();
21206         }
21207     };
21208     SkipUntilSubscriber.prototype.notifyComplete = function () {
21209     };
21210     return SkipUntilSubscriber;
21211 }(OuterSubscriber_1.OuterSubscriber));
21212
21213 },{"../InnerSubscriber":46,"../OuterSubscriber":50,"../util/subscribeToResult":238}],165:[function(require,module,exports){
21214 "use strict";
21215 var __extends = (this && this.__extends) || (function () {
21216     var extendStatics = function (d, b) {
21217         extendStatics = Object.setPrototypeOf ||
21218             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21219             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21220         return extendStatics(d, b);
21221     }
21222     return function (d, b) {
21223         extendStatics(d, b);
21224         function __() { this.constructor = d; }
21225         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21226     };
21227 })();
21228 Object.defineProperty(exports, "__esModule", { value: true });
21229 var Subscriber_1 = require("../Subscriber");
21230 function skipWhile(predicate) {
21231     return function (source) { return source.lift(new SkipWhileOperator(predicate)); };
21232 }
21233 exports.skipWhile = skipWhile;
21234 var SkipWhileOperator = (function () {
21235     function SkipWhileOperator(predicate) {
21236         this.predicate = predicate;
21237     }
21238     SkipWhileOperator.prototype.call = function (subscriber, source) {
21239         return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
21240     };
21241     return SkipWhileOperator;
21242 }());
21243 var SkipWhileSubscriber = (function (_super) {
21244     __extends(SkipWhileSubscriber, _super);
21245     function SkipWhileSubscriber(destination, predicate) {
21246         var _this = _super.call(this, destination) || this;
21247         _this.predicate = predicate;
21248         _this.skipping = true;
21249         _this.index = 0;
21250         return _this;
21251     }
21252     SkipWhileSubscriber.prototype._next = function (value) {
21253         var destination = this.destination;
21254         if (this.skipping) {
21255             this.tryCallPredicate(value);
21256         }
21257         if (!this.skipping) {
21258             destination.next(value);
21259         }
21260     };
21261     SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
21262         try {
21263             var result = this.predicate(value, this.index++);
21264             this.skipping = Boolean(result);
21265         }
21266         catch (err) {
21267             this.destination.error(err);
21268         }
21269     };
21270     return SkipWhileSubscriber;
21271 }(Subscriber_1.Subscriber));
21272
21273 },{"../Subscriber":55}],166:[function(require,module,exports){
21274 "use strict";
21275 Object.defineProperty(exports, "__esModule", { value: true });
21276 var fromArray_1 = require("../observable/fromArray");
21277 var scalar_1 = require("../observable/scalar");
21278 var empty_1 = require("../observable/empty");
21279 var concat_1 = require("../observable/concat");
21280 var isScheduler_1 = require("../util/isScheduler");
21281 function startWith() {
21282     var array = [];
21283     for (var _i = 0; _i < arguments.length; _i++) {
21284         array[_i] = arguments[_i];
21285     }
21286     return function (source) {
21287         var scheduler = array[array.length - 1];
21288         if (isScheduler_1.isScheduler(scheduler)) {
21289             array.pop();
21290         }
21291         else {
21292             scheduler = null;
21293         }
21294         var len = array.length;
21295         if (len === 1 && !scheduler) {
21296             return concat_1.concat(scalar_1.scalar(array[0]), source);
21297         }
21298         else if (len > 0) {
21299             return concat_1.concat(fromArray_1.fromArray(array, scheduler), source);
21300         }
21301         else {
21302             return concat_1.concat(empty_1.empty(scheduler), source);
21303         }
21304     };
21305 }
21306 exports.startWith = startWith;
21307
21308 },{"../observable/concat":63,"../observable/empty":65,"../observable/fromArray":68,"../observable/scalar":84,"../util/isScheduler":229}],167:[function(require,module,exports){
21309 "use strict";
21310 Object.defineProperty(exports, "__esModule", { value: true });
21311 var SubscribeOnObservable_1 = require("../observable/SubscribeOnObservable");
21312 function subscribeOn(scheduler, delay) {
21313     if (delay === void 0) { delay = 0; }
21314     return function subscribeOnOperatorFunction(source) {
21315         return source.lift(new SubscribeOnOperator(scheduler, delay));
21316     };
21317 }
21318 exports.subscribeOn = subscribeOn;
21319 var SubscribeOnOperator = (function () {
21320     function SubscribeOnOperator(scheduler, delay) {
21321         this.scheduler = scheduler;
21322         this.delay = delay;
21323     }
21324     SubscribeOnOperator.prototype.call = function (subscriber, source) {
21325         return new SubscribeOnObservable_1.SubscribeOnObservable(source, this.delay, this.scheduler).subscribe(subscriber);
21326     };
21327     return SubscribeOnOperator;
21328 }());
21329
21330 },{"../observable/SubscribeOnObservable":59}],168:[function(require,module,exports){
21331 "use strict";
21332 Object.defineProperty(exports, "__esModule", { value: true });
21333 var switchMap_1 = require("./switchMap");
21334 var identity_1 = require("../util/identity");
21335 function switchAll() {
21336     return switchMap_1.switchMap(identity_1.identity);
21337 }
21338 exports.switchAll = switchAll;
21339
21340 },{"../util/identity":218,"./switchMap":169}],169:[function(require,module,exports){
21341 "use strict";
21342 var __extends = (this && this.__extends) || (function () {
21343     var extendStatics = function (d, b) {
21344         extendStatics = Object.setPrototypeOf ||
21345             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21346             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21347         return extendStatics(d, b);
21348     }
21349     return function (d, b) {
21350         extendStatics(d, b);
21351         function __() { this.constructor = d; }
21352         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21353     };
21354 })();
21355 Object.defineProperty(exports, "__esModule", { value: true });
21356 var OuterSubscriber_1 = require("../OuterSubscriber");
21357 var InnerSubscriber_1 = require("../InnerSubscriber");
21358 var subscribeToResult_1 = require("../util/subscribeToResult");
21359 var map_1 = require("./map");
21360 var from_1 = require("../observable/from");
21361 function switchMap(project, resultSelector) {
21362     if (typeof resultSelector === 'function') {
21363         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); })); })); };
21364     }
21365     return function (source) { return source.lift(new SwitchMapOperator(project)); };
21366 }
21367 exports.switchMap = switchMap;
21368 var SwitchMapOperator = (function () {
21369     function SwitchMapOperator(project) {
21370         this.project = project;
21371     }
21372     SwitchMapOperator.prototype.call = function (subscriber, source) {
21373         return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));
21374     };
21375     return SwitchMapOperator;
21376 }());
21377 var SwitchMapSubscriber = (function (_super) {
21378     __extends(SwitchMapSubscriber, _super);
21379     function SwitchMapSubscriber(destination, project) {
21380         var _this = _super.call(this, destination) || this;
21381         _this.project = project;
21382         _this.index = 0;
21383         return _this;
21384     }
21385     SwitchMapSubscriber.prototype._next = function (value) {
21386         var result;
21387         var index = this.index++;
21388         try {
21389             result = this.project(value, index);
21390         }
21391         catch (error) {
21392             this.destination.error(error);
21393             return;
21394         }
21395         this._innerSub(result, value, index);
21396     };
21397     SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
21398         var innerSubscription = this.innerSubscription;
21399         if (innerSubscription) {
21400             innerSubscription.unsubscribe();
21401         }
21402         var innerSubscriber = new InnerSubscriber_1.InnerSubscriber(this, undefined, undefined);
21403         var destination = this.destination;
21404         destination.add(innerSubscriber);
21405         this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index, innerSubscriber);
21406     };
21407     SwitchMapSubscriber.prototype._complete = function () {
21408         var innerSubscription = this.innerSubscription;
21409         if (!innerSubscription || innerSubscription.closed) {
21410             _super.prototype._complete.call(this);
21411         }
21412         this.unsubscribe();
21413     };
21414     SwitchMapSubscriber.prototype._unsubscribe = function () {
21415         this.innerSubscription = null;
21416     };
21417     SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
21418         var destination = this.destination;
21419         destination.remove(innerSub);
21420         this.innerSubscription = null;
21421         if (this.isStopped) {
21422             _super.prototype._complete.call(this);
21423         }
21424     };
21425     SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
21426         this.destination.next(innerValue);
21427     };
21428     return SwitchMapSubscriber;
21429 }(OuterSubscriber_1.OuterSubscriber));
21430
21431 },{"../InnerSubscriber":46,"../OuterSubscriber":50,"../observable/from":67,"../util/subscribeToResult":238,"./map":128}],170:[function(require,module,exports){
21432 "use strict";
21433 Object.defineProperty(exports, "__esModule", { value: true });
21434 var switchMap_1 = require("./switchMap");
21435 function switchMapTo(innerObservable, resultSelector) {
21436     return resultSelector ? switchMap_1.switchMap(function () { return innerObservable; }, resultSelector) : switchMap_1.switchMap(function () { return innerObservable; });
21437 }
21438 exports.switchMapTo = switchMapTo;
21439
21440 },{"./switchMap":169}],171:[function(require,module,exports){
21441 "use strict";
21442 var __extends = (this && this.__extends) || (function () {
21443     var extendStatics = function (d, b) {
21444         extendStatics = Object.setPrototypeOf ||
21445             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21446             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21447         return extendStatics(d, b);
21448     }
21449     return function (d, b) {
21450         extendStatics(d, b);
21451         function __() { this.constructor = d; }
21452         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21453     };
21454 })();
21455 Object.defineProperty(exports, "__esModule", { value: true });
21456 var Subscriber_1 = require("../Subscriber");
21457 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
21458 var empty_1 = require("../observable/empty");
21459 function take(count) {
21460     return function (source) {
21461         if (count === 0) {
21462             return empty_1.empty();
21463         }
21464         else {
21465             return source.lift(new TakeOperator(count));
21466         }
21467     };
21468 }
21469 exports.take = take;
21470 var TakeOperator = (function () {
21471     function TakeOperator(total) {
21472         this.total = total;
21473         if (this.total < 0) {
21474             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
21475         }
21476     }
21477     TakeOperator.prototype.call = function (subscriber, source) {
21478         return source.subscribe(new TakeSubscriber(subscriber, this.total));
21479     };
21480     return TakeOperator;
21481 }());
21482 var TakeSubscriber = (function (_super) {
21483     __extends(TakeSubscriber, _super);
21484     function TakeSubscriber(destination, total) {
21485         var _this = _super.call(this, destination) || this;
21486         _this.total = total;
21487         _this.count = 0;
21488         return _this;
21489     }
21490     TakeSubscriber.prototype._next = function (value) {
21491         var total = this.total;
21492         var count = ++this.count;
21493         if (count <= total) {
21494             this.destination.next(value);
21495             if (count === total) {
21496                 this.destination.complete();
21497                 this.unsubscribe();
21498             }
21499         }
21500     };
21501     return TakeSubscriber;
21502 }(Subscriber_1.Subscriber));
21503
21504 },{"../Subscriber":55,"../observable/empty":65,"../util/ArgumentOutOfRangeError":209}],172:[function(require,module,exports){
21505 "use strict";
21506 var __extends = (this && this.__extends) || (function () {
21507     var extendStatics = function (d, b) {
21508         extendStatics = Object.setPrototypeOf ||
21509             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21510             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21511         return extendStatics(d, b);
21512     }
21513     return function (d, b) {
21514         extendStatics(d, b);
21515         function __() { this.constructor = d; }
21516         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21517     };
21518 })();
21519 Object.defineProperty(exports, "__esModule", { value: true });
21520 var Subscriber_1 = require("../Subscriber");
21521 var ArgumentOutOfRangeError_1 = require("../util/ArgumentOutOfRangeError");
21522 var empty_1 = require("../observable/empty");
21523 function takeLast(count) {
21524     return function takeLastOperatorFunction(source) {
21525         if (count === 0) {
21526             return empty_1.empty();
21527         }
21528         else {
21529             return source.lift(new TakeLastOperator(count));
21530         }
21531     };
21532 }
21533 exports.takeLast = takeLast;
21534 var TakeLastOperator = (function () {
21535     function TakeLastOperator(total) {
21536         this.total = total;
21537         if (this.total < 0) {
21538             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
21539         }
21540     }
21541     TakeLastOperator.prototype.call = function (subscriber, source) {
21542         return source.subscribe(new TakeLastSubscriber(subscriber, this.total));
21543     };
21544     return TakeLastOperator;
21545 }());
21546 var TakeLastSubscriber = (function (_super) {
21547     __extends(TakeLastSubscriber, _super);
21548     function TakeLastSubscriber(destination, total) {
21549         var _this = _super.call(this, destination) || this;
21550         _this.total = total;
21551         _this.ring = new Array();
21552         _this.count = 0;
21553         return _this;
21554     }
21555     TakeLastSubscriber.prototype._next = function (value) {
21556         var ring = this.ring;
21557         var total = this.total;
21558         var count = this.count++;
21559         if (ring.length < total) {
21560             ring.push(value);
21561         }
21562         else {
21563             var index = count % total;
21564             ring[index] = value;
21565         }
21566     };
21567     TakeLastSubscriber.prototype._complete = function () {
21568         var destination = this.destination;
21569         var count = this.count;
21570         if (count > 0) {
21571             var total = this.count >= this.total ? this.total : this.count;
21572             var ring = this.ring;
21573             for (var i = 0; i < total; i++) {
21574                 var idx = (count++) % total;
21575                 destination.next(ring[idx]);
21576             }
21577         }
21578         destination.complete();
21579     };
21580     return TakeLastSubscriber;
21581 }(Subscriber_1.Subscriber));
21582
21583 },{"../Subscriber":55,"../observable/empty":65,"../util/ArgumentOutOfRangeError":209}],173:[function(require,module,exports){
21584 "use strict";
21585 var __extends = (this && this.__extends) || (function () {
21586     var extendStatics = function (d, b) {
21587         extendStatics = Object.setPrototypeOf ||
21588             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21589             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21590         return extendStatics(d, b);
21591     }
21592     return function (d, b) {
21593         extendStatics(d, b);
21594         function __() { this.constructor = d; }
21595         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21596     };
21597 })();
21598 Object.defineProperty(exports, "__esModule", { value: true });
21599 var OuterSubscriber_1 = require("../OuterSubscriber");
21600 var subscribeToResult_1 = require("../util/subscribeToResult");
21601 function takeUntil(notifier) {
21602     return function (source) { return source.lift(new TakeUntilOperator(notifier)); };
21603 }
21604 exports.takeUntil = takeUntil;
21605 var TakeUntilOperator = (function () {
21606     function TakeUntilOperator(notifier) {
21607         this.notifier = notifier;
21608     }
21609     TakeUntilOperator.prototype.call = function (subscriber, source) {
21610         var takeUntilSubscriber = new TakeUntilSubscriber(subscriber);
21611         var notifierSubscription = subscribeToResult_1.subscribeToResult(takeUntilSubscriber, this.notifier);
21612         if (notifierSubscription && !takeUntilSubscriber.seenValue) {
21613             takeUntilSubscriber.add(notifierSubscription);
21614             return source.subscribe(takeUntilSubscriber);
21615         }
21616         return takeUntilSubscriber;
21617     };
21618     return TakeUntilOperator;
21619 }());
21620 var TakeUntilSubscriber = (function (_super) {
21621     __extends(TakeUntilSubscriber, _super);
21622     function TakeUntilSubscriber(destination) {
21623         var _this = _super.call(this, destination) || this;
21624         _this.seenValue = false;
21625         return _this;
21626     }
21627     TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
21628         this.seenValue = true;
21629         this.complete();
21630     };
21631     TakeUntilSubscriber.prototype.notifyComplete = function () {
21632     };
21633     return TakeUntilSubscriber;
21634 }(OuterSubscriber_1.OuterSubscriber));
21635
21636 },{"../OuterSubscriber":50,"../util/subscribeToResult":238}],174:[function(require,module,exports){
21637 "use strict";
21638 var __extends = (this && this.__extends) || (function () {
21639     var extendStatics = function (d, b) {
21640         extendStatics = Object.setPrototypeOf ||
21641             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21642             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21643         return extendStatics(d, b);
21644     }
21645     return function (d, b) {
21646         extendStatics(d, b);
21647         function __() { this.constructor = d; }
21648         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21649     };
21650 })();
21651 Object.defineProperty(exports, "__esModule", { value: true });
21652 var Subscriber_1 = require("../Subscriber");
21653 function takeWhile(predicate) {
21654     return function (source) { return source.lift(new TakeWhileOperator(predicate)); };
21655 }
21656 exports.takeWhile = takeWhile;
21657 var TakeWhileOperator = (function () {
21658     function TakeWhileOperator(predicate) {
21659         this.predicate = predicate;
21660     }
21661     TakeWhileOperator.prototype.call = function (subscriber, source) {
21662         return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate));
21663     };
21664     return TakeWhileOperator;
21665 }());
21666 var TakeWhileSubscriber = (function (_super) {
21667     __extends(TakeWhileSubscriber, _super);
21668     function TakeWhileSubscriber(destination, predicate) {
21669         var _this = _super.call(this, destination) || this;
21670         _this.predicate = predicate;
21671         _this.index = 0;
21672         return _this;
21673     }
21674     TakeWhileSubscriber.prototype._next = function (value) {
21675         var destination = this.destination;
21676         var result;
21677         try {
21678             result = this.predicate(value, this.index++);
21679         }
21680         catch (err) {
21681             destination.error(err);
21682             return;
21683         }
21684         this.nextOrComplete(value, result);
21685     };
21686     TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) {
21687         var destination = this.destination;
21688         if (Boolean(predicateResult)) {
21689             destination.next(value);
21690         }
21691         else {
21692             destination.complete();
21693         }
21694     };
21695     return TakeWhileSubscriber;
21696 }(Subscriber_1.Subscriber));
21697
21698 },{"../Subscriber":55}],175:[function(require,module,exports){
21699 "use strict";
21700 var __extends = (this && this.__extends) || (function () {
21701     var extendStatics = function (d, b) {
21702         extendStatics = Object.setPrototypeOf ||
21703             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21704             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21705         return extendStatics(d, b);
21706     }
21707     return function (d, b) {
21708         extendStatics(d, b);
21709         function __() { this.constructor = d; }
21710         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21711     };
21712 })();
21713 Object.defineProperty(exports, "__esModule", { value: true });
21714 var Subscriber_1 = require("../Subscriber");
21715 var noop_1 = require("../util/noop");
21716 var isFunction_1 = require("../util/isFunction");
21717 function tap(nextOrObserver, error, complete) {
21718     return function tapOperatorFunction(source) {
21719         return source.lift(new DoOperator(nextOrObserver, error, complete));
21720     };
21721 }
21722 exports.tap = tap;
21723 var DoOperator = (function () {
21724     function DoOperator(nextOrObserver, error, complete) {
21725         this.nextOrObserver = nextOrObserver;
21726         this.error = error;
21727         this.complete = complete;
21728     }
21729     DoOperator.prototype.call = function (subscriber, source) {
21730         return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
21731     };
21732     return DoOperator;
21733 }());
21734 var TapSubscriber = (function (_super) {
21735     __extends(TapSubscriber, _super);
21736     function TapSubscriber(destination, observerOrNext, error, complete) {
21737         var _this = _super.call(this, destination) || this;
21738         _this._tapNext = noop_1.noop;
21739         _this._tapError = noop_1.noop;
21740         _this._tapComplete = noop_1.noop;
21741         _this._tapError = error || noop_1.noop;
21742         _this._tapComplete = complete || noop_1.noop;
21743         if (isFunction_1.isFunction(observerOrNext)) {
21744             _this._context = _this;
21745             _this._tapNext = observerOrNext;
21746         }
21747         else if (observerOrNext) {
21748             _this._context = observerOrNext;
21749             _this._tapNext = observerOrNext.next || noop_1.noop;
21750             _this._tapError = observerOrNext.error || noop_1.noop;
21751             _this._tapComplete = observerOrNext.complete || noop_1.noop;
21752         }
21753         return _this;
21754     }
21755     TapSubscriber.prototype._next = function (value) {
21756         try {
21757             this._tapNext.call(this._context, value);
21758         }
21759         catch (err) {
21760             this.destination.error(err);
21761             return;
21762         }
21763         this.destination.next(value);
21764     };
21765     TapSubscriber.prototype._error = function (err) {
21766         try {
21767             this._tapError.call(this._context, err);
21768         }
21769         catch (err) {
21770             this.destination.error(err);
21771             return;
21772         }
21773         this.destination.error(err);
21774     };
21775     TapSubscriber.prototype._complete = function () {
21776         try {
21777             this._tapComplete.call(this._context);
21778         }
21779         catch (err) {
21780             this.destination.error(err);
21781             return;
21782         }
21783         return this.destination.complete();
21784     };
21785     return TapSubscriber;
21786 }(Subscriber_1.Subscriber));
21787
21788 },{"../Subscriber":55,"../util/isFunction":222,"../util/noop":230}],176:[function(require,module,exports){
21789 "use strict";
21790 var __extends = (this && this.__extends) || (function () {
21791     var extendStatics = function (d, b) {
21792         extendStatics = Object.setPrototypeOf ||
21793             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21794             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21795         return extendStatics(d, b);
21796     }
21797     return function (d, b) {
21798         extendStatics(d, b);
21799         function __() { this.constructor = d; }
21800         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21801     };
21802 })();
21803 Object.defineProperty(exports, "__esModule", { value: true });
21804 var OuterSubscriber_1 = require("../OuterSubscriber");
21805 var subscribeToResult_1 = require("../util/subscribeToResult");
21806 exports.defaultThrottleConfig = {
21807     leading: true,
21808     trailing: false
21809 };
21810 function throttle(durationSelector, config) {
21811     if (config === void 0) { config = exports.defaultThrottleConfig; }
21812     return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); };
21813 }
21814 exports.throttle = throttle;
21815 var ThrottleOperator = (function () {
21816     function ThrottleOperator(durationSelector, leading, trailing) {
21817         this.durationSelector = durationSelector;
21818         this.leading = leading;
21819         this.trailing = trailing;
21820     }
21821     ThrottleOperator.prototype.call = function (subscriber, source) {
21822         return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
21823     };
21824     return ThrottleOperator;
21825 }());
21826 var ThrottleSubscriber = (function (_super) {
21827     __extends(ThrottleSubscriber, _super);
21828     function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
21829         var _this = _super.call(this, destination) || this;
21830         _this.destination = destination;
21831         _this.durationSelector = durationSelector;
21832         _this._leading = _leading;
21833         _this._trailing = _trailing;
21834         _this._hasValue = false;
21835         return _this;
21836     }
21837     ThrottleSubscriber.prototype._next = function (value) {
21838         this._hasValue = true;
21839         this._sendValue = value;
21840         if (!this._throttled) {
21841             if (this._leading) {
21842                 this.send();
21843             }
21844             else {
21845                 this.throttle(value);
21846             }
21847         }
21848     };
21849     ThrottleSubscriber.prototype.send = function () {
21850         var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue;
21851         if (_hasValue) {
21852             this.destination.next(_sendValue);
21853             this.throttle(_sendValue);
21854         }
21855         this._hasValue = false;
21856         this._sendValue = null;
21857     };
21858     ThrottleSubscriber.prototype.throttle = function (value) {
21859         var duration = this.tryDurationSelector(value);
21860         if (duration) {
21861             this.add(this._throttled = subscribeToResult_1.subscribeToResult(this, duration));
21862         }
21863     };
21864     ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
21865         try {
21866             return this.durationSelector(value);
21867         }
21868         catch (err) {
21869             this.destination.error(err);
21870             return null;
21871         }
21872     };
21873     ThrottleSubscriber.prototype.throttlingDone = function () {
21874         var _a = this, _throttled = _a._throttled, _trailing = _a._trailing;
21875         if (_throttled) {
21876             _throttled.unsubscribe();
21877         }
21878         this._throttled = null;
21879         if (_trailing) {
21880             this.send();
21881         }
21882     };
21883     ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
21884         this.throttlingDone();
21885     };
21886     ThrottleSubscriber.prototype.notifyComplete = function () {
21887         this.throttlingDone();
21888     };
21889     return ThrottleSubscriber;
21890 }(OuterSubscriber_1.OuterSubscriber));
21891
21892 },{"../OuterSubscriber":50,"../util/subscribeToResult":238}],177:[function(require,module,exports){
21893 "use strict";
21894 var __extends = (this && this.__extends) || (function () {
21895     var extendStatics = function (d, b) {
21896         extendStatics = Object.setPrototypeOf ||
21897             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21898             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21899         return extendStatics(d, b);
21900     }
21901     return function (d, b) {
21902         extendStatics(d, b);
21903         function __() { this.constructor = d; }
21904         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21905     };
21906 })();
21907 Object.defineProperty(exports, "__esModule", { value: true });
21908 var Subscriber_1 = require("../Subscriber");
21909 var async_1 = require("../scheduler/async");
21910 var throttle_1 = require("./throttle");
21911 function throttleTime(duration, scheduler, config) {
21912     if (scheduler === void 0) { scheduler = async_1.async; }
21913     if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
21914     return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); };
21915 }
21916 exports.throttleTime = throttleTime;
21917 var ThrottleTimeOperator = (function () {
21918     function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
21919         this.duration = duration;
21920         this.scheduler = scheduler;
21921         this.leading = leading;
21922         this.trailing = trailing;
21923     }
21924     ThrottleTimeOperator.prototype.call = function (subscriber, source) {
21925         return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
21926     };
21927     return ThrottleTimeOperator;
21928 }());
21929 var ThrottleTimeSubscriber = (function (_super) {
21930     __extends(ThrottleTimeSubscriber, _super);
21931     function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
21932         var _this = _super.call(this, destination) || this;
21933         _this.duration = duration;
21934         _this.scheduler = scheduler;
21935         _this.leading = leading;
21936         _this.trailing = trailing;
21937         _this._hasTrailingValue = false;
21938         _this._trailingValue = null;
21939         return _this;
21940     }
21941     ThrottleTimeSubscriber.prototype._next = function (value) {
21942         if (this.throttled) {
21943             if (this.trailing) {
21944                 this._trailingValue = value;
21945                 this._hasTrailingValue = true;
21946             }
21947         }
21948         else {
21949             this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
21950             if (this.leading) {
21951                 this.destination.next(value);
21952             }
21953         }
21954     };
21955     ThrottleTimeSubscriber.prototype._complete = function () {
21956         if (this._hasTrailingValue) {
21957             this.destination.next(this._trailingValue);
21958             this.destination.complete();
21959         }
21960         else {
21961             this.destination.complete();
21962         }
21963     };
21964     ThrottleTimeSubscriber.prototype.clearThrottle = function () {
21965         var throttled = this.throttled;
21966         if (throttled) {
21967             if (this.trailing && this._hasTrailingValue) {
21968                 this.destination.next(this._trailingValue);
21969                 this._trailingValue = null;
21970                 this._hasTrailingValue = false;
21971             }
21972             throttled.unsubscribe();
21973             this.remove(throttled);
21974             this.throttled = null;
21975         }
21976     };
21977     return ThrottleTimeSubscriber;
21978 }(Subscriber_1.Subscriber));
21979 function dispatchNext(arg) {
21980     var subscriber = arg.subscriber;
21981     subscriber.clearThrottle();
21982 }
21983
21984 },{"../Subscriber":55,"../scheduler/async":204,"./throttle":176}],178:[function(require,module,exports){
21985 "use strict";
21986 Object.defineProperty(exports, "__esModule", { value: true });
21987 var tap_1 = require("./tap");
21988 var EmptyError_1 = require("../util/EmptyError");
21989 exports.throwIfEmpty = function (errorFactory) {
21990     if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
21991     return tap_1.tap({
21992         hasValue: false,
21993         next: function () { this.hasValue = true; },
21994         complete: function () {
21995             if (!this.hasValue) {
21996                 throw errorFactory();
21997             }
21998         }
21999     });
22000 };
22001 function defaultErrorFactory() {
22002     return new EmptyError_1.EmptyError();
22003 }
22004
22005 },{"../util/EmptyError":210,"./tap":175}],179:[function(require,module,exports){
22006 "use strict";
22007 Object.defineProperty(exports, "__esModule", { value: true });
22008 var async_1 = require("../scheduler/async");
22009 var scan_1 = require("./scan");
22010 var defer_1 = require("../observable/defer");
22011 var map_1 = require("./map");
22012 function timeInterval(scheduler) {
22013     if (scheduler === void 0) { scheduler = async_1.async; }
22014     return function (source) { return defer_1.defer(function () {
22015         return source.pipe(scan_1.scan(function (_a, value) {
22016             var current = _a.current;
22017             return ({ value: value, current: scheduler.now(), last: current });
22018         }, { current: scheduler.now(), value: undefined, last: undefined }), map_1.map(function (_a) {
22019             var current = _a.current, last = _a.last, value = _a.value;
22020             return new TimeInterval(value, current - last);
22021         }));
22022     }); };
22023 }
22024 exports.timeInterval = timeInterval;
22025 var TimeInterval = (function () {
22026     function TimeInterval(value, interval) {
22027         this.value = value;
22028         this.interval = interval;
22029     }
22030     return TimeInterval;
22031 }());
22032 exports.TimeInterval = TimeInterval;
22033
22034 },{"../observable/defer":64,"../scheduler/async":204,"./map":128,"./scan":157}],180:[function(require,module,exports){
22035 "use strict";
22036 Object.defineProperty(exports, "__esModule", { value: true });
22037 var async_1 = require("../scheduler/async");
22038 var TimeoutError_1 = require("../util/TimeoutError");
22039 var timeoutWith_1 = require("./timeoutWith");
22040 var throwError_1 = require("../observable/throwError");
22041 function timeout(due, scheduler) {
22042     if (scheduler === void 0) { scheduler = async_1.async; }
22043     return timeoutWith_1.timeoutWith(due, throwError_1.throwError(new TimeoutError_1.TimeoutError()), scheduler);
22044 }
22045 exports.timeout = timeout;
22046
22047 },{"../observable/throwError":85,"../scheduler/async":204,"../util/TimeoutError":213,"./timeoutWith":181}],181:[function(require,module,exports){
22048 "use strict";
22049 var __extends = (this && this.__extends) || (function () {
22050     var extendStatics = function (d, b) {
22051         extendStatics = Object.setPrototypeOf ||
22052             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22053             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22054         return extendStatics(d, b);
22055     }
22056     return function (d, b) {
22057         extendStatics(d, b);
22058         function __() { this.constructor = d; }
22059         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22060     };
22061 })();
22062 Object.defineProperty(exports, "__esModule", { value: true });
22063 var async_1 = require("../scheduler/async");
22064 var isDate_1 = require("../util/isDate");
22065 var OuterSubscriber_1 = require("../OuterSubscriber");
22066 var subscribeToResult_1 = require("../util/subscribeToResult");
22067 function timeoutWith(due, withObservable, scheduler) {
22068     if (scheduler === void 0) { scheduler = async_1.async; }
22069     return function (source) {
22070         var absoluteTimeout = isDate_1.isDate(due);
22071         var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
22072         return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));
22073     };
22074 }
22075 exports.timeoutWith = timeoutWith;
22076 var TimeoutWithOperator = (function () {
22077     function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) {
22078         this.waitFor = waitFor;
22079         this.absoluteTimeout = absoluteTimeout;
22080         this.withObservable = withObservable;
22081         this.scheduler = scheduler;
22082     }
22083     TimeoutWithOperator.prototype.call = function (subscriber, source) {
22084         return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler));
22085     };
22086     return TimeoutWithOperator;
22087 }());
22088 var TimeoutWithSubscriber = (function (_super) {
22089     __extends(TimeoutWithSubscriber, _super);
22090     function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) {
22091         var _this = _super.call(this, destination) || this;
22092         _this.absoluteTimeout = absoluteTimeout;
22093         _this.waitFor = waitFor;
22094         _this.withObservable = withObservable;
22095         _this.scheduler = scheduler;
22096         _this.action = null;
22097         _this.scheduleTimeout();
22098         return _this;
22099     }
22100     TimeoutWithSubscriber.dispatchTimeout = function (subscriber) {
22101         var withObservable = subscriber.withObservable;
22102         subscriber._unsubscribeAndRecycle();
22103         subscriber.add(subscribeToResult_1.subscribeToResult(subscriber, withObservable));
22104     };
22105     TimeoutWithSubscriber.prototype.scheduleTimeout = function () {
22106         var action = this.action;
22107         if (action) {
22108             this.action = action.schedule(this, this.waitFor);
22109         }
22110         else {
22111             this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this));
22112         }
22113     };
22114     TimeoutWithSubscriber.prototype._next = function (value) {
22115         if (!this.absoluteTimeout) {
22116             this.scheduleTimeout();
22117         }
22118         _super.prototype._next.call(this, value);
22119     };
22120     TimeoutWithSubscriber.prototype._unsubscribe = function () {
22121         this.action = null;
22122         this.scheduler = null;
22123         this.withObservable = null;
22124     };
22125     return TimeoutWithSubscriber;
22126 }(OuterSubscriber_1.OuterSubscriber));
22127
22128 },{"../OuterSubscriber":50,"../scheduler/async":204,"../util/isDate":221,"../util/subscribeToResult":238}],182:[function(require,module,exports){
22129 "use strict";
22130 Object.defineProperty(exports, "__esModule", { value: true });
22131 var async_1 = require("../scheduler/async");
22132 var map_1 = require("./map");
22133 function timestamp(scheduler) {
22134     if (scheduler === void 0) { scheduler = async_1.async; }
22135     return map_1.map(function (value) { return new Timestamp(value, scheduler.now()); });
22136 }
22137 exports.timestamp = timestamp;
22138 var Timestamp = (function () {
22139     function Timestamp(value, timestamp) {
22140         this.value = value;
22141         this.timestamp = timestamp;
22142     }
22143     return Timestamp;
22144 }());
22145 exports.Timestamp = Timestamp;
22146
22147 },{"../scheduler/async":204,"./map":128}],183:[function(require,module,exports){
22148 "use strict";
22149 Object.defineProperty(exports, "__esModule", { value: true });
22150 var reduce_1 = require("./reduce");
22151 function toArrayReducer(arr, item, index) {
22152     if (index === 0) {
22153         return [item];
22154     }
22155     arr.push(item);
22156     return arr;
22157 }
22158 function toArray() {
22159     return reduce_1.reduce(toArrayReducer, []);
22160 }
22161 exports.toArray = toArray;
22162
22163 },{"./reduce":149}],184:[function(require,module,exports){
22164 "use strict";
22165 var __extends = (this && this.__extends) || (function () {
22166     var extendStatics = function (d, b) {
22167         extendStatics = Object.setPrototypeOf ||
22168             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22169             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22170         return extendStatics(d, b);
22171     }
22172     return function (d, b) {
22173         extendStatics(d, b);
22174         function __() { this.constructor = d; }
22175         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22176     };
22177 })();
22178 Object.defineProperty(exports, "__esModule", { value: true });
22179 var Subject_1 = require("../Subject");
22180 var OuterSubscriber_1 = require("../OuterSubscriber");
22181 var subscribeToResult_1 = require("../util/subscribeToResult");
22182 function window(windowBoundaries) {
22183     return function windowOperatorFunction(source) {
22184         return source.lift(new WindowOperator(windowBoundaries));
22185     };
22186 }
22187 exports.window = window;
22188 var WindowOperator = (function () {
22189     function WindowOperator(windowBoundaries) {
22190         this.windowBoundaries = windowBoundaries;
22191     }
22192     WindowOperator.prototype.call = function (subscriber, source) {
22193         var windowSubscriber = new WindowSubscriber(subscriber);
22194         var sourceSubscription = source.subscribe(windowSubscriber);
22195         if (!sourceSubscription.closed) {
22196             windowSubscriber.add(subscribeToResult_1.subscribeToResult(windowSubscriber, this.windowBoundaries));
22197         }
22198         return sourceSubscription;
22199     };
22200     return WindowOperator;
22201 }());
22202 var WindowSubscriber = (function (_super) {
22203     __extends(WindowSubscriber, _super);
22204     function WindowSubscriber(destination) {
22205         var _this = _super.call(this, destination) || this;
22206         _this.window = new Subject_1.Subject();
22207         destination.next(_this.window);
22208         return _this;
22209     }
22210     WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
22211         this.openWindow();
22212     };
22213     WindowSubscriber.prototype.notifyError = function (error, innerSub) {
22214         this._error(error);
22215     };
22216     WindowSubscriber.prototype.notifyComplete = function (innerSub) {
22217         this._complete();
22218     };
22219     WindowSubscriber.prototype._next = function (value) {
22220         this.window.next(value);
22221     };
22222     WindowSubscriber.prototype._error = function (err) {
22223         this.window.error(err);
22224         this.destination.error(err);
22225     };
22226     WindowSubscriber.prototype._complete = function () {
22227         this.window.complete();
22228         this.destination.complete();
22229     };
22230     WindowSubscriber.prototype._unsubscribe = function () {
22231         this.window = null;
22232     };
22233     WindowSubscriber.prototype.openWindow = function () {
22234         var prevWindow = this.window;
22235         if (prevWindow) {
22236             prevWindow.complete();
22237         }
22238         var destination = this.destination;
22239         var newWindow = this.window = new Subject_1.Subject();
22240         destination.next(newWindow);
22241     };
22242     return WindowSubscriber;
22243 }(OuterSubscriber_1.OuterSubscriber));
22244
22245 },{"../OuterSubscriber":50,"../Subject":53,"../util/subscribeToResult":238}],185:[function(require,module,exports){
22246 "use strict";
22247 var __extends = (this && this.__extends) || (function () {
22248     var extendStatics = function (d, b) {
22249         extendStatics = Object.setPrototypeOf ||
22250             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22251             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22252         return extendStatics(d, b);
22253     }
22254     return function (d, b) {
22255         extendStatics(d, b);
22256         function __() { this.constructor = d; }
22257         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22258     };
22259 })();
22260 Object.defineProperty(exports, "__esModule", { value: true });
22261 var Subscriber_1 = require("../Subscriber");
22262 var Subject_1 = require("../Subject");
22263 function windowCount(windowSize, startWindowEvery) {
22264     if (startWindowEvery === void 0) { startWindowEvery = 0; }
22265     return function windowCountOperatorFunction(source) {
22266         return source.lift(new WindowCountOperator(windowSize, startWindowEvery));
22267     };
22268 }
22269 exports.windowCount = windowCount;
22270 var WindowCountOperator = (function () {
22271     function WindowCountOperator(windowSize, startWindowEvery) {
22272         this.windowSize = windowSize;
22273         this.startWindowEvery = startWindowEvery;
22274     }
22275     WindowCountOperator.prototype.call = function (subscriber, source) {
22276         return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery));
22277     };
22278     return WindowCountOperator;
22279 }());
22280 var WindowCountSubscriber = (function (_super) {
22281     __extends(WindowCountSubscriber, _super);
22282     function WindowCountSubscriber(destination, windowSize, startWindowEvery) {
22283         var _this = _super.call(this, destination) || this;
22284         _this.destination = destination;
22285         _this.windowSize = windowSize;
22286         _this.startWindowEvery = startWindowEvery;
22287         _this.windows = [new Subject_1.Subject()];
22288         _this.count = 0;
22289         destination.next(_this.windows[0]);
22290         return _this;
22291     }
22292     WindowCountSubscriber.prototype._next = function (value) {
22293         var startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize;
22294         var destination = this.destination;
22295         var windowSize = this.windowSize;
22296         var windows = this.windows;
22297         var len = windows.length;
22298         for (var i = 0; i < len && !this.closed; i++) {
22299             windows[i].next(value);
22300         }
22301         var c = this.count - windowSize + 1;
22302         if (c >= 0 && c % startWindowEvery === 0 && !this.closed) {
22303             windows.shift().complete();
22304         }
22305         if (++this.count % startWindowEvery === 0 && !this.closed) {
22306             var window_1 = new Subject_1.Subject();
22307             windows.push(window_1);
22308             destination.next(window_1);
22309         }
22310     };
22311     WindowCountSubscriber.prototype._error = function (err) {
22312         var windows = this.windows;
22313         if (windows) {
22314             while (windows.length > 0 && !this.closed) {
22315                 windows.shift().error(err);
22316             }
22317         }
22318         this.destination.error(err);
22319     };
22320     WindowCountSubscriber.prototype._complete = function () {
22321         var windows = this.windows;
22322         if (windows) {
22323             while (windows.length > 0 && !this.closed) {
22324                 windows.shift().complete();
22325             }
22326         }
22327         this.destination.complete();
22328     };
22329     WindowCountSubscriber.prototype._unsubscribe = function () {
22330         this.count = 0;
22331         this.windows = null;
22332     };
22333     return WindowCountSubscriber;
22334 }(Subscriber_1.Subscriber));
22335
22336 },{"../Subject":53,"../Subscriber":55}],186:[function(require,module,exports){
22337 "use strict";
22338 var __extends = (this && this.__extends) || (function () {
22339     var extendStatics = function (d, b) {
22340         extendStatics = Object.setPrototypeOf ||
22341             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22342             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22343         return extendStatics(d, b);
22344     }
22345     return function (d, b) {
22346         extendStatics(d, b);
22347         function __() { this.constructor = d; }
22348         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22349     };
22350 })();
22351 Object.defineProperty(exports, "__esModule", { value: true });
22352 var Subject_1 = require("../Subject");
22353 var async_1 = require("../scheduler/async");
22354 var Subscriber_1 = require("../Subscriber");
22355 var isNumeric_1 = require("../util/isNumeric");
22356 var isScheduler_1 = require("../util/isScheduler");
22357 function windowTime(windowTimeSpan) {
22358     var scheduler = async_1.async;
22359     var windowCreationInterval = null;
22360     var maxWindowSize = Number.POSITIVE_INFINITY;
22361     if (isScheduler_1.isScheduler(arguments[3])) {
22362         scheduler = arguments[3];
22363     }
22364     if (isScheduler_1.isScheduler(arguments[2])) {
22365         scheduler = arguments[2];
22366     }
22367     else if (isNumeric_1.isNumeric(arguments[2])) {
22368         maxWindowSize = arguments[2];
22369     }
22370     if (isScheduler_1.isScheduler(arguments[1])) {
22371         scheduler = arguments[1];
22372     }
22373     else if (isNumeric_1.isNumeric(arguments[1])) {
22374         windowCreationInterval = arguments[1];
22375     }
22376     return function windowTimeOperatorFunction(source) {
22377         return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler));
22378     };
22379 }
22380 exports.windowTime = windowTime;
22381 var WindowTimeOperator = (function () {
22382     function WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
22383         this.windowTimeSpan = windowTimeSpan;
22384         this.windowCreationInterval = windowCreationInterval;
22385         this.maxWindowSize = maxWindowSize;
22386         this.scheduler = scheduler;
22387     }
22388     WindowTimeOperator.prototype.call = function (subscriber, source) {
22389         return source.subscribe(new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler));
22390     };
22391     return WindowTimeOperator;
22392 }());
22393 var CountedSubject = (function (_super) {
22394     __extends(CountedSubject, _super);
22395     function CountedSubject() {
22396         var _this = _super !== null && _super.apply(this, arguments) || this;
22397         _this._numberOfNextedValues = 0;
22398         return _this;
22399     }
22400     CountedSubject.prototype.next = function (value) {
22401         this._numberOfNextedValues++;
22402         _super.prototype.next.call(this, value);
22403     };
22404     Object.defineProperty(CountedSubject.prototype, "numberOfNextedValues", {
22405         get: function () {
22406             return this._numberOfNextedValues;
22407         },
22408         enumerable: true,
22409         configurable: true
22410     });
22411     return CountedSubject;
22412 }(Subject_1.Subject));
22413 var WindowTimeSubscriber = (function (_super) {
22414     __extends(WindowTimeSubscriber, _super);
22415     function WindowTimeSubscriber(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
22416         var _this = _super.call(this, destination) || this;
22417         _this.destination = destination;
22418         _this.windowTimeSpan = windowTimeSpan;
22419         _this.windowCreationInterval = windowCreationInterval;
22420         _this.maxWindowSize = maxWindowSize;
22421         _this.scheduler = scheduler;
22422         _this.windows = [];
22423         var window = _this.openWindow();
22424         if (windowCreationInterval !== null && windowCreationInterval >= 0) {
22425             var closeState = { subscriber: _this, window: window, context: null };
22426             var creationState = { windowTimeSpan: windowTimeSpan, windowCreationInterval: windowCreationInterval, subscriber: _this, scheduler: scheduler };
22427             _this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState));
22428             _this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState));
22429         }
22430         else {
22431             var timeSpanOnlyState = { subscriber: _this, window: window, windowTimeSpan: windowTimeSpan };
22432             _this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState));
22433         }
22434         return _this;
22435     }
22436     WindowTimeSubscriber.prototype._next = function (value) {
22437         var windows = this.windows;
22438         var len = windows.length;
22439         for (var i = 0; i < len; i++) {
22440             var window_1 = windows[i];
22441             if (!window_1.closed) {
22442                 window_1.next(value);
22443                 if (window_1.numberOfNextedValues >= this.maxWindowSize) {
22444                     this.closeWindow(window_1);
22445                 }
22446             }
22447         }
22448     };
22449     WindowTimeSubscriber.prototype._error = function (err) {
22450         var windows = this.windows;
22451         while (windows.length > 0) {
22452             windows.shift().error(err);
22453         }
22454         this.destination.error(err);
22455     };
22456     WindowTimeSubscriber.prototype._complete = function () {
22457         var windows = this.windows;
22458         while (windows.length > 0) {
22459             var window_2 = windows.shift();
22460             if (!window_2.closed) {
22461                 window_2.complete();
22462             }
22463         }
22464         this.destination.complete();
22465     };
22466     WindowTimeSubscriber.prototype.openWindow = function () {
22467         var window = new CountedSubject();
22468         this.windows.push(window);
22469         var destination = this.destination;
22470         destination.next(window);
22471         return window;
22472     };
22473     WindowTimeSubscriber.prototype.closeWindow = function (window) {
22474         window.complete();
22475         var windows = this.windows;
22476         windows.splice(windows.indexOf(window), 1);
22477     };
22478     return WindowTimeSubscriber;
22479 }(Subscriber_1.Subscriber));
22480 function dispatchWindowTimeSpanOnly(state) {
22481     var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, window = state.window;
22482     if (window) {
22483         subscriber.closeWindow(window);
22484     }
22485     state.window = subscriber.openWindow();
22486     this.schedule(state, windowTimeSpan);
22487 }
22488 function dispatchWindowCreation(state) {
22489     var windowTimeSpan = state.windowTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler, windowCreationInterval = state.windowCreationInterval;
22490     var window = subscriber.openWindow();
22491     var action = this;
22492     var context = { action: action, subscription: null };
22493     var timeSpanState = { subscriber: subscriber, window: window, context: context };
22494     context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState);
22495     action.add(context.subscription);
22496     action.schedule(state, windowCreationInterval);
22497 }
22498 function dispatchWindowClose(state) {
22499     var subscriber = state.subscriber, window = state.window, context = state.context;
22500     if (context && context.action && context.subscription) {
22501         context.action.remove(context.subscription);
22502     }
22503     subscriber.closeWindow(window);
22504 }
22505
22506 },{"../Subject":53,"../Subscriber":55,"../scheduler/async":204,"../util/isNumeric":225,"../util/isScheduler":229}],187:[function(require,module,exports){
22507 "use strict";
22508 var __extends = (this && this.__extends) || (function () {
22509     var extendStatics = function (d, b) {
22510         extendStatics = Object.setPrototypeOf ||
22511             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22512             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22513         return extendStatics(d, b);
22514     }
22515     return function (d, b) {
22516         extendStatics(d, b);
22517         function __() { this.constructor = d; }
22518         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22519     };
22520 })();
22521 Object.defineProperty(exports, "__esModule", { value: true });
22522 var Subject_1 = require("../Subject");
22523 var Subscription_1 = require("../Subscription");
22524 var tryCatch_1 = require("../util/tryCatch");
22525 var errorObject_1 = require("../util/errorObject");
22526 var OuterSubscriber_1 = require("../OuterSubscriber");
22527 var subscribeToResult_1 = require("../util/subscribeToResult");
22528 function windowToggle(openings, closingSelector) {
22529     return function (source) { return source.lift(new WindowToggleOperator(openings, closingSelector)); };
22530 }
22531 exports.windowToggle = windowToggle;
22532 var WindowToggleOperator = (function () {
22533     function WindowToggleOperator(openings, closingSelector) {
22534         this.openings = openings;
22535         this.closingSelector = closingSelector;
22536     }
22537     WindowToggleOperator.prototype.call = function (subscriber, source) {
22538         return source.subscribe(new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector));
22539     };
22540     return WindowToggleOperator;
22541 }());
22542 var WindowToggleSubscriber = (function (_super) {
22543     __extends(WindowToggleSubscriber, _super);
22544     function WindowToggleSubscriber(destination, openings, closingSelector) {
22545         var _this = _super.call(this, destination) || this;
22546         _this.openings = openings;
22547         _this.closingSelector = closingSelector;
22548         _this.contexts = [];
22549         _this.add(_this.openSubscription = subscribeToResult_1.subscribeToResult(_this, openings, openings));
22550         return _this;
22551     }
22552     WindowToggleSubscriber.prototype._next = function (value) {
22553         var contexts = this.contexts;
22554         if (contexts) {
22555             var len = contexts.length;
22556             for (var i = 0; i < len; i++) {
22557                 contexts[i].window.next(value);
22558             }
22559         }
22560     };
22561     WindowToggleSubscriber.prototype._error = function (err) {
22562         var contexts = this.contexts;
22563         this.contexts = null;
22564         if (contexts) {
22565             var len = contexts.length;
22566             var index = -1;
22567             while (++index < len) {
22568                 var context_1 = contexts[index];
22569                 context_1.window.error(err);
22570                 context_1.subscription.unsubscribe();
22571             }
22572         }
22573         _super.prototype._error.call(this, err);
22574     };
22575     WindowToggleSubscriber.prototype._complete = function () {
22576         var contexts = this.contexts;
22577         this.contexts = null;
22578         if (contexts) {
22579             var len = contexts.length;
22580             var index = -1;
22581             while (++index < len) {
22582                 var context_2 = contexts[index];
22583                 context_2.window.complete();
22584                 context_2.subscription.unsubscribe();
22585             }
22586         }
22587         _super.prototype._complete.call(this);
22588     };
22589     WindowToggleSubscriber.prototype._unsubscribe = function () {
22590         var contexts = this.contexts;
22591         this.contexts = null;
22592         if (contexts) {
22593             var len = contexts.length;
22594             var index = -1;
22595             while (++index < len) {
22596                 var context_3 = contexts[index];
22597                 context_3.window.unsubscribe();
22598                 context_3.subscription.unsubscribe();
22599             }
22600         }
22601     };
22602     WindowToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
22603         if (outerValue === this.openings) {
22604             var closingSelector = this.closingSelector;
22605             var closingNotifier = tryCatch_1.tryCatch(closingSelector)(innerValue);
22606             if (closingNotifier === errorObject_1.errorObject) {
22607                 return this.error(errorObject_1.errorObject.e);
22608             }
22609             else {
22610                 var window_1 = new Subject_1.Subject();
22611                 var subscription = new Subscription_1.Subscription();
22612                 var context_4 = { window: window_1, subscription: subscription };
22613                 this.contexts.push(context_4);
22614                 var innerSubscription = subscribeToResult_1.subscribeToResult(this, closingNotifier, context_4);
22615                 if (innerSubscription.closed) {
22616                     this.closeWindow(this.contexts.length - 1);
22617                 }
22618                 else {
22619                     innerSubscription.context = context_4;
22620                     subscription.add(innerSubscription);
22621                 }
22622                 this.destination.next(window_1);
22623             }
22624         }
22625         else {
22626             this.closeWindow(this.contexts.indexOf(outerValue));
22627         }
22628     };
22629     WindowToggleSubscriber.prototype.notifyError = function (err) {
22630         this.error(err);
22631     };
22632     WindowToggleSubscriber.prototype.notifyComplete = function (inner) {
22633         if (inner !== this.openSubscription) {
22634             this.closeWindow(this.contexts.indexOf(inner.context));
22635         }
22636     };
22637     WindowToggleSubscriber.prototype.closeWindow = function (index) {
22638         if (index === -1) {
22639             return;
22640         }
22641         var contexts = this.contexts;
22642         var context = contexts[index];
22643         var window = context.window, subscription = context.subscription;
22644         contexts.splice(index, 1);
22645         window.complete();
22646         subscription.unsubscribe();
22647     };
22648     return WindowToggleSubscriber;
22649 }(OuterSubscriber_1.OuterSubscriber));
22650
22651 },{"../OuterSubscriber":50,"../Subject":53,"../Subscription":56,"../util/errorObject":216,"../util/subscribeToResult":238,"../util/tryCatch":240}],188:[function(require,module,exports){
22652 "use strict";
22653 var __extends = (this && this.__extends) || (function () {
22654     var extendStatics = function (d, b) {
22655         extendStatics = Object.setPrototypeOf ||
22656             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22657             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22658         return extendStatics(d, b);
22659     }
22660     return function (d, b) {
22661         extendStatics(d, b);
22662         function __() { this.constructor = d; }
22663         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22664     };
22665 })();
22666 Object.defineProperty(exports, "__esModule", { value: true });
22667 var Subject_1 = require("../Subject");
22668 var tryCatch_1 = require("../util/tryCatch");
22669 var errorObject_1 = require("../util/errorObject");
22670 var OuterSubscriber_1 = require("../OuterSubscriber");
22671 var subscribeToResult_1 = require("../util/subscribeToResult");
22672 function windowWhen(closingSelector) {
22673     return function windowWhenOperatorFunction(source) {
22674         return source.lift(new WindowOperator(closingSelector));
22675     };
22676 }
22677 exports.windowWhen = windowWhen;
22678 var WindowOperator = (function () {
22679     function WindowOperator(closingSelector) {
22680         this.closingSelector = closingSelector;
22681     }
22682     WindowOperator.prototype.call = function (subscriber, source) {
22683         return source.subscribe(new WindowSubscriber(subscriber, this.closingSelector));
22684     };
22685     return WindowOperator;
22686 }());
22687 var WindowSubscriber = (function (_super) {
22688     __extends(WindowSubscriber, _super);
22689     function WindowSubscriber(destination, closingSelector) {
22690         var _this = _super.call(this, destination) || this;
22691         _this.destination = destination;
22692         _this.closingSelector = closingSelector;
22693         _this.openWindow();
22694         return _this;
22695     }
22696     WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
22697         this.openWindow(innerSub);
22698     };
22699     WindowSubscriber.prototype.notifyError = function (error, innerSub) {
22700         this._error(error);
22701     };
22702     WindowSubscriber.prototype.notifyComplete = function (innerSub) {
22703         this.openWindow(innerSub);
22704     };
22705     WindowSubscriber.prototype._next = function (value) {
22706         this.window.next(value);
22707     };
22708     WindowSubscriber.prototype._error = function (err) {
22709         this.window.error(err);
22710         this.destination.error(err);
22711         this.unsubscribeClosingNotification();
22712     };
22713     WindowSubscriber.prototype._complete = function () {
22714         this.window.complete();
22715         this.destination.complete();
22716         this.unsubscribeClosingNotification();
22717     };
22718     WindowSubscriber.prototype.unsubscribeClosingNotification = function () {
22719         if (this.closingNotification) {
22720             this.closingNotification.unsubscribe();
22721         }
22722     };
22723     WindowSubscriber.prototype.openWindow = function (innerSub) {
22724         if (innerSub === void 0) { innerSub = null; }
22725         if (innerSub) {
22726             this.remove(innerSub);
22727             innerSub.unsubscribe();
22728         }
22729         var prevWindow = this.window;
22730         if (prevWindow) {
22731             prevWindow.complete();
22732         }
22733         var window = this.window = new Subject_1.Subject();
22734         this.destination.next(window);
22735         var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
22736         if (closingNotifier === errorObject_1.errorObject) {
22737             var err = errorObject_1.errorObject.e;
22738             this.destination.error(err);
22739             this.window.error(err);
22740         }
22741         else {
22742             this.add(this.closingNotification = subscribeToResult_1.subscribeToResult(this, closingNotifier));
22743         }
22744     };
22745     return WindowSubscriber;
22746 }(OuterSubscriber_1.OuterSubscriber));
22747
22748 },{"../OuterSubscriber":50,"../Subject":53,"../util/errorObject":216,"../util/subscribeToResult":238,"../util/tryCatch":240}],189:[function(require,module,exports){
22749 "use strict";
22750 var __extends = (this && this.__extends) || (function () {
22751     var extendStatics = function (d, b) {
22752         extendStatics = Object.setPrototypeOf ||
22753             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22754             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22755         return extendStatics(d, b);
22756     }
22757     return function (d, b) {
22758         extendStatics(d, b);
22759         function __() { this.constructor = d; }
22760         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22761     };
22762 })();
22763 Object.defineProperty(exports, "__esModule", { value: true });
22764 var OuterSubscriber_1 = require("../OuterSubscriber");
22765 var subscribeToResult_1 = require("../util/subscribeToResult");
22766 function withLatestFrom() {
22767     var args = [];
22768     for (var _i = 0; _i < arguments.length; _i++) {
22769         args[_i] = arguments[_i];
22770     }
22771     return function (source) {
22772         var project;
22773         if (typeof args[args.length - 1] === 'function') {
22774             project = args.pop();
22775         }
22776         var observables = args;
22777         return source.lift(new WithLatestFromOperator(observables, project));
22778     };
22779 }
22780 exports.withLatestFrom = withLatestFrom;
22781 var WithLatestFromOperator = (function () {
22782     function WithLatestFromOperator(observables, project) {
22783         this.observables = observables;
22784         this.project = project;
22785     }
22786     WithLatestFromOperator.prototype.call = function (subscriber, source) {
22787         return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
22788     };
22789     return WithLatestFromOperator;
22790 }());
22791 var WithLatestFromSubscriber = (function (_super) {
22792     __extends(WithLatestFromSubscriber, _super);
22793     function WithLatestFromSubscriber(destination, observables, project) {
22794         var _this = _super.call(this, destination) || this;
22795         _this.observables = observables;
22796         _this.project = project;
22797         _this.toRespond = [];
22798         var len = observables.length;
22799         _this.values = new Array(len);
22800         for (var i = 0; i < len; i++) {
22801             _this.toRespond.push(i);
22802         }
22803         for (var i = 0; i < len; i++) {
22804             var observable = observables[i];
22805             _this.add(subscribeToResult_1.subscribeToResult(_this, observable, observable, i));
22806         }
22807         return _this;
22808     }
22809     WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
22810         this.values[outerIndex] = innerValue;
22811         var toRespond = this.toRespond;
22812         if (toRespond.length > 0) {
22813             var found = toRespond.indexOf(outerIndex);
22814             if (found !== -1) {
22815                 toRespond.splice(found, 1);
22816             }
22817         }
22818     };
22819     WithLatestFromSubscriber.prototype.notifyComplete = function () {
22820     };
22821     WithLatestFromSubscriber.prototype._next = function (value) {
22822         if (this.toRespond.length === 0) {
22823             var args = [value].concat(this.values);
22824             if (this.project) {
22825                 this._tryProject(args);
22826             }
22827             else {
22828                 this.destination.next(args);
22829             }
22830         }
22831     };
22832     WithLatestFromSubscriber.prototype._tryProject = function (args) {
22833         var result;
22834         try {
22835             result = this.project.apply(this, args);
22836         }
22837         catch (err) {
22838             this.destination.error(err);
22839             return;
22840         }
22841         this.destination.next(result);
22842     };
22843     return WithLatestFromSubscriber;
22844 }(OuterSubscriber_1.OuterSubscriber));
22845
22846 },{"../OuterSubscriber":50,"../util/subscribeToResult":238}],190:[function(require,module,exports){
22847 "use strict";
22848 Object.defineProperty(exports, "__esModule", { value: true });
22849 var zip_1 = require("../observable/zip");
22850 function zip() {
22851     var observables = [];
22852     for (var _i = 0; _i < arguments.length; _i++) {
22853         observables[_i] = arguments[_i];
22854     }
22855     return function zipOperatorFunction(source) {
22856         return source.lift.call(zip_1.zip.apply(void 0, [source].concat(observables)));
22857     };
22858 }
22859 exports.zip = zip;
22860
22861 },{"../observable/zip":88}],191:[function(require,module,exports){
22862 "use strict";
22863 Object.defineProperty(exports, "__esModule", { value: true });
22864 var zip_1 = require("../observable/zip");
22865 function zipAll(project) {
22866     return function (source) { return source.lift(new zip_1.ZipOperator(project)); };
22867 }
22868 exports.zipAll = zipAll;
22869
22870 },{"../observable/zip":88}],192:[function(require,module,exports){
22871 "use strict";
22872 var __extends = (this && this.__extends) || (function () {
22873     var extendStatics = function (d, b) {
22874         extendStatics = Object.setPrototypeOf ||
22875             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22876             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22877         return extendStatics(d, b);
22878     }
22879     return function (d, b) {
22880         extendStatics(d, b);
22881         function __() { this.constructor = d; }
22882         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22883     };
22884 })();
22885 Object.defineProperty(exports, "__esModule", { value: true });
22886 var Subscription_1 = require("../Subscription");
22887 var Action = (function (_super) {
22888     __extends(Action, _super);
22889     function Action(scheduler, work) {
22890         return _super.call(this) || this;
22891     }
22892     Action.prototype.schedule = function (state, delay) {
22893         if (delay === void 0) { delay = 0; }
22894         return this;
22895     };
22896     return Action;
22897 }(Subscription_1.Subscription));
22898 exports.Action = Action;
22899
22900 },{"../Subscription":56}],193:[function(require,module,exports){
22901 "use strict";
22902 var __extends = (this && this.__extends) || (function () {
22903     var extendStatics = function (d, b) {
22904         extendStatics = Object.setPrototypeOf ||
22905             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22906             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22907         return extendStatics(d, b);
22908     }
22909     return function (d, b) {
22910         extendStatics(d, b);
22911         function __() { this.constructor = d; }
22912         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22913     };
22914 })();
22915 Object.defineProperty(exports, "__esModule", { value: true });
22916 var AsyncAction_1 = require("./AsyncAction");
22917 var AnimationFrameAction = (function (_super) {
22918     __extends(AnimationFrameAction, _super);
22919     function AnimationFrameAction(scheduler, work) {
22920         var _this = _super.call(this, scheduler, work) || this;
22921         _this.scheduler = scheduler;
22922         _this.work = work;
22923         return _this;
22924     }
22925     AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) {
22926         if (delay === void 0) { delay = 0; }
22927         if (delay !== null && delay > 0) {
22928             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
22929         }
22930         scheduler.actions.push(this);
22931         return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(function () { return scheduler.flush(null); }));
22932     };
22933     AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
22934         if (delay === void 0) { delay = 0; }
22935         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
22936             return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
22937         }
22938         if (scheduler.actions.length === 0) {
22939             cancelAnimationFrame(id);
22940             scheduler.scheduled = undefined;
22941         }
22942         return undefined;
22943     };
22944     return AnimationFrameAction;
22945 }(AsyncAction_1.AsyncAction));
22946 exports.AnimationFrameAction = AnimationFrameAction;
22947
22948 },{"./AsyncAction":197}],194:[function(require,module,exports){
22949 "use strict";
22950 var __extends = (this && this.__extends) || (function () {
22951     var extendStatics = function (d, b) {
22952         extendStatics = Object.setPrototypeOf ||
22953             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22954             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22955         return extendStatics(d, b);
22956     }
22957     return function (d, b) {
22958         extendStatics(d, b);
22959         function __() { this.constructor = d; }
22960         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22961     };
22962 })();
22963 Object.defineProperty(exports, "__esModule", { value: true });
22964 var AsyncScheduler_1 = require("./AsyncScheduler");
22965 var AnimationFrameScheduler = (function (_super) {
22966     __extends(AnimationFrameScheduler, _super);
22967     function AnimationFrameScheduler() {
22968         return _super !== null && _super.apply(this, arguments) || this;
22969     }
22970     AnimationFrameScheduler.prototype.flush = function (action) {
22971         this.active = true;
22972         this.scheduled = undefined;
22973         var actions = this.actions;
22974         var error;
22975         var index = -1;
22976         var count = actions.length;
22977         action = action || actions.shift();
22978         do {
22979             if (error = action.execute(action.state, action.delay)) {
22980                 break;
22981             }
22982         } while (++index < count && (action = actions.shift()));
22983         this.active = false;
22984         if (error) {
22985             while (++index < count && (action = actions.shift())) {
22986                 action.unsubscribe();
22987             }
22988             throw error;
22989         }
22990     };
22991     return AnimationFrameScheduler;
22992 }(AsyncScheduler_1.AsyncScheduler));
22993 exports.AnimationFrameScheduler = AnimationFrameScheduler;
22994
22995 },{"./AsyncScheduler":198}],195:[function(require,module,exports){
22996 "use strict";
22997 var __extends = (this && this.__extends) || (function () {
22998     var extendStatics = function (d, b) {
22999         extendStatics = Object.setPrototypeOf ||
23000             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23001             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23002         return extendStatics(d, b);
23003     }
23004     return function (d, b) {
23005         extendStatics(d, b);
23006         function __() { this.constructor = d; }
23007         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23008     };
23009 })();
23010 Object.defineProperty(exports, "__esModule", { value: true });
23011 var Immediate_1 = require("../util/Immediate");
23012 var AsyncAction_1 = require("./AsyncAction");
23013 var AsapAction = (function (_super) {
23014     __extends(AsapAction, _super);
23015     function AsapAction(scheduler, work) {
23016         var _this = _super.call(this, scheduler, work) || this;
23017         _this.scheduler = scheduler;
23018         _this.work = work;
23019         return _this;
23020     }
23021     AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) {
23022         if (delay === void 0) { delay = 0; }
23023         if (delay !== null && delay > 0) {
23024             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
23025         }
23026         scheduler.actions.push(this);
23027         return scheduler.scheduled || (scheduler.scheduled = Immediate_1.Immediate.setImmediate(scheduler.flush.bind(scheduler, null)));
23028     };
23029     AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
23030         if (delay === void 0) { delay = 0; }
23031         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
23032             return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
23033         }
23034         if (scheduler.actions.length === 0) {
23035             Immediate_1.Immediate.clearImmediate(id);
23036             scheduler.scheduled = undefined;
23037         }
23038         return undefined;
23039     };
23040     return AsapAction;
23041 }(AsyncAction_1.AsyncAction));
23042 exports.AsapAction = AsapAction;
23043
23044 },{"../util/Immediate":211,"./AsyncAction":197}],196:[function(require,module,exports){
23045 "use strict";
23046 var __extends = (this && this.__extends) || (function () {
23047     var extendStatics = function (d, b) {
23048         extendStatics = Object.setPrototypeOf ||
23049             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23050             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23051         return extendStatics(d, b);
23052     }
23053     return function (d, b) {
23054         extendStatics(d, b);
23055         function __() { this.constructor = d; }
23056         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23057     };
23058 })();
23059 Object.defineProperty(exports, "__esModule", { value: true });
23060 var AsyncScheduler_1 = require("./AsyncScheduler");
23061 var AsapScheduler = (function (_super) {
23062     __extends(AsapScheduler, _super);
23063     function AsapScheduler() {
23064         return _super !== null && _super.apply(this, arguments) || this;
23065     }
23066     AsapScheduler.prototype.flush = function (action) {
23067         this.active = true;
23068         this.scheduled = undefined;
23069         var actions = this.actions;
23070         var error;
23071         var index = -1;
23072         var count = actions.length;
23073         action = action || actions.shift();
23074         do {
23075             if (error = action.execute(action.state, action.delay)) {
23076                 break;
23077             }
23078         } while (++index < count && (action = actions.shift()));
23079         this.active = false;
23080         if (error) {
23081             while (++index < count && (action = actions.shift())) {
23082                 action.unsubscribe();
23083             }
23084             throw error;
23085         }
23086     };
23087     return AsapScheduler;
23088 }(AsyncScheduler_1.AsyncScheduler));
23089 exports.AsapScheduler = AsapScheduler;
23090
23091 },{"./AsyncScheduler":198}],197:[function(require,module,exports){
23092 "use strict";
23093 var __extends = (this && this.__extends) || (function () {
23094     var extendStatics = function (d, b) {
23095         extendStatics = Object.setPrototypeOf ||
23096             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23097             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23098         return extendStatics(d, b);
23099     }
23100     return function (d, b) {
23101         extendStatics(d, b);
23102         function __() { this.constructor = d; }
23103         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23104     };
23105 })();
23106 Object.defineProperty(exports, "__esModule", { value: true });
23107 var Action_1 = require("./Action");
23108 var AsyncAction = (function (_super) {
23109     __extends(AsyncAction, _super);
23110     function AsyncAction(scheduler, work) {
23111         var _this = _super.call(this, scheduler, work) || this;
23112         _this.scheduler = scheduler;
23113         _this.work = work;
23114         _this.pending = false;
23115         return _this;
23116     }
23117     AsyncAction.prototype.schedule = function (state, delay) {
23118         if (delay === void 0) { delay = 0; }
23119         if (this.closed) {
23120             return this;
23121         }
23122         this.state = state;
23123         var id = this.id;
23124         var scheduler = this.scheduler;
23125         if (id != null) {
23126             this.id = this.recycleAsyncId(scheduler, id, delay);
23127         }
23128         this.pending = true;
23129         this.delay = delay;
23130         this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
23131         return this;
23132     };
23133     AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
23134         if (delay === void 0) { delay = 0; }
23135         return setInterval(scheduler.flush.bind(scheduler, this), delay);
23136     };
23137     AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
23138         if (delay === void 0) { delay = 0; }
23139         if (delay !== null && this.delay === delay && this.pending === false) {
23140             return id;
23141         }
23142         clearInterval(id);
23143     };
23144     AsyncAction.prototype.execute = function (state, delay) {
23145         if (this.closed) {
23146             return new Error('executing a cancelled action');
23147         }
23148         this.pending = false;
23149         var error = this._execute(state, delay);
23150         if (error) {
23151             return error;
23152         }
23153         else if (this.pending === false && this.id != null) {
23154             this.id = this.recycleAsyncId(this.scheduler, this.id, null);
23155         }
23156     };
23157     AsyncAction.prototype._execute = function (state, delay) {
23158         var errored = false;
23159         var errorValue = undefined;
23160         try {
23161             this.work(state);
23162         }
23163         catch (e) {
23164             errored = true;
23165             errorValue = !!e && e || new Error(e);
23166         }
23167         if (errored) {
23168             this.unsubscribe();
23169             return errorValue;
23170         }
23171     };
23172     AsyncAction.prototype._unsubscribe = function () {
23173         var id = this.id;
23174         var scheduler = this.scheduler;
23175         var actions = scheduler.actions;
23176         var index = actions.indexOf(this);
23177         this.work = null;
23178         this.state = null;
23179         this.pending = false;
23180         this.scheduler = null;
23181         if (index !== -1) {
23182             actions.splice(index, 1);
23183         }
23184         if (id != null) {
23185             this.id = this.recycleAsyncId(scheduler, id, null);
23186         }
23187         this.delay = null;
23188     };
23189     return AsyncAction;
23190 }(Action_1.Action));
23191 exports.AsyncAction = AsyncAction;
23192
23193 },{"./Action":192}],198:[function(require,module,exports){
23194 "use strict";
23195 var __extends = (this && this.__extends) || (function () {
23196     var extendStatics = function (d, b) {
23197         extendStatics = Object.setPrototypeOf ||
23198             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23199             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23200         return extendStatics(d, b);
23201     }
23202     return function (d, b) {
23203         extendStatics(d, b);
23204         function __() { this.constructor = d; }
23205         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23206     };
23207 })();
23208 Object.defineProperty(exports, "__esModule", { value: true });
23209 var Scheduler_1 = require("../Scheduler");
23210 var AsyncScheduler = (function (_super) {
23211     __extends(AsyncScheduler, _super);
23212     function AsyncScheduler(SchedulerAction, now) {
23213         if (now === void 0) { now = Scheduler_1.Scheduler.now; }
23214         var _this = _super.call(this, SchedulerAction, function () {
23215             if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) {
23216                 return AsyncScheduler.delegate.now();
23217             }
23218             else {
23219                 return now();
23220             }
23221         }) || this;
23222         _this.actions = [];
23223         _this.active = false;
23224         _this.scheduled = undefined;
23225         return _this;
23226     }
23227     AsyncScheduler.prototype.schedule = function (work, delay, state) {
23228         if (delay === void 0) { delay = 0; }
23229         if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
23230             return AsyncScheduler.delegate.schedule(work, delay, state);
23231         }
23232         else {
23233             return _super.prototype.schedule.call(this, work, delay, state);
23234         }
23235     };
23236     AsyncScheduler.prototype.flush = function (action) {
23237         var actions = this.actions;
23238         if (this.active) {
23239             actions.push(action);
23240             return;
23241         }
23242         var error;
23243         this.active = true;
23244         do {
23245             if (error = action.execute(action.state, action.delay)) {
23246                 break;
23247             }
23248         } while (action = actions.shift());
23249         this.active = false;
23250         if (error) {
23251             while (action = actions.shift()) {
23252                 action.unsubscribe();
23253             }
23254             throw error;
23255         }
23256     };
23257     return AsyncScheduler;
23258 }(Scheduler_1.Scheduler));
23259 exports.AsyncScheduler = AsyncScheduler;
23260
23261 },{"../Scheduler":52}],199:[function(require,module,exports){
23262 "use strict";
23263 var __extends = (this && this.__extends) || (function () {
23264     var extendStatics = function (d, b) {
23265         extendStatics = Object.setPrototypeOf ||
23266             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23267             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23268         return extendStatics(d, b);
23269     }
23270     return function (d, b) {
23271         extendStatics(d, b);
23272         function __() { this.constructor = d; }
23273         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23274     };
23275 })();
23276 Object.defineProperty(exports, "__esModule", { value: true });
23277 var AsyncAction_1 = require("./AsyncAction");
23278 var QueueAction = (function (_super) {
23279     __extends(QueueAction, _super);
23280     function QueueAction(scheduler, work) {
23281         var _this = _super.call(this, scheduler, work) || this;
23282         _this.scheduler = scheduler;
23283         _this.work = work;
23284         return _this;
23285     }
23286     QueueAction.prototype.schedule = function (state, delay) {
23287         if (delay === void 0) { delay = 0; }
23288         if (delay > 0) {
23289             return _super.prototype.schedule.call(this, state, delay);
23290         }
23291         this.delay = delay;
23292         this.state = state;
23293         this.scheduler.flush(this);
23294         return this;
23295     };
23296     QueueAction.prototype.execute = function (state, delay) {
23297         return (delay > 0 || this.closed) ?
23298             _super.prototype.execute.call(this, state, delay) :
23299             this._execute(state, delay);
23300     };
23301     QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
23302         if (delay === void 0) { delay = 0; }
23303         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
23304             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
23305         }
23306         return scheduler.flush(this);
23307     };
23308     return QueueAction;
23309 }(AsyncAction_1.AsyncAction));
23310 exports.QueueAction = QueueAction;
23311
23312 },{"./AsyncAction":197}],200:[function(require,module,exports){
23313 "use strict";
23314 var __extends = (this && this.__extends) || (function () {
23315     var extendStatics = function (d, b) {
23316         extendStatics = Object.setPrototypeOf ||
23317             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23318             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23319         return extendStatics(d, b);
23320     }
23321     return function (d, b) {
23322         extendStatics(d, b);
23323         function __() { this.constructor = d; }
23324         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23325     };
23326 })();
23327 Object.defineProperty(exports, "__esModule", { value: true });
23328 var AsyncScheduler_1 = require("./AsyncScheduler");
23329 var QueueScheduler = (function (_super) {
23330     __extends(QueueScheduler, _super);
23331     function QueueScheduler() {
23332         return _super !== null && _super.apply(this, arguments) || this;
23333     }
23334     return QueueScheduler;
23335 }(AsyncScheduler_1.AsyncScheduler));
23336 exports.QueueScheduler = QueueScheduler;
23337
23338 },{"./AsyncScheduler":198}],201:[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 AsyncAction_1 = require("./AsyncAction");
23355 var AsyncScheduler_1 = require("./AsyncScheduler");
23356 var VirtualTimeScheduler = (function (_super) {
23357     __extends(VirtualTimeScheduler, _super);
23358     function VirtualTimeScheduler(SchedulerAction, maxFrames) {
23359         if (SchedulerAction === void 0) { SchedulerAction = VirtualAction; }
23360         if (maxFrames === void 0) { maxFrames = Number.POSITIVE_INFINITY; }
23361         var _this = _super.call(this, SchedulerAction, function () { return _this.frame; }) || this;
23362         _this.maxFrames = maxFrames;
23363         _this.frame = 0;
23364         _this.index = -1;
23365         return _this;
23366     }
23367     VirtualTimeScheduler.prototype.flush = function () {
23368         var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
23369         var error, action;
23370         while ((action = actions.shift()) && (this.frame = action.delay) <= maxFrames) {
23371             if (error = action.execute(action.state, action.delay)) {
23372                 break;
23373             }
23374         }
23375         if (error) {
23376             while (action = actions.shift()) {
23377                 action.unsubscribe();
23378             }
23379             throw error;
23380         }
23381     };
23382     VirtualTimeScheduler.frameTimeFactor = 10;
23383     return VirtualTimeScheduler;
23384 }(AsyncScheduler_1.AsyncScheduler));
23385 exports.VirtualTimeScheduler = VirtualTimeScheduler;
23386 var VirtualAction = (function (_super) {
23387     __extends(VirtualAction, _super);
23388     function VirtualAction(scheduler, work, index) {
23389         if (index === void 0) { index = scheduler.index += 1; }
23390         var _this = _super.call(this, scheduler, work) || this;
23391         _this.scheduler = scheduler;
23392         _this.work = work;
23393         _this.index = index;
23394         _this.active = true;
23395         _this.index = scheduler.index = index;
23396         return _this;
23397     }
23398     VirtualAction.prototype.schedule = function (state, delay) {
23399         if (delay === void 0) { delay = 0; }
23400         if (!this.id) {
23401             return _super.prototype.schedule.call(this, state, delay);
23402         }
23403         this.active = false;
23404         var action = new VirtualAction(this.scheduler, this.work);
23405         this.add(action);
23406         return action.schedule(state, delay);
23407     };
23408     VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) {
23409         if (delay === void 0) { delay = 0; }
23410         this.delay = scheduler.frame + delay;
23411         var actions = scheduler.actions;
23412         actions.push(this);
23413         actions.sort(VirtualAction.sortActions);
23414         return true;
23415     };
23416     VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
23417         if (delay === void 0) { delay = 0; }
23418         return undefined;
23419     };
23420     VirtualAction.prototype._execute = function (state, delay) {
23421         if (this.active === true) {
23422             return _super.prototype._execute.call(this, state, delay);
23423         }
23424     };
23425     VirtualAction.sortActions = function (a, b) {
23426         if (a.delay === b.delay) {
23427             if (a.index === b.index) {
23428                 return 0;
23429             }
23430             else if (a.index > b.index) {
23431                 return 1;
23432             }
23433             else {
23434                 return -1;
23435             }
23436         }
23437         else if (a.delay > b.delay) {
23438             return 1;
23439         }
23440         else {
23441             return -1;
23442         }
23443     };
23444     return VirtualAction;
23445 }(AsyncAction_1.AsyncAction));
23446 exports.VirtualAction = VirtualAction;
23447
23448 },{"./AsyncAction":197,"./AsyncScheduler":198}],202:[function(require,module,exports){
23449 "use strict";
23450 Object.defineProperty(exports, "__esModule", { value: true });
23451 var AnimationFrameAction_1 = require("./AnimationFrameAction");
23452 var AnimationFrameScheduler_1 = require("./AnimationFrameScheduler");
23453 exports.animationFrame = new AnimationFrameScheduler_1.AnimationFrameScheduler(AnimationFrameAction_1.AnimationFrameAction);
23454
23455 },{"./AnimationFrameAction":193,"./AnimationFrameScheduler":194}],203:[function(require,module,exports){
23456 "use strict";
23457 Object.defineProperty(exports, "__esModule", { value: true });
23458 var AsapAction_1 = require("./AsapAction");
23459 var AsapScheduler_1 = require("./AsapScheduler");
23460 exports.asap = new AsapScheduler_1.AsapScheduler(AsapAction_1.AsapAction);
23461
23462 },{"./AsapAction":195,"./AsapScheduler":196}],204:[function(require,module,exports){
23463 "use strict";
23464 Object.defineProperty(exports, "__esModule", { value: true });
23465 var AsyncAction_1 = require("./AsyncAction");
23466 var AsyncScheduler_1 = require("./AsyncScheduler");
23467 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
23468
23469 },{"./AsyncAction":197,"./AsyncScheduler":198}],205:[function(require,module,exports){
23470 "use strict";
23471 Object.defineProperty(exports, "__esModule", { value: true });
23472 var QueueAction_1 = require("./QueueAction");
23473 var QueueScheduler_1 = require("./QueueScheduler");
23474 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
23475
23476 },{"./QueueAction":199,"./QueueScheduler":200}],206:[function(require,module,exports){
23477 "use strict";
23478 Object.defineProperty(exports, "__esModule", { value: true });
23479 function getSymbolIterator() {
23480     if (typeof Symbol !== 'function' || !Symbol.iterator) {
23481         return '@@iterator';
23482     }
23483     return Symbol.iterator;
23484 }
23485 exports.getSymbolIterator = getSymbolIterator;
23486 exports.iterator = getSymbolIterator();
23487 exports.$$iterator = exports.iterator;
23488
23489 },{}],207:[function(require,module,exports){
23490 "use strict";
23491 Object.defineProperty(exports, "__esModule", { value: true });
23492 exports.observable = typeof Symbol === 'function' && Symbol.observable || '@@observable';
23493
23494 },{}],208:[function(require,module,exports){
23495 "use strict";
23496 Object.defineProperty(exports, "__esModule", { value: true });
23497 exports.rxSubscriber = typeof Symbol === 'function'
23498     ? Symbol('rxSubscriber')
23499     : '@@rxSubscriber_' + Math.random();
23500 exports.$$rxSubscriber = exports.rxSubscriber;
23501
23502 },{}],209:[function(require,module,exports){
23503 "use strict";
23504 Object.defineProperty(exports, "__esModule", { value: true });
23505 function ArgumentOutOfRangeErrorImpl() {
23506     Error.call(this);
23507     this.message = 'argument out of range';
23508     this.name = 'ArgumentOutOfRangeError';
23509     return this;
23510 }
23511 ArgumentOutOfRangeErrorImpl.prototype = Object.create(Error.prototype);
23512 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;
23513
23514 },{}],210:[function(require,module,exports){
23515 "use strict";
23516 Object.defineProperty(exports, "__esModule", { value: true });
23517 function EmptyErrorImpl() {
23518     Error.call(this);
23519     this.message = 'no elements in sequence';
23520     this.name = 'EmptyError';
23521     return this;
23522 }
23523 EmptyErrorImpl.prototype = Object.create(Error.prototype);
23524 exports.EmptyError = EmptyErrorImpl;
23525
23526 },{}],211:[function(require,module,exports){
23527 "use strict";
23528 Object.defineProperty(exports, "__esModule", { value: true });
23529 var nextHandle = 1;
23530 var tasksByHandle = {};
23531 function runIfPresent(handle) {
23532     var cb = tasksByHandle[handle];
23533     if (cb) {
23534         cb();
23535     }
23536 }
23537 exports.Immediate = {
23538     setImmediate: function (cb) {
23539         var handle = nextHandle++;
23540         tasksByHandle[handle] = cb;
23541         Promise.resolve().then(function () { return runIfPresent(handle); });
23542         return handle;
23543     },
23544     clearImmediate: function (handle) {
23545         delete tasksByHandle[handle];
23546     },
23547 };
23548
23549 },{}],212:[function(require,module,exports){
23550 "use strict";
23551 Object.defineProperty(exports, "__esModule", { value: true });
23552 function ObjectUnsubscribedErrorImpl() {
23553     Error.call(this);
23554     this.message = 'object unsubscribed';
23555     this.name = 'ObjectUnsubscribedError';
23556     return this;
23557 }
23558 ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);
23559 exports.ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;
23560
23561 },{}],213:[function(require,module,exports){
23562 "use strict";
23563 Object.defineProperty(exports, "__esModule", { value: true });
23564 function TimeoutErrorImpl() {
23565     Error.call(this);
23566     this.message = 'Timeout has occurred';
23567     this.name = 'TimeoutError';
23568     return this;
23569 }
23570 TimeoutErrorImpl.prototype = Object.create(Error.prototype);
23571 exports.TimeoutError = TimeoutErrorImpl;
23572
23573 },{}],214:[function(require,module,exports){
23574 "use strict";
23575 Object.defineProperty(exports, "__esModule", { value: true });
23576 function UnsubscriptionErrorImpl(errors) {
23577     Error.call(this);
23578     this.message = errors ?
23579         errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n  ') : '';
23580     this.name = 'UnsubscriptionError';
23581     this.errors = errors;
23582     return this;
23583 }
23584 UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);
23585 exports.UnsubscriptionError = UnsubscriptionErrorImpl;
23586
23587 },{}],215:[function(require,module,exports){
23588 "use strict";
23589 Object.defineProperty(exports, "__esModule", { value: true });
23590 var Subscriber_1 = require("../Subscriber");
23591 function canReportError(observer) {
23592     while (observer) {
23593         var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;
23594         if (closed_1 || isStopped) {
23595             return false;
23596         }
23597         else if (destination && destination instanceof Subscriber_1.Subscriber) {
23598             observer = destination;
23599         }
23600         else {
23601             observer = null;
23602         }
23603     }
23604     return true;
23605 }
23606 exports.canReportError = canReportError;
23607
23608 },{"../Subscriber":55}],216:[function(require,module,exports){
23609 "use strict";
23610 Object.defineProperty(exports, "__esModule", { value: true });
23611 exports.errorObject = { e: {} };
23612
23613 },{}],217:[function(require,module,exports){
23614 "use strict";
23615 Object.defineProperty(exports, "__esModule", { value: true });
23616 function hostReportError(err) {
23617     setTimeout(function () { throw err; });
23618 }
23619 exports.hostReportError = hostReportError;
23620
23621 },{}],218:[function(require,module,exports){
23622 "use strict";
23623 Object.defineProperty(exports, "__esModule", { value: true });
23624 function identity(x) {
23625     return x;
23626 }
23627 exports.identity = identity;
23628
23629 },{}],219:[function(require,module,exports){
23630 "use strict";
23631 Object.defineProperty(exports, "__esModule", { value: true });
23632 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
23633
23634 },{}],220:[function(require,module,exports){
23635 "use strict";
23636 Object.defineProperty(exports, "__esModule", { value: true });
23637 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
23638
23639 },{}],221:[function(require,module,exports){
23640 "use strict";
23641 Object.defineProperty(exports, "__esModule", { value: true });
23642 function isDate(value) {
23643     return value instanceof Date && !isNaN(+value);
23644 }
23645 exports.isDate = isDate;
23646
23647 },{}],222:[function(require,module,exports){
23648 "use strict";
23649 Object.defineProperty(exports, "__esModule", { value: true });
23650 function isFunction(x) {
23651     return typeof x === 'function';
23652 }
23653 exports.isFunction = isFunction;
23654
23655 },{}],223:[function(require,module,exports){
23656 "use strict";
23657 Object.defineProperty(exports, "__esModule", { value: true });
23658 var observable_1 = require("../symbol/observable");
23659 function isInteropObservable(input) {
23660     return input && typeof input[observable_1.observable] === 'function';
23661 }
23662 exports.isInteropObservable = isInteropObservable;
23663
23664 },{"../symbol/observable":207}],224:[function(require,module,exports){
23665 "use strict";
23666 Object.defineProperty(exports, "__esModule", { value: true });
23667 var iterator_1 = require("../symbol/iterator");
23668 function isIterable(input) {
23669     return input && typeof input[iterator_1.iterator] === 'function';
23670 }
23671 exports.isIterable = isIterable;
23672
23673 },{"../symbol/iterator":206}],225:[function(require,module,exports){
23674 "use strict";
23675 Object.defineProperty(exports, "__esModule", { value: true });
23676 var isArray_1 = require("./isArray");
23677 function isNumeric(val) {
23678     return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
23679 }
23680 exports.isNumeric = isNumeric;
23681
23682 },{"./isArray":219}],226:[function(require,module,exports){
23683 "use strict";
23684 Object.defineProperty(exports, "__esModule", { value: true });
23685 function isObject(x) {
23686     return x != null && typeof x === 'object';
23687 }
23688 exports.isObject = isObject;
23689
23690 },{}],227:[function(require,module,exports){
23691 "use strict";
23692 Object.defineProperty(exports, "__esModule", { value: true });
23693 var Observable_1 = require("../Observable");
23694 function isObservable(obj) {
23695     return !!obj && (obj instanceof Observable_1.Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function'));
23696 }
23697 exports.isObservable = isObservable;
23698
23699 },{"../Observable":48}],228:[function(require,module,exports){
23700 "use strict";
23701 Object.defineProperty(exports, "__esModule", { value: true });
23702 function isPromise(value) {
23703     return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
23704 }
23705 exports.isPromise = isPromise;
23706
23707 },{}],229:[function(require,module,exports){
23708 "use strict";
23709 Object.defineProperty(exports, "__esModule", { value: true });
23710 function isScheduler(value) {
23711     return value && typeof value.schedule === 'function';
23712 }
23713 exports.isScheduler = isScheduler;
23714
23715 },{}],230:[function(require,module,exports){
23716 "use strict";
23717 Object.defineProperty(exports, "__esModule", { value: true });
23718 function noop() { }
23719 exports.noop = noop;
23720
23721 },{}],231:[function(require,module,exports){
23722 "use strict";
23723 Object.defineProperty(exports, "__esModule", { value: true });
23724 function not(pred, thisArg) {
23725     function notPred() {
23726         return !(notPred.pred.apply(notPred.thisArg, arguments));
23727     }
23728     notPred.pred = pred;
23729     notPred.thisArg = thisArg;
23730     return notPred;
23731 }
23732 exports.not = not;
23733
23734 },{}],232:[function(require,module,exports){
23735 "use strict";
23736 Object.defineProperty(exports, "__esModule", { value: true });
23737 var noop_1 = require("./noop");
23738 function pipe() {
23739     var fns = [];
23740     for (var _i = 0; _i < arguments.length; _i++) {
23741         fns[_i] = arguments[_i];
23742     }
23743     return pipeFromArray(fns);
23744 }
23745 exports.pipe = pipe;
23746 function pipeFromArray(fns) {
23747     if (!fns) {
23748         return noop_1.noop;
23749     }
23750     if (fns.length === 1) {
23751         return fns[0];
23752     }
23753     return function piped(input) {
23754         return fns.reduce(function (prev, fn) { return fn(prev); }, input);
23755     };
23756 }
23757 exports.pipeFromArray = pipeFromArray;
23758
23759 },{"./noop":230}],233:[function(require,module,exports){
23760 "use strict";
23761 Object.defineProperty(exports, "__esModule", { value: true });
23762 var Observable_1 = require("../Observable");
23763 var subscribeToArray_1 = require("./subscribeToArray");
23764 var subscribeToPromise_1 = require("./subscribeToPromise");
23765 var subscribeToIterable_1 = require("./subscribeToIterable");
23766 var subscribeToObservable_1 = require("./subscribeToObservable");
23767 var isArrayLike_1 = require("./isArrayLike");
23768 var isPromise_1 = require("./isPromise");
23769 var isObject_1 = require("./isObject");
23770 var iterator_1 = require("../symbol/iterator");
23771 var observable_1 = require("../symbol/observable");
23772 exports.subscribeTo = function (result) {
23773     if (result instanceof Observable_1.Observable) {
23774         return function (subscriber) {
23775             if (result._isScalar) {
23776                 subscriber.next(result.value);
23777                 subscriber.complete();
23778                 return undefined;
23779             }
23780             else {
23781                 return result.subscribe(subscriber);
23782             }
23783         };
23784     }
23785     else if (result && typeof result[observable_1.observable] === 'function') {
23786         return subscribeToObservable_1.subscribeToObservable(result);
23787     }
23788     else if (isArrayLike_1.isArrayLike(result)) {
23789         return subscribeToArray_1.subscribeToArray(result);
23790     }
23791     else if (isPromise_1.isPromise(result)) {
23792         return subscribeToPromise_1.subscribeToPromise(result);
23793     }
23794     else if (result && typeof result[iterator_1.iterator] === 'function') {
23795         return subscribeToIterable_1.subscribeToIterable(result);
23796     }
23797     else {
23798         var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
23799         var msg = "You provided " + value + " where a stream was expected."
23800             + ' You can provide an Observable, Promise, Array, or Iterable.';
23801         throw new TypeError(msg);
23802     }
23803 };
23804
23805 },{"../Observable":48,"../symbol/iterator":206,"../symbol/observable":207,"./isArrayLike":220,"./isObject":226,"./isPromise":228,"./subscribeToArray":234,"./subscribeToIterable":235,"./subscribeToObservable":236,"./subscribeToPromise":237}],234:[function(require,module,exports){
23806 "use strict";
23807 Object.defineProperty(exports, "__esModule", { value: true });
23808 exports.subscribeToArray = function (array) { return function (subscriber) {
23809     for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) {
23810         subscriber.next(array[i]);
23811     }
23812     if (!subscriber.closed) {
23813         subscriber.complete();
23814     }
23815 }; };
23816
23817 },{}],235:[function(require,module,exports){
23818 "use strict";
23819 Object.defineProperty(exports, "__esModule", { value: true });
23820 var iterator_1 = require("../symbol/iterator");
23821 exports.subscribeToIterable = function (iterable) { return function (subscriber) {
23822     var iterator = iterable[iterator_1.iterator]();
23823     do {
23824         var item = iterator.next();
23825         if (item.done) {
23826             subscriber.complete();
23827             break;
23828         }
23829         subscriber.next(item.value);
23830         if (subscriber.closed) {
23831             break;
23832         }
23833     } while (true);
23834     if (typeof iterator.return === 'function') {
23835         subscriber.add(function () {
23836             if (iterator.return) {
23837                 iterator.return();
23838             }
23839         });
23840     }
23841     return subscriber;
23842 }; };
23843
23844 },{"../symbol/iterator":206}],236:[function(require,module,exports){
23845 "use strict";
23846 Object.defineProperty(exports, "__esModule", { value: true });
23847 var observable_1 = require("../symbol/observable");
23848 exports.subscribeToObservable = function (obj) { return function (subscriber) {
23849     var obs = obj[observable_1.observable]();
23850     if (typeof obs.subscribe !== 'function') {
23851         throw new TypeError('Provided object does not correctly implement Symbol.observable');
23852     }
23853     else {
23854         return obs.subscribe(subscriber);
23855     }
23856 }; };
23857
23858 },{"../symbol/observable":207}],237:[function(require,module,exports){
23859 "use strict";
23860 Object.defineProperty(exports, "__esModule", { value: true });
23861 var hostReportError_1 = require("./hostReportError");
23862 exports.subscribeToPromise = function (promise) { return function (subscriber) {
23863     promise.then(function (value) {
23864         if (!subscriber.closed) {
23865             subscriber.next(value);
23866             subscriber.complete();
23867         }
23868     }, function (err) { return subscriber.error(err); })
23869         .then(null, hostReportError_1.hostReportError);
23870     return subscriber;
23871 }; };
23872
23873 },{"./hostReportError":217}],238:[function(require,module,exports){
23874 "use strict";
23875 Object.defineProperty(exports, "__esModule", { value: true });
23876 var InnerSubscriber_1 = require("../InnerSubscriber");
23877 var subscribeTo_1 = require("./subscribeTo");
23878 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, destination) {
23879     if (destination === void 0) { destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex); }
23880     if (destination.closed) {
23881         return;
23882     }
23883     return subscribeTo_1.subscribeTo(result)(destination);
23884 }
23885 exports.subscribeToResult = subscribeToResult;
23886
23887 },{"../InnerSubscriber":46,"./subscribeTo":233}],239:[function(require,module,exports){
23888 "use strict";
23889 Object.defineProperty(exports, "__esModule", { value: true });
23890 var Subscriber_1 = require("../Subscriber");
23891 var rxSubscriber_1 = require("../symbol/rxSubscriber");
23892 var Observer_1 = require("../Observer");
23893 function toSubscriber(nextOrObserver, error, complete) {
23894     if (nextOrObserver) {
23895         if (nextOrObserver instanceof Subscriber_1.Subscriber) {
23896             return nextOrObserver;
23897         }
23898         if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
23899             return nextOrObserver[rxSubscriber_1.rxSubscriber]();
23900         }
23901     }
23902     if (!nextOrObserver && !error && !complete) {
23903         return new Subscriber_1.Subscriber(Observer_1.empty);
23904     }
23905     return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
23906 }
23907 exports.toSubscriber = toSubscriber;
23908
23909 },{"../Observer":49,"../Subscriber":55,"../symbol/rxSubscriber":208}],240:[function(require,module,exports){
23910 "use strict";
23911 Object.defineProperty(exports, "__esModule", { value: true });
23912 var errorObject_1 = require("./errorObject");
23913 var tryCatchTarget;
23914 function tryCatcher() {
23915     try {
23916         return tryCatchTarget.apply(this, arguments);
23917     }
23918     catch (e) {
23919         errorObject_1.errorObject.e = e;
23920         return errorObject_1.errorObject;
23921     }
23922 }
23923 function tryCatch(fn) {
23924     tryCatchTarget = fn;
23925     return tryCatcher;
23926 }
23927 exports.tryCatch = tryCatch;
23928
23929 },{"./errorObject":216}],241:[function(require,module,exports){
23930 "use strict";
23931 Object.defineProperty(exports, "__esModule", { value: true });
23932 var audit_1 = require("../internal/operators/audit");
23933 exports.audit = audit_1.audit;
23934 var auditTime_1 = require("../internal/operators/auditTime");
23935 exports.auditTime = auditTime_1.auditTime;
23936 var buffer_1 = require("../internal/operators/buffer");
23937 exports.buffer = buffer_1.buffer;
23938 var bufferCount_1 = require("../internal/operators/bufferCount");
23939 exports.bufferCount = bufferCount_1.bufferCount;
23940 var bufferTime_1 = require("../internal/operators/bufferTime");
23941 exports.bufferTime = bufferTime_1.bufferTime;
23942 var bufferToggle_1 = require("../internal/operators/bufferToggle");
23943 exports.bufferToggle = bufferToggle_1.bufferToggle;
23944 var bufferWhen_1 = require("../internal/operators/bufferWhen");
23945 exports.bufferWhen = bufferWhen_1.bufferWhen;
23946 var catchError_1 = require("../internal/operators/catchError");
23947 exports.catchError = catchError_1.catchError;
23948 var combineAll_1 = require("../internal/operators/combineAll");
23949 exports.combineAll = combineAll_1.combineAll;
23950 var combineLatest_1 = require("../internal/operators/combineLatest");
23951 exports.combineLatest = combineLatest_1.combineLatest;
23952 var concat_1 = require("../internal/operators/concat");
23953 exports.concat = concat_1.concat;
23954 var concatAll_1 = require("../internal/operators/concatAll");
23955 exports.concatAll = concatAll_1.concatAll;
23956 var concatMap_1 = require("../internal/operators/concatMap");
23957 exports.concatMap = concatMap_1.concatMap;
23958 var concatMapTo_1 = require("../internal/operators/concatMapTo");
23959 exports.concatMapTo = concatMapTo_1.concatMapTo;
23960 var count_1 = require("../internal/operators/count");
23961 exports.count = count_1.count;
23962 var debounce_1 = require("../internal/operators/debounce");
23963 exports.debounce = debounce_1.debounce;
23964 var debounceTime_1 = require("../internal/operators/debounceTime");
23965 exports.debounceTime = debounceTime_1.debounceTime;
23966 var defaultIfEmpty_1 = require("../internal/operators/defaultIfEmpty");
23967 exports.defaultIfEmpty = defaultIfEmpty_1.defaultIfEmpty;
23968 var delay_1 = require("../internal/operators/delay");
23969 exports.delay = delay_1.delay;
23970 var delayWhen_1 = require("../internal/operators/delayWhen");
23971 exports.delayWhen = delayWhen_1.delayWhen;
23972 var dematerialize_1 = require("../internal/operators/dematerialize");
23973 exports.dematerialize = dematerialize_1.dematerialize;
23974 var distinct_1 = require("../internal/operators/distinct");
23975 exports.distinct = distinct_1.distinct;
23976 var distinctUntilChanged_1 = require("../internal/operators/distinctUntilChanged");
23977 exports.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
23978 var distinctUntilKeyChanged_1 = require("../internal/operators/distinctUntilKeyChanged");
23979 exports.distinctUntilKeyChanged = distinctUntilKeyChanged_1.distinctUntilKeyChanged;
23980 var elementAt_1 = require("../internal/operators/elementAt");
23981 exports.elementAt = elementAt_1.elementAt;
23982 var endWith_1 = require("../internal/operators/endWith");
23983 exports.endWith = endWith_1.endWith;
23984 var every_1 = require("../internal/operators/every");
23985 exports.every = every_1.every;
23986 var exhaust_1 = require("../internal/operators/exhaust");
23987 exports.exhaust = exhaust_1.exhaust;
23988 var exhaustMap_1 = require("../internal/operators/exhaustMap");
23989 exports.exhaustMap = exhaustMap_1.exhaustMap;
23990 var expand_1 = require("../internal/operators/expand");
23991 exports.expand = expand_1.expand;
23992 var filter_1 = require("../internal/operators/filter");
23993 exports.filter = filter_1.filter;
23994 var finalize_1 = require("../internal/operators/finalize");
23995 exports.finalize = finalize_1.finalize;
23996 var find_1 = require("../internal/operators/find");
23997 exports.find = find_1.find;
23998 var findIndex_1 = require("../internal/operators/findIndex");
23999 exports.findIndex = findIndex_1.findIndex;
24000 var first_1 = require("../internal/operators/first");
24001 exports.first = first_1.first;
24002 var groupBy_1 = require("../internal/operators/groupBy");
24003 exports.groupBy = groupBy_1.groupBy;
24004 var ignoreElements_1 = require("../internal/operators/ignoreElements");
24005 exports.ignoreElements = ignoreElements_1.ignoreElements;
24006 var isEmpty_1 = require("../internal/operators/isEmpty");
24007 exports.isEmpty = isEmpty_1.isEmpty;
24008 var last_1 = require("../internal/operators/last");
24009 exports.last = last_1.last;
24010 var map_1 = require("../internal/operators/map");
24011 exports.map = map_1.map;
24012 var mapTo_1 = require("../internal/operators/mapTo");
24013 exports.mapTo = mapTo_1.mapTo;
24014 var materialize_1 = require("../internal/operators/materialize");
24015 exports.materialize = materialize_1.materialize;
24016 var max_1 = require("../internal/operators/max");
24017 exports.max = max_1.max;
24018 var merge_1 = require("../internal/operators/merge");
24019 exports.merge = merge_1.merge;
24020 var mergeAll_1 = require("../internal/operators/mergeAll");
24021 exports.mergeAll = mergeAll_1.mergeAll;
24022 var mergeMap_1 = require("../internal/operators/mergeMap");
24023 exports.mergeMap = mergeMap_1.mergeMap;
24024 var mergeMap_2 = require("../internal/operators/mergeMap");
24025 exports.flatMap = mergeMap_2.mergeMap;
24026 var mergeMapTo_1 = require("../internal/operators/mergeMapTo");
24027 exports.mergeMapTo = mergeMapTo_1.mergeMapTo;
24028 var mergeScan_1 = require("../internal/operators/mergeScan");
24029 exports.mergeScan = mergeScan_1.mergeScan;
24030 var min_1 = require("../internal/operators/min");
24031 exports.min = min_1.min;
24032 var multicast_1 = require("../internal/operators/multicast");
24033 exports.multicast = multicast_1.multicast;
24034 var observeOn_1 = require("../internal/operators/observeOn");
24035 exports.observeOn = observeOn_1.observeOn;
24036 var onErrorResumeNext_1 = require("../internal/operators/onErrorResumeNext");
24037 exports.onErrorResumeNext = onErrorResumeNext_1.onErrorResumeNext;
24038 var pairwise_1 = require("../internal/operators/pairwise");
24039 exports.pairwise = pairwise_1.pairwise;
24040 var partition_1 = require("../internal/operators/partition");
24041 exports.partition = partition_1.partition;
24042 var pluck_1 = require("../internal/operators/pluck");
24043 exports.pluck = pluck_1.pluck;
24044 var publish_1 = require("../internal/operators/publish");
24045 exports.publish = publish_1.publish;
24046 var publishBehavior_1 = require("../internal/operators/publishBehavior");
24047 exports.publishBehavior = publishBehavior_1.publishBehavior;
24048 var publishLast_1 = require("../internal/operators/publishLast");
24049 exports.publishLast = publishLast_1.publishLast;
24050 var publishReplay_1 = require("../internal/operators/publishReplay");
24051 exports.publishReplay = publishReplay_1.publishReplay;
24052 var race_1 = require("../internal/operators/race");
24053 exports.race = race_1.race;
24054 var reduce_1 = require("../internal/operators/reduce");
24055 exports.reduce = reduce_1.reduce;
24056 var repeat_1 = require("../internal/operators/repeat");
24057 exports.repeat = repeat_1.repeat;
24058 var repeatWhen_1 = require("../internal/operators/repeatWhen");
24059 exports.repeatWhen = repeatWhen_1.repeatWhen;
24060 var retry_1 = require("../internal/operators/retry");
24061 exports.retry = retry_1.retry;
24062 var retryWhen_1 = require("../internal/operators/retryWhen");
24063 exports.retryWhen = retryWhen_1.retryWhen;
24064 var refCount_1 = require("../internal/operators/refCount");
24065 exports.refCount = refCount_1.refCount;
24066 var sample_1 = require("../internal/operators/sample");
24067 exports.sample = sample_1.sample;
24068 var sampleTime_1 = require("../internal/operators/sampleTime");
24069 exports.sampleTime = sampleTime_1.sampleTime;
24070 var scan_1 = require("../internal/operators/scan");
24071 exports.scan = scan_1.scan;
24072 var sequenceEqual_1 = require("../internal/operators/sequenceEqual");
24073 exports.sequenceEqual = sequenceEqual_1.sequenceEqual;
24074 var share_1 = require("../internal/operators/share");
24075 exports.share = share_1.share;
24076 var shareReplay_1 = require("../internal/operators/shareReplay");
24077 exports.shareReplay = shareReplay_1.shareReplay;
24078 var single_1 = require("../internal/operators/single");
24079 exports.single = single_1.single;
24080 var skip_1 = require("../internal/operators/skip");
24081 exports.skip = skip_1.skip;
24082 var skipLast_1 = require("../internal/operators/skipLast");
24083 exports.skipLast = skipLast_1.skipLast;
24084 var skipUntil_1 = require("../internal/operators/skipUntil");
24085 exports.skipUntil = skipUntil_1.skipUntil;
24086 var skipWhile_1 = require("../internal/operators/skipWhile");
24087 exports.skipWhile = skipWhile_1.skipWhile;
24088 var startWith_1 = require("../internal/operators/startWith");
24089 exports.startWith = startWith_1.startWith;
24090 var subscribeOn_1 = require("../internal/operators/subscribeOn");
24091 exports.subscribeOn = subscribeOn_1.subscribeOn;
24092 var switchAll_1 = require("../internal/operators/switchAll");
24093 exports.switchAll = switchAll_1.switchAll;
24094 var switchMap_1 = require("../internal/operators/switchMap");
24095 exports.switchMap = switchMap_1.switchMap;
24096 var switchMapTo_1 = require("../internal/operators/switchMapTo");
24097 exports.switchMapTo = switchMapTo_1.switchMapTo;
24098 var take_1 = require("../internal/operators/take");
24099 exports.take = take_1.take;
24100 var takeLast_1 = require("../internal/operators/takeLast");
24101 exports.takeLast = takeLast_1.takeLast;
24102 var takeUntil_1 = require("../internal/operators/takeUntil");
24103 exports.takeUntil = takeUntil_1.takeUntil;
24104 var takeWhile_1 = require("../internal/operators/takeWhile");
24105 exports.takeWhile = takeWhile_1.takeWhile;
24106 var tap_1 = require("../internal/operators/tap");
24107 exports.tap = tap_1.tap;
24108 var throttle_1 = require("../internal/operators/throttle");
24109 exports.throttle = throttle_1.throttle;
24110 var throttleTime_1 = require("../internal/operators/throttleTime");
24111 exports.throttleTime = throttleTime_1.throttleTime;
24112 var throwIfEmpty_1 = require("../internal/operators/throwIfEmpty");
24113 exports.throwIfEmpty = throwIfEmpty_1.throwIfEmpty;
24114 var timeInterval_1 = require("../internal/operators/timeInterval");
24115 exports.timeInterval = timeInterval_1.timeInterval;
24116 var timeout_1 = require("../internal/operators/timeout");
24117 exports.timeout = timeout_1.timeout;
24118 var timeoutWith_1 = require("../internal/operators/timeoutWith");
24119 exports.timeoutWith = timeoutWith_1.timeoutWith;
24120 var timestamp_1 = require("../internal/operators/timestamp");
24121 exports.timestamp = timestamp_1.timestamp;
24122 var toArray_1 = require("../internal/operators/toArray");
24123 exports.toArray = toArray_1.toArray;
24124 var window_1 = require("../internal/operators/window");
24125 exports.window = window_1.window;
24126 var windowCount_1 = require("../internal/operators/windowCount");
24127 exports.windowCount = windowCount_1.windowCount;
24128 var windowTime_1 = require("../internal/operators/windowTime");
24129 exports.windowTime = windowTime_1.windowTime;
24130 var windowToggle_1 = require("../internal/operators/windowToggle");
24131 exports.windowToggle = windowToggle_1.windowToggle;
24132 var windowWhen_1 = require("../internal/operators/windowWhen");
24133 exports.windowWhen = windowWhen_1.windowWhen;
24134 var withLatestFrom_1 = require("../internal/operators/withLatestFrom");
24135 exports.withLatestFrom = withLatestFrom_1.withLatestFrom;
24136 var zip_1 = require("../internal/operators/zip");
24137 exports.zip = zip_1.zip;
24138 var zipAll_1 = require("../internal/operators/zipAll");
24139 exports.zipAll = zipAll_1.zipAll;
24140
24141 },{"../internal/operators/audit":89,"../internal/operators/auditTime":90,"../internal/operators/buffer":91,"../internal/operators/bufferCount":92,"../internal/operators/bufferTime":93,"../internal/operators/bufferToggle":94,"../internal/operators/bufferWhen":95,"../internal/operators/catchError":96,"../internal/operators/combineAll":97,"../internal/operators/combineLatest":98,"../internal/operators/concat":99,"../internal/operators/concatAll":100,"../internal/operators/concatMap":101,"../internal/operators/concatMapTo":102,"../internal/operators/count":103,"../internal/operators/debounce":104,"../internal/operators/debounceTime":105,"../internal/operators/defaultIfEmpty":106,"../internal/operators/delay":107,"../internal/operators/delayWhen":108,"../internal/operators/dematerialize":109,"../internal/operators/distinct":110,"../internal/operators/distinctUntilChanged":111,"../internal/operators/distinctUntilKeyChanged":112,"../internal/operators/elementAt":113,"../internal/operators/endWith":114,"../internal/operators/every":115,"../internal/operators/exhaust":116,"../internal/operators/exhaustMap":117,"../internal/operators/expand":118,"../internal/operators/filter":119,"../internal/operators/finalize":120,"../internal/operators/find":121,"../internal/operators/findIndex":122,"../internal/operators/first":123,"../internal/operators/groupBy":124,"../internal/operators/ignoreElements":125,"../internal/operators/isEmpty":126,"../internal/operators/last":127,"../internal/operators/map":128,"../internal/operators/mapTo":129,"../internal/operators/materialize":130,"../internal/operators/max":131,"../internal/operators/merge":132,"../internal/operators/mergeAll":133,"../internal/operators/mergeMap":134,"../internal/operators/mergeMapTo":135,"../internal/operators/mergeScan":136,"../internal/operators/min":137,"../internal/operators/multicast":138,"../internal/operators/observeOn":139,"../internal/operators/onErrorResumeNext":140,"../internal/operators/pairwise":141,"../internal/operators/partition":142,"../internal/operators/pluck":143,"../internal/operators/publish":144,"../internal/operators/publishBehavior":145,"../internal/operators/publishLast":146,"../internal/operators/publishReplay":147,"../internal/operators/race":148,"../internal/operators/reduce":149,"../internal/operators/refCount":150,"../internal/operators/repeat":151,"../internal/operators/repeatWhen":152,"../internal/operators/retry":153,"../internal/operators/retryWhen":154,"../internal/operators/sample":155,"../internal/operators/sampleTime":156,"../internal/operators/scan":157,"../internal/operators/sequenceEqual":158,"../internal/operators/share":159,"../internal/operators/shareReplay":160,"../internal/operators/single":161,"../internal/operators/skip":162,"../internal/operators/skipLast":163,"../internal/operators/skipUntil":164,"../internal/operators/skipWhile":165,"../internal/operators/startWith":166,"../internal/operators/subscribeOn":167,"../internal/operators/switchAll":168,"../internal/operators/switchMap":169,"../internal/operators/switchMapTo":170,"../internal/operators/take":171,"../internal/operators/takeLast":172,"../internal/operators/takeUntil":173,"../internal/operators/takeWhile":174,"../internal/operators/tap":175,"../internal/operators/throttle":176,"../internal/operators/throttleTime":177,"../internal/operators/throwIfEmpty":178,"../internal/operators/timeInterval":179,"../internal/operators/timeout":180,"../internal/operators/timeoutWith":181,"../internal/operators/timestamp":182,"../internal/operators/toArray":183,"../internal/operators/window":184,"../internal/operators/windowCount":185,"../internal/operators/windowTime":186,"../internal/operators/windowToggle":187,"../internal/operators/windowWhen":188,"../internal/operators/withLatestFrom":189,"../internal/operators/zip":190,"../internal/operators/zipAll":191}],242:[function(require,module,exports){
24142 // threejs.org/license
24143 (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,
24144 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!==
24145 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,
24146 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?
24147 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!==
24148 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),
24149 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
24150 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);
24151 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=
24152 -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,
24153 {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=
24154 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,
24155 "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.");
24156 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,
24157 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;
24158 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,
24159 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+=
24160 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",
24161 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=
24162 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=
24163 !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;
24164 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=
24165 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=
24166 {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=
24167 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,
24168 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)},
24169 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"),
24170 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"===
24171 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),
24172 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,
24173 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===
24174 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=
24175 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;
24176 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");
24177 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?
24178 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!==
24179 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=
24180 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++;
24181 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);
24182 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"+
24183 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),
24184 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]!==
24185 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,
24186 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,
24187 !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||
24188 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;
24189 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,
24190 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,
24191 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;
24192 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=
24193 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.");
24194 ""!==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: "+
24195 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||
24196 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=
24197 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,
24198 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&&
24199 (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=
24200 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":
24201 "",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":
24202 "",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 "+
24203 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;",
24204 "#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",
24205 "#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 "+
24206 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?
24207 "#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&&
24208 (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",
24209 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"+
24210 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")+
24211 "\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",
24212 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),
24213 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=
24214 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",
24215 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(" ");
24216 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."));
24217 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,
24218 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,
24219 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,
24220 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<
24221 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!==
24222 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,
24223 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=
24224 {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};
24225 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,
24226 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=
24227 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);
24228 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,
24229 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;
24230 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=
24231 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]?
24232 (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=
24233 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)),
24234 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;
24235 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,
24236 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),
24237 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);
24238 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());
24239 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,
24240 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":
24241 "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,
24242 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,
24243 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);
24244 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;
24245 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);
24246 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!==
24247 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]),
24248 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,
24249 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!==
24250 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!==
24251 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:",
24252 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+").");
24253 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!==
24254 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=
24255 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=
24256 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");
24257 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);
24258 (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+
24259 "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=
24260 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,
24261 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=
24262 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)),
24263 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."));
24264 !(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);
24265 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,
24266 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);
24267 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+
24268 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+
24269 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=
24270 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),
24271 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&&
24272 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");
24273 }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;
24274 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;
24275 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===
24276 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===
24277 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;
24278 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===
24279 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;
24280 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=
24281 [],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]=
24282 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!==
24283 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);
24284 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),
24285 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;
24286 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"}),
24287 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);
24288 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};
24289 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(),
24290 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),
24291 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=
24292 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");
24293 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();
24294 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||
24295 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=
24296 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*
24297 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,
24298 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=
24299 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,
24300 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=
24301 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=
24302 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,
24303 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=
24304 !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));
24305 (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=
24306 !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=
24307 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,
24308 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,
24309 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=
24310 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&&
24311 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,
24312 "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=
24313 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),
24314 !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,
24315 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),
24316 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!==
24317 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=
24318 !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);
24319 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,
24320 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!==
24321 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)};
24322 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,
24323 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",
24324 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),
24325 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,
24326 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&&
24327 (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,
24328 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===
24329 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*
24330 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?
24331 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,
24332 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));
24333 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=
24334 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};
24335 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&&
24336 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=
24337 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=
24338 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")||
24339 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&&
24340 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,
24341 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=
24342 {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",
24343 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."),
24344 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;
24345 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=
24346 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,
24347 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=
24348 [],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,
24349 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,
24350 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.");
24351 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",
24352 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,
24353 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=
24354 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],
24355 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,
24356 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,
24357 -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,
24358 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,
24359 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,
24360 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=
24361 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=
24362 (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,
24363 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;
24364 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);
24365 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)||
24366 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",
24367 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}
24368 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;
24369 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=
24370 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,
24371 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,
24372 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,
24373 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-
24374 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=
24375 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),
24376 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;
24377 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);
24378 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?
24379 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;
24380 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],
24381 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=
24382 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=
24383 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=
24384 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()}
24385 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,
24386 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,
24387 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",
24388 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;
24389 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",
24390 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=
24391 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=
24392 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;
24393 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);
24394 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=
24395 ["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],
24396 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=
24397 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)||
24398 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),
24399 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=
24400 {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=
24401 [],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)}
24402 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=
24403 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);
24404 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;
24405 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=
24406 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=
24407 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,
24408 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}
24409 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,
24410 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)*
24411 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||
24412 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);
24413 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=
24414 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,
24415 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,
24416 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,
24417 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,
24418 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;
24419 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!==
24420 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.");
24421 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=
24422 !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);
24423 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,
24424 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=
24425 !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=
24426 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=
24427 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=
24428 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;
24429 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,
24430 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],
24431 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=
24432 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();
24433 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}
24434 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();
24435 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();
24436 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,
24437 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,
24438 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)&&
24439 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,
24440 -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);
24441 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&&
24442 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,
24443 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,
24444 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}));
24445 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.");
24446 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)===
24447 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,
24448 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!==
24449 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>>
24450 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;
24451 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)/
24452 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: "+
24453 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},
24454 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*=
24455 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,
24456 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=
24457 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)+
24458 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+=
24459 (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);
24460 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)},
24461 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,
24462 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.");
24463 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]=
24464 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=
24465 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!==
24466 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],
24467 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]*=
24468 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-
24469 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],
24470 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*
24471 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)*
24472 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=
24473 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,
24474 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;
24475 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);
24476 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]=
24477 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];
24478 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*
24479 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=
24480 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=
24481 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+
24482 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/
24483 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,
24484 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*
24485 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."),
24486 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;
24487 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===
24488 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},
24489 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,
24490 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+=
24491 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."),
24492 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,
24493 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,
24494 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=
24495 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,
24496 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=
24497 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*
24498 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,
24499 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=
24500 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-
24501 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(),
24502 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!==
24503 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;
24504 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,
24505 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]*=
24506 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");
24507 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=
24508 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]=
24509 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];
24510 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",
24511 .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=
24512 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=
24513 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!==
24514 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);
24515 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=
24516 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;
24517 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+=
24518 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-=
24519 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/
24520 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;
24521 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,
24522 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,
24523 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);
24524 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*
24525 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,
24526 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().");
24527 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();
24528 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=
24529 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);
24530 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},
24531 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"),
24532 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&&
24533 (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&&
24534 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,
24535 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;
24536 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=
24537 [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=
24538 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=
24539 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];
24540 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=
24541 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;
24542 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===
24543 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,
24544 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=
24545 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=
24546 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)},
24547 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);
24548 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],
24549 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();
24550 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];
24551 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",
24552 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",
24553 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",
24554 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",
24555 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",
24556 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",
24557 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",
24558 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",
24559 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",
24560 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",
24561 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",
24562 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",
24563 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",
24564 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",
24565 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",
24566 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",
24567 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",
24568 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",
24569 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",
24570 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",
24571 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",
24572 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",
24573 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",
24574 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",
24575 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",
24576 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",
24577 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",
24578 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",
24579 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",
24580 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",
24581 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",
24582 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",
24583 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",
24584 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",
24585 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",
24586 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",
24587 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",
24588 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",
24589 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",
24590 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",
24591 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",
24592 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",
24593 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",
24594 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",
24595 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",
24596 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",
24597 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",
24598 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",
24599 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",
24600 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",
24601 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",
24602 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",
24603 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",
24604 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",
24605 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",
24606 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",
24607 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",
24608 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",
24609 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",
24610 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",
24611 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",
24612 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",
24613 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",
24614 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"},
24615 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,
24616 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,
24617 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,
24618 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,
24619 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,
24620 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,
24621 {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,
24622 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=
24623 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])/
24624 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],
24625 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,
24626 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);
24627 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-
24628 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+=
24629 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=
24630 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},
24631 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},
24632 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:[]},
24633 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}},
24634 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},
24635 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},
24636 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,
24637 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,
24638 {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(" ");
24639 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=
24640 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=
24641 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"===
24642 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);
24643 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=[]);
24644 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&
24645 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,
24646 !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=
24647 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,
24648 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)}}(),
24649 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]);
24650 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"),
24651 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);
24652 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)}},
24653 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=
24654 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&&
24655 (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!==
24656 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);
24657 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;
24658 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,
24659 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)}});
24660 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=
24661 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);
24662 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;
24663 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}});
24664 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();
24665 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=
24666 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!==
24667 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],
24668 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&&
24669 (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=
24670 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,
24671 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=
24672 !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):
24673 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;
24674 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],
24675 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],
24676 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);
24677 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.",
24678 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=
24679 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&&
24680 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=
24681 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=
24682 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,
24683 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<
24684 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!==
24685 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!==
24686 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=
24687 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(){},
24688 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<
24689 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",
24690 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;
24691 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+
24692 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,
24693 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=
24694 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,
24695 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]);
24696 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 ",
24697 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}});
24698 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."),
24699 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;
24700 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);
24701 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}}(),
24702 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&&
24703 (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=
24704 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=
24705 !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},
24706 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)));
24707 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",
24708 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();
24709 (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,
24710 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",
24711 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]+=
24712 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."));
24713 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===
24714 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",
24715 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]=
24716 {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());
24717 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;
24718 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=
24719 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=
24720 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!==
24721 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&&
24722 (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,
24723 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&&
24724 (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);
24725 !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=
24726 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),
24727 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=
24728 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));
24729 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=
24730 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=
24731 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;
24732 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,
24733 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);
24734 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);
24735 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=
24736 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,
24737 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,
24738 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=
24739 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)}}(),
24740 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=
24741 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,
24742 {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===
24743 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,
24744 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);
24745 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)}});
24746 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=
24747 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,
24748 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,
24749 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),
24750 !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,
24751 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/
24752 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=
24753 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);
24754 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!==
24755 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=
24756 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};
24757 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;
24758 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()/
24759 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,
24760 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=
24761 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=
24762 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,
24763 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));
24764 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=
24765 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}},
24766 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+
24767 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,
24768 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,
24769 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,
24770 -.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}});
24771 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-
24772 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;
24773 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<
24774 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:
24775 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=
24776 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(),
24777 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),
24778 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,
24779 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===
24780 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=
24781 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]);
24782 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),
24783 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),
24784 {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=
24785 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=
24786 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&&
24787 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<
24788 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=
24789 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=
24790 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);
24791 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=
24792 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-
24793 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=
24794 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+
24795 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);
24796 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,
24797 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,
24798 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,
24799 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=
24800 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=
24801 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=
24802 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=
24803 !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=
24804 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;
24805 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,
24806 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;
24807 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);
24808 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};
24809 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,
24810 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),
24811 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=
24812 (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&&
24813 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);
24814 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=
24815 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");
24816 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=
24817 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?
24818 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);
24819 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);
24820 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=
24821 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.");
24822 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;
24823 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=
24824 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,
24825 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],
24826 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=
24827 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,
24828 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=
24829 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=
24830 !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;
24831 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),
24832 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};
24833 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,
24834 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};
24835 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();
24836 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=
24837 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=
24838 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();
24839 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};
24840 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,
24841 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);
24842 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=
24843 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,
24844 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();
24845 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=
24846 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},
24847 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,
24848 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);
24849 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&&
24850 (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),
24851 {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());
24852 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=
24853 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,
24854 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;
24855 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=
24856 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,
24857 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,
24858 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=
24859 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++];
24860 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=
24861 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]=
24862 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=
24863 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,
24864 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,
24865 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,
24866 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+
24867 " 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/
24868 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=
24869 !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=
24870 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]=
24871 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,
24872 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,
24873 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));
24874 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+
24875 "]",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,
24876 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=
24877 [],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=
24878 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===
24879 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=
24880 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=
24881 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=
24882 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&&
24883 (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);
24884 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!==
24885 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!==
24886 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||
24887 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,
24888 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,
24889 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!==
24890 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=
24891 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;
24892 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,
24893 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;
24894 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;
24895 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=
24896 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"!==
24897 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"===
24898 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},
24899 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=
24900 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++],
24901 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);
24902 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=
24903 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=
24904 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,
24905 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,
24906 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 "+
24907 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));
24908 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=
24909 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,
24910 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);
24911 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,
24912 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=
24913 (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<
24914 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={};
24915 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.",
24916 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);
24917 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",
24918 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):
24919 "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({},
24920 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.");
24921 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!==
24922 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&&
24923 (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);
24924 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,
24925 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),
24926 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,
24927 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)>
24928 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=
24929 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,
24930 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=
24931 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,
24932 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||
24933 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=
24934 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)}}()});
24935 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)):
24936 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,
24937 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,
24938 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},
24939 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;
24940 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(),
24941 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]);
24942 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.");
24943 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=
24944 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},
24945 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,
24946 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,
24947 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,
24948 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,
24949 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=
24950 /[\[\]\.:\/]/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: "+
24951 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;
24952 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,
24953 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=
24954 !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,
24955 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,
24956 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.",
24957 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.",
24958 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.",
24959 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.",
24960 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: "+
24961 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!==
24962 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_=
24963 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=
24964 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_,
24965 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()},
24966 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;
24967 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;
24968 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,
24969 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||
24970 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];
24971 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===
24972 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:
24973 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:
24974 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===
24975 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,
24976 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=
24977 [];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}}}},
24978 _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;
24979 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,
24980 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,
24981 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++,
24982 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=
24983 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,
24984 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,
24985 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=
24986 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)}});
24987 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,
24988 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||
24989 [];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=
24990 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-
24991 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*
24992 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);
24993 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()?
24994 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,
24995 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;
24996 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)},
24997 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)},
24998 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"),
24999 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",
25000 "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=
25001 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,
25002 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=
25003 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)}}();
25004 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,
25005 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=
25006 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);
25007 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);
25008 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,
25009 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"),
25010 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",
25011 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]=
25012 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,
25013 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,
25014 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);
25015 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.");
25016 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);
25017 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.")};
25018 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().");
25019 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().");
25020 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().");
25021 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,
25022 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.");
25023 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;
25024 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.");
25025 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.");
25026 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.");
25027 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)};
25028 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)},
25029 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().");
25030 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().");
25031 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,
25032 {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,
25033 {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().");
25034 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,
25035 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,
25036 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().");
25037 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,
25038 {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.")}}});
25039 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.");
25040 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.");
25041 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.");
25042 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.");
25043 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.");
25044 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)},
25045 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.");
25046 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.")}},
25047 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+
25048 ": .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")}}});
25049 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().");
25050 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' ).");
25051 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' ).");
25052 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.");
25053 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.")},
25054 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.");
25055 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,
25056 {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.")}},
25057 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.");
25058 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=
25059 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=
25060 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.");
25061 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},
25062 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().");
25063 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.");
25064 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=
25065 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=
25066 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;
25067 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=
25068 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=
25069 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=
25070 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=
25071 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=
25072 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=
25073 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=
25074 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=
25075 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=
25076 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;
25077 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=
25078 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;
25079 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,
25080 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,
25081 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.");
25082 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,
25083 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.");
25084 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=
25085 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.");
25086 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)};
25087 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.");
25088 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=
25089 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")},
25090 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})});
25091
25092 },{}],243:[function(require,module,exports){
25093 'use strict';
25094
25095 module.exports = TinyQueue;
25096
25097 function TinyQueue(data, compare) {
25098     if (!(this instanceof TinyQueue)) return new TinyQueue(data, compare);
25099
25100     this.data = data || [];
25101     this.length = this.data.length;
25102     this.compare = compare || defaultCompare;
25103
25104     if (this.length > 0) {
25105         for (var i = (this.length >> 1); i >= 0; i--) this._down(i);
25106     }
25107 }
25108
25109 function defaultCompare(a, b) {
25110     return a < b ? -1 : a > b ? 1 : 0;
25111 }
25112
25113 TinyQueue.prototype = {
25114
25115     push: function (item) {
25116         this.data.push(item);
25117         this.length++;
25118         this._up(this.length - 1);
25119     },
25120
25121     pop: function () {
25122         if (this.length === 0) return undefined;
25123         var top = this.data[0];
25124         this.length--;
25125         if (this.length > 0) {
25126             this.data[0] = this.data[this.length];
25127             this._down(0);
25128         }
25129         this.data.pop();
25130         return top;
25131     },
25132
25133     peek: function () {
25134         return this.data[0];
25135     },
25136
25137     _up: function (pos) {
25138         var data = this.data;
25139         var compare = this.compare;
25140         var item = data[pos];
25141
25142         while (pos > 0) {
25143             var parent = (pos - 1) >> 1;
25144             var current = data[parent];
25145             if (compare(item, current) >= 0) break;
25146             data[pos] = current;
25147             pos = parent;
25148         }
25149
25150         data[pos] = item;
25151     },
25152
25153     _down: function (pos) {
25154         var data = this.data;
25155         var compare = this.compare;
25156         var len = this.length;
25157         var halfLen = len >> 1;
25158         var item = data[pos];
25159
25160         while (pos < halfLen) {
25161             var left = (pos << 1) + 1;
25162             var right = left + 1;
25163             var best = data[left];
25164
25165             if (right < len && compare(data[right], best) < 0) {
25166                 left = right;
25167                 best = data[right];
25168             }
25169             if (compare(best, item) >= 0) break;
25170
25171             data[pos] = best;
25172             pos = left;
25173         }
25174
25175         data[pos] = item;
25176     }
25177 };
25178
25179 },{}],244:[function(require,module,exports){
25180 var createElement = require("./vdom/create-element.js")
25181
25182 module.exports = createElement
25183
25184 },{"./vdom/create-element.js":250}],245:[function(require,module,exports){
25185 var diff = require("./vtree/diff.js")
25186
25187 module.exports = diff
25188
25189 },{"./vtree/diff.js":270}],246:[function(require,module,exports){
25190 var h = require("./virtual-hyperscript/index.js")
25191
25192 module.exports = h
25193
25194 },{"./virtual-hyperscript/index.js":257}],247:[function(require,module,exports){
25195 var diff = require("./diff.js")
25196 var patch = require("./patch.js")
25197 var h = require("./h.js")
25198 var create = require("./create-element.js")
25199 var VNode = require('./vnode/vnode.js')
25200 var VText = require('./vnode/vtext.js')
25201
25202 module.exports = {
25203     diff: diff,
25204     patch: patch,
25205     h: h,
25206     create: create,
25207     VNode: VNode,
25208     VText: VText
25209 }
25210
25211 },{"./create-element.js":244,"./diff.js":245,"./h.js":246,"./patch.js":248,"./vnode/vnode.js":266,"./vnode/vtext.js":268}],248:[function(require,module,exports){
25212 var patch = require("./vdom/patch.js")
25213
25214 module.exports = patch
25215
25216 },{"./vdom/patch.js":253}],249:[function(require,module,exports){
25217 var isObject = require("is-object")
25218 var isHook = require("../vnode/is-vhook.js")
25219
25220 module.exports = applyProperties
25221
25222 function applyProperties(node, props, previous) {
25223     for (var propName in props) {
25224         var propValue = props[propName]
25225
25226         if (propValue === undefined) {
25227             removeProperty(node, propName, propValue, previous);
25228         } else if (isHook(propValue)) {
25229             removeProperty(node, propName, propValue, previous)
25230             if (propValue.hook) {
25231                 propValue.hook(node,
25232                     propName,
25233                     previous ? previous[propName] : undefined)
25234             }
25235         } else {
25236             if (isObject(propValue)) {
25237                 patchObject(node, props, previous, propName, propValue);
25238             } else {
25239                 node[propName] = propValue
25240             }
25241         }
25242     }
25243 }
25244
25245 function removeProperty(node, propName, propValue, previous) {
25246     if (previous) {
25247         var previousValue = previous[propName]
25248
25249         if (!isHook(previousValue)) {
25250             if (propName === "attributes") {
25251                 for (var attrName in previousValue) {
25252                     node.removeAttribute(attrName)
25253                 }
25254             } else if (propName === "style") {
25255                 for (var i in previousValue) {
25256                     node.style[i] = ""
25257                 }
25258             } else if (typeof previousValue === "string") {
25259                 node[propName] = ""
25260             } else {
25261                 node[propName] = null
25262             }
25263         } else if (previousValue.unhook) {
25264             previousValue.unhook(node, propName, propValue)
25265         }
25266     }
25267 }
25268
25269 function patchObject(node, props, previous, propName, propValue) {
25270     var previousValue = previous ? previous[propName] : undefined
25271
25272     // Set attributes
25273     if (propName === "attributes") {
25274         for (var attrName in propValue) {
25275             var attrValue = propValue[attrName]
25276
25277             if (attrValue === undefined) {
25278                 node.removeAttribute(attrName)
25279             } else {
25280                 node.setAttribute(attrName, attrValue)
25281             }
25282         }
25283
25284         return
25285     }
25286
25287     if(previousValue && isObject(previousValue) &&
25288         getPrototype(previousValue) !== getPrototype(propValue)) {
25289         node[propName] = propValue
25290         return
25291     }
25292
25293     if (!isObject(node[propName])) {
25294         node[propName] = {}
25295     }
25296
25297     var replacer = propName === "style" ? "" : undefined
25298
25299     for (var k in propValue) {
25300         var value = propValue[k]
25301         node[propName][k] = (value === undefined) ? replacer : value
25302     }
25303 }
25304
25305 function getPrototype(value) {
25306     if (Object.getPrototypeOf) {
25307         return Object.getPrototypeOf(value)
25308     } else if (value.__proto__) {
25309         return value.__proto__
25310     } else if (value.constructor) {
25311         return value.constructor.prototype
25312     }
25313 }
25314
25315 },{"../vnode/is-vhook.js":261,"is-object":20}],250:[function(require,module,exports){
25316 var document = require("global/document")
25317
25318 var applyProperties = require("./apply-properties")
25319
25320 var isVNode = require("../vnode/is-vnode.js")
25321 var isVText = require("../vnode/is-vtext.js")
25322 var isWidget = require("../vnode/is-widget.js")
25323 var handleThunk = require("../vnode/handle-thunk.js")
25324
25325 module.exports = createElement
25326
25327 function createElement(vnode, opts) {
25328     var doc = opts ? opts.document || document : document
25329     var warn = opts ? opts.warn : null
25330
25331     vnode = handleThunk(vnode).a
25332
25333     if (isWidget(vnode)) {
25334         return vnode.init()
25335     } else if (isVText(vnode)) {
25336         return doc.createTextNode(vnode.text)
25337     } else if (!isVNode(vnode)) {
25338         if (warn) {
25339             warn("Item is not a valid virtual dom node", vnode)
25340         }
25341         return null
25342     }
25343
25344     var node = (vnode.namespace === null) ?
25345         doc.createElement(vnode.tagName) :
25346         doc.createElementNS(vnode.namespace, vnode.tagName)
25347
25348     var props = vnode.properties
25349     applyProperties(node, props)
25350
25351     var children = vnode.children
25352
25353     for (var i = 0; i < children.length; i++) {
25354         var childNode = createElement(children[i], opts)
25355         if (childNode) {
25356             node.appendChild(childNode)
25357         }
25358     }
25359
25360     return node
25361 }
25362
25363 },{"../vnode/handle-thunk.js":259,"../vnode/is-vnode.js":262,"../vnode/is-vtext.js":263,"../vnode/is-widget.js":264,"./apply-properties":249,"global/document":16}],251:[function(require,module,exports){
25364 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
25365 // We don't want to read all of the DOM nodes in the tree so we use
25366 // the in-order tree indexing to eliminate recursion down certain branches.
25367 // We only recurse into a DOM node if we know that it contains a child of
25368 // interest.
25369
25370 var noChild = {}
25371
25372 module.exports = domIndex
25373
25374 function domIndex(rootNode, tree, indices, nodes) {
25375     if (!indices || indices.length === 0) {
25376         return {}
25377     } else {
25378         indices.sort(ascending)
25379         return recurse(rootNode, tree, indices, nodes, 0)
25380     }
25381 }
25382
25383 function recurse(rootNode, tree, indices, nodes, rootIndex) {
25384     nodes = nodes || {}
25385
25386
25387     if (rootNode) {
25388         if (indexInRange(indices, rootIndex, rootIndex)) {
25389             nodes[rootIndex] = rootNode
25390         }
25391
25392         var vChildren = tree.children
25393
25394         if (vChildren) {
25395
25396             var childNodes = rootNode.childNodes
25397
25398             for (var i = 0; i < tree.children.length; i++) {
25399                 rootIndex += 1
25400
25401                 var vChild = vChildren[i] || noChild
25402                 var nextIndex = rootIndex + (vChild.count || 0)
25403
25404                 // skip recursion down the tree if there are no nodes down here
25405                 if (indexInRange(indices, rootIndex, nextIndex)) {
25406                     recurse(childNodes[i], vChild, indices, nodes, rootIndex)
25407                 }
25408
25409                 rootIndex = nextIndex
25410             }
25411         }
25412     }
25413
25414     return nodes
25415 }
25416
25417 // Binary search for an index in the interval [left, right]
25418 function indexInRange(indices, left, right) {
25419     if (indices.length === 0) {
25420         return false
25421     }
25422
25423     var minIndex = 0
25424     var maxIndex = indices.length - 1
25425     var currentIndex
25426     var currentItem
25427
25428     while (minIndex <= maxIndex) {
25429         currentIndex = ((maxIndex + minIndex) / 2) >> 0
25430         currentItem = indices[currentIndex]
25431
25432         if (minIndex === maxIndex) {
25433             return currentItem >= left && currentItem <= right
25434         } else if (currentItem < left) {
25435             minIndex = currentIndex + 1
25436         } else  if (currentItem > right) {
25437             maxIndex = currentIndex - 1
25438         } else {
25439             return true
25440         }
25441     }
25442
25443     return false;
25444 }
25445
25446 function ascending(a, b) {
25447     return a > b ? 1 : -1
25448 }
25449
25450 },{}],252:[function(require,module,exports){
25451 var applyProperties = require("./apply-properties")
25452
25453 var isWidget = require("../vnode/is-widget.js")
25454 var VPatch = require("../vnode/vpatch.js")
25455
25456 var updateWidget = require("./update-widget")
25457
25458 module.exports = applyPatch
25459
25460 function applyPatch(vpatch, domNode, renderOptions) {
25461     var type = vpatch.type
25462     var vNode = vpatch.vNode
25463     var patch = vpatch.patch
25464
25465     switch (type) {
25466         case VPatch.REMOVE:
25467             return removeNode(domNode, vNode)
25468         case VPatch.INSERT:
25469             return insertNode(domNode, patch, renderOptions)
25470         case VPatch.VTEXT:
25471             return stringPatch(domNode, vNode, patch, renderOptions)
25472         case VPatch.WIDGET:
25473             return widgetPatch(domNode, vNode, patch, renderOptions)
25474         case VPatch.VNODE:
25475             return vNodePatch(domNode, vNode, patch, renderOptions)
25476         case VPatch.ORDER:
25477             reorderChildren(domNode, patch)
25478             return domNode
25479         case VPatch.PROPS:
25480             applyProperties(domNode, patch, vNode.properties)
25481             return domNode
25482         case VPatch.THUNK:
25483             return replaceRoot(domNode,
25484                 renderOptions.patch(domNode, patch, renderOptions))
25485         default:
25486             return domNode
25487     }
25488 }
25489
25490 function removeNode(domNode, vNode) {
25491     var parentNode = domNode.parentNode
25492
25493     if (parentNode) {
25494         parentNode.removeChild(domNode)
25495     }
25496
25497     destroyWidget(domNode, vNode);
25498
25499     return null
25500 }
25501
25502 function insertNode(parentNode, vNode, renderOptions) {
25503     var newNode = renderOptions.render(vNode, renderOptions)
25504
25505     if (parentNode) {
25506         parentNode.appendChild(newNode)
25507     }
25508
25509     return parentNode
25510 }
25511
25512 function stringPatch(domNode, leftVNode, vText, renderOptions) {
25513     var newNode
25514
25515     if (domNode.nodeType === 3) {
25516         domNode.replaceData(0, domNode.length, vText.text)
25517         newNode = domNode
25518     } else {
25519         var parentNode = domNode.parentNode
25520         newNode = renderOptions.render(vText, renderOptions)
25521
25522         if (parentNode && newNode !== domNode) {
25523             parentNode.replaceChild(newNode, domNode)
25524         }
25525     }
25526
25527     return newNode
25528 }
25529
25530 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
25531     var updating = updateWidget(leftVNode, widget)
25532     var newNode
25533
25534     if (updating) {
25535         newNode = widget.update(leftVNode, domNode) || domNode
25536     } else {
25537         newNode = renderOptions.render(widget, renderOptions)
25538     }
25539
25540     var parentNode = domNode.parentNode
25541
25542     if (parentNode && newNode !== domNode) {
25543         parentNode.replaceChild(newNode, domNode)
25544     }
25545
25546     if (!updating) {
25547         destroyWidget(domNode, leftVNode)
25548     }
25549
25550     return newNode
25551 }
25552
25553 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
25554     var parentNode = domNode.parentNode
25555     var newNode = renderOptions.render(vNode, renderOptions)
25556
25557     if (parentNode && newNode !== domNode) {
25558         parentNode.replaceChild(newNode, domNode)
25559     }
25560
25561     return newNode
25562 }
25563
25564 function destroyWidget(domNode, w) {
25565     if (typeof w.destroy === "function" && isWidget(w)) {
25566         w.destroy(domNode)
25567     }
25568 }
25569
25570 function reorderChildren(domNode, moves) {
25571     var childNodes = domNode.childNodes
25572     var keyMap = {}
25573     var node
25574     var remove
25575     var insert
25576
25577     for (var i = 0; i < moves.removes.length; i++) {
25578         remove = moves.removes[i]
25579         node = childNodes[remove.from]
25580         if (remove.key) {
25581             keyMap[remove.key] = node
25582         }
25583         domNode.removeChild(node)
25584     }
25585
25586     var length = childNodes.length
25587     for (var j = 0; j < moves.inserts.length; j++) {
25588         insert = moves.inserts[j]
25589         node = keyMap[insert.key]
25590         // this is the weirdest bug i've ever seen in webkit
25591         domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
25592     }
25593 }
25594
25595 function replaceRoot(oldRoot, newRoot) {
25596     if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
25597         oldRoot.parentNode.replaceChild(newRoot, oldRoot)
25598     }
25599
25600     return newRoot;
25601 }
25602
25603 },{"../vnode/is-widget.js":264,"../vnode/vpatch.js":267,"./apply-properties":249,"./update-widget":254}],253:[function(require,module,exports){
25604 var document = require("global/document")
25605 var isArray = require("x-is-array")
25606
25607 var render = require("./create-element")
25608 var domIndex = require("./dom-index")
25609 var patchOp = require("./patch-op")
25610 module.exports = patch
25611
25612 function patch(rootNode, patches, renderOptions) {
25613     renderOptions = renderOptions || {}
25614     renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
25615         ? renderOptions.patch
25616         : patchRecursive
25617     renderOptions.render = renderOptions.render || render
25618
25619     return renderOptions.patch(rootNode, patches, renderOptions)
25620 }
25621
25622 function patchRecursive(rootNode, patches, renderOptions) {
25623     var indices = patchIndices(patches)
25624
25625     if (indices.length === 0) {
25626         return rootNode
25627     }
25628
25629     var index = domIndex(rootNode, patches.a, indices)
25630     var ownerDocument = rootNode.ownerDocument
25631
25632     if (!renderOptions.document && ownerDocument !== document) {
25633         renderOptions.document = ownerDocument
25634     }
25635
25636     for (var i = 0; i < indices.length; i++) {
25637         var nodeIndex = indices[i]
25638         rootNode = applyPatch(rootNode,
25639             index[nodeIndex],
25640             patches[nodeIndex],
25641             renderOptions)
25642     }
25643
25644     return rootNode
25645 }
25646
25647 function applyPatch(rootNode, domNode, patchList, renderOptions) {
25648     if (!domNode) {
25649         return rootNode
25650     }
25651
25652     var newNode
25653
25654     if (isArray(patchList)) {
25655         for (var i = 0; i < patchList.length; i++) {
25656             newNode = patchOp(patchList[i], domNode, renderOptions)
25657
25658             if (domNode === rootNode) {
25659                 rootNode = newNode
25660             }
25661         }
25662     } else {
25663         newNode = patchOp(patchList, domNode, renderOptions)
25664
25665         if (domNode === rootNode) {
25666             rootNode = newNode
25667         }
25668     }
25669
25670     return rootNode
25671 }
25672
25673 function patchIndices(patches) {
25674     var indices = []
25675
25676     for (var key in patches) {
25677         if (key !== "a") {
25678             indices.push(Number(key))
25679         }
25680     }
25681
25682     return indices
25683 }
25684
25685 },{"./create-element":250,"./dom-index":251,"./patch-op":252,"global/document":16,"x-is-array":289}],254:[function(require,module,exports){
25686 var isWidget = require("../vnode/is-widget.js")
25687
25688 module.exports = updateWidget
25689
25690 function updateWidget(a, b) {
25691     if (isWidget(a) && isWidget(b)) {
25692         if ("name" in a && "name" in b) {
25693             return a.id === b.id
25694         } else {
25695             return a.init === b.init
25696         }
25697     }
25698
25699     return false
25700 }
25701
25702 },{"../vnode/is-widget.js":264}],255:[function(require,module,exports){
25703 'use strict';
25704
25705 var EvStore = require('ev-store');
25706
25707 module.exports = EvHook;
25708
25709 function EvHook(value) {
25710     if (!(this instanceof EvHook)) {
25711         return new EvHook(value);
25712     }
25713
25714     this.value = value;
25715 }
25716
25717 EvHook.prototype.hook = function (node, propertyName) {
25718     var es = EvStore(node);
25719     var propName = propertyName.substr(3);
25720
25721     es[propName] = this.value;
25722 };
25723
25724 EvHook.prototype.unhook = function(node, propertyName) {
25725     var es = EvStore(node);
25726     var propName = propertyName.substr(3);
25727
25728     es[propName] = undefined;
25729 };
25730
25731 },{"ev-store":9}],256:[function(require,module,exports){
25732 'use strict';
25733
25734 module.exports = SoftSetHook;
25735
25736 function SoftSetHook(value) {
25737     if (!(this instanceof SoftSetHook)) {
25738         return new SoftSetHook(value);
25739     }
25740
25741     this.value = value;
25742 }
25743
25744 SoftSetHook.prototype.hook = function (node, propertyName) {
25745     if (node[propertyName] !== this.value) {
25746         node[propertyName] = this.value;
25747     }
25748 };
25749
25750 },{}],257:[function(require,module,exports){
25751 'use strict';
25752
25753 var isArray = require('x-is-array');
25754
25755 var VNode = require('../vnode/vnode.js');
25756 var VText = require('../vnode/vtext.js');
25757 var isVNode = require('../vnode/is-vnode');
25758 var isVText = require('../vnode/is-vtext');
25759 var isWidget = require('../vnode/is-widget');
25760 var isHook = require('../vnode/is-vhook');
25761 var isVThunk = require('../vnode/is-thunk');
25762
25763 var parseTag = require('./parse-tag.js');
25764 var softSetHook = require('./hooks/soft-set-hook.js');
25765 var evHook = require('./hooks/ev-hook.js');
25766
25767 module.exports = h;
25768
25769 function h(tagName, properties, children) {
25770     var childNodes = [];
25771     var tag, props, key, namespace;
25772
25773     if (!children && isChildren(properties)) {
25774         children = properties;
25775         props = {};
25776     }
25777
25778     props = props || properties || {};
25779     tag = parseTag(tagName, props);
25780
25781     // support keys
25782     if (props.hasOwnProperty('key')) {
25783         key = props.key;
25784         props.key = undefined;
25785     }
25786
25787     // support namespace
25788     if (props.hasOwnProperty('namespace')) {
25789         namespace = props.namespace;
25790         props.namespace = undefined;
25791     }
25792
25793     // fix cursor bug
25794     if (tag === 'INPUT' &&
25795         !namespace &&
25796         props.hasOwnProperty('value') &&
25797         props.value !== undefined &&
25798         !isHook(props.value)
25799     ) {
25800         props.value = softSetHook(props.value);
25801     }
25802
25803     transformProperties(props);
25804
25805     if (children !== undefined && children !== null) {
25806         addChild(children, childNodes, tag, props);
25807     }
25808
25809
25810     return new VNode(tag, props, childNodes, key, namespace);
25811 }
25812
25813 function addChild(c, childNodes, tag, props) {
25814     if (typeof c === 'string') {
25815         childNodes.push(new VText(c));
25816     } else if (typeof c === 'number') {
25817         childNodes.push(new VText(String(c)));
25818     } else if (isChild(c)) {
25819         childNodes.push(c);
25820     } else if (isArray(c)) {
25821         for (var i = 0; i < c.length; i++) {
25822             addChild(c[i], childNodes, tag, props);
25823         }
25824     } else if (c === null || c === undefined) {
25825         return;
25826     } else {
25827         throw UnexpectedVirtualElement({
25828             foreignObject: c,
25829             parentVnode: {
25830                 tagName: tag,
25831                 properties: props
25832             }
25833         });
25834     }
25835 }
25836
25837 function transformProperties(props) {
25838     for (var propName in props) {
25839         if (props.hasOwnProperty(propName)) {
25840             var value = props[propName];
25841
25842             if (isHook(value)) {
25843                 continue;
25844             }
25845
25846             if (propName.substr(0, 3) === 'ev-') {
25847                 // add ev-foo support
25848                 props[propName] = evHook(value);
25849             }
25850         }
25851     }
25852 }
25853
25854 function isChild(x) {
25855     return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
25856 }
25857
25858 function isChildren(x) {
25859     return typeof x === 'string' || isArray(x) || isChild(x);
25860 }
25861
25862 function UnexpectedVirtualElement(data) {
25863     var err = new Error();
25864
25865     err.type = 'virtual-hyperscript.unexpected.virtual-element';
25866     err.message = 'Unexpected virtual child passed to h().\n' +
25867         'Expected a VNode / Vthunk / VWidget / string but:\n' +
25868         'got:\n' +
25869         errorString(data.foreignObject) +
25870         '.\n' +
25871         'The parent vnode is:\n' +
25872         errorString(data.parentVnode)
25873         '\n' +
25874         'Suggested fix: change your `h(..., [ ... ])` callsite.';
25875     err.foreignObject = data.foreignObject;
25876     err.parentVnode = data.parentVnode;
25877
25878     return err;
25879 }
25880
25881 function errorString(obj) {
25882     try {
25883         return JSON.stringify(obj, null, '    ');
25884     } catch (e) {
25885         return String(obj);
25886     }
25887 }
25888
25889 },{"../vnode/is-thunk":260,"../vnode/is-vhook":261,"../vnode/is-vnode":262,"../vnode/is-vtext":263,"../vnode/is-widget":264,"../vnode/vnode.js":266,"../vnode/vtext.js":268,"./hooks/ev-hook.js":255,"./hooks/soft-set-hook.js":256,"./parse-tag.js":258,"x-is-array":289}],258:[function(require,module,exports){
25890 'use strict';
25891
25892 var split = require('browser-split');
25893
25894 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
25895 var notClassId = /^\.|#/;
25896
25897 module.exports = parseTag;
25898
25899 function parseTag(tag, props) {
25900     if (!tag) {
25901         return 'DIV';
25902     }
25903
25904     var noId = !(props.hasOwnProperty('id'));
25905
25906     var tagParts = split(tag, classIdSplit);
25907     var tagName = null;
25908
25909     if (notClassId.test(tagParts[1])) {
25910         tagName = 'DIV';
25911     }
25912
25913     var classes, part, type, i;
25914
25915     for (i = 0; i < tagParts.length; i++) {
25916         part = tagParts[i];
25917
25918         if (!part) {
25919             continue;
25920         }
25921
25922         type = part.charAt(0);
25923
25924         if (!tagName) {
25925             tagName = part;
25926         } else if (type === '.') {
25927             classes = classes || [];
25928             classes.push(part.substring(1, part.length));
25929         } else if (type === '#' && noId) {
25930             props.id = part.substring(1, part.length);
25931         }
25932     }
25933
25934     if (classes) {
25935         if (props.className) {
25936             classes.push(props.className);
25937         }
25938
25939         props.className = classes.join(' ');
25940     }
25941
25942     return props.namespace ? tagName : tagName.toUpperCase();
25943 }
25944
25945 },{"browser-split":5}],259:[function(require,module,exports){
25946 var isVNode = require("./is-vnode")
25947 var isVText = require("./is-vtext")
25948 var isWidget = require("./is-widget")
25949 var isThunk = require("./is-thunk")
25950
25951 module.exports = handleThunk
25952
25953 function handleThunk(a, b) {
25954     var renderedA = a
25955     var renderedB = b
25956
25957     if (isThunk(b)) {
25958         renderedB = renderThunk(b, a)
25959     }
25960
25961     if (isThunk(a)) {
25962         renderedA = renderThunk(a, null)
25963     }
25964
25965     return {
25966         a: renderedA,
25967         b: renderedB
25968     }
25969 }
25970
25971 function renderThunk(thunk, previous) {
25972     var renderedThunk = thunk.vnode
25973
25974     if (!renderedThunk) {
25975         renderedThunk = thunk.vnode = thunk.render(previous)
25976     }
25977
25978     if (!(isVNode(renderedThunk) ||
25979             isVText(renderedThunk) ||
25980             isWidget(renderedThunk))) {
25981         throw new Error("thunk did not return a valid node");
25982     }
25983
25984     return renderedThunk
25985 }
25986
25987 },{"./is-thunk":260,"./is-vnode":262,"./is-vtext":263,"./is-widget":264}],260:[function(require,module,exports){
25988 module.exports = isThunk
25989
25990 function isThunk(t) {
25991     return t && t.type === "Thunk"
25992 }
25993
25994 },{}],261:[function(require,module,exports){
25995 module.exports = isHook
25996
25997 function isHook(hook) {
25998     return hook &&
25999       (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
26000        typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
26001 }
26002
26003 },{}],262:[function(require,module,exports){
26004 var version = require("./version")
26005
26006 module.exports = isVirtualNode
26007
26008 function isVirtualNode(x) {
26009     return x && x.type === "VirtualNode" && x.version === version
26010 }
26011
26012 },{"./version":265}],263:[function(require,module,exports){
26013 var version = require("./version")
26014
26015 module.exports = isVirtualText
26016
26017 function isVirtualText(x) {
26018     return x && x.type === "VirtualText" && x.version === version
26019 }
26020
26021 },{"./version":265}],264:[function(require,module,exports){
26022 module.exports = isWidget
26023
26024 function isWidget(w) {
26025     return w && w.type === "Widget"
26026 }
26027
26028 },{}],265:[function(require,module,exports){
26029 module.exports = "2"
26030
26031 },{}],266:[function(require,module,exports){
26032 var version = require("./version")
26033 var isVNode = require("./is-vnode")
26034 var isWidget = require("./is-widget")
26035 var isThunk = require("./is-thunk")
26036 var isVHook = require("./is-vhook")
26037
26038 module.exports = VirtualNode
26039
26040 var noProperties = {}
26041 var noChildren = []
26042
26043 function VirtualNode(tagName, properties, children, key, namespace) {
26044     this.tagName = tagName
26045     this.properties = properties || noProperties
26046     this.children = children || noChildren
26047     this.key = key != null ? String(key) : undefined
26048     this.namespace = (typeof namespace === "string") ? namespace : null
26049
26050     var count = (children && children.length) || 0
26051     var descendants = 0
26052     var hasWidgets = false
26053     var hasThunks = false
26054     var descendantHooks = false
26055     var hooks
26056
26057     for (var propName in properties) {
26058         if (properties.hasOwnProperty(propName)) {
26059             var property = properties[propName]
26060             if (isVHook(property) && property.unhook) {
26061                 if (!hooks) {
26062                     hooks = {}
26063                 }
26064
26065                 hooks[propName] = property
26066             }
26067         }
26068     }
26069
26070     for (var i = 0; i < count; i++) {
26071         var child = children[i]
26072         if (isVNode(child)) {
26073             descendants += child.count || 0
26074
26075             if (!hasWidgets && child.hasWidgets) {
26076                 hasWidgets = true
26077             }
26078
26079             if (!hasThunks && child.hasThunks) {
26080                 hasThunks = true
26081             }
26082
26083             if (!descendantHooks && (child.hooks || child.descendantHooks)) {
26084                 descendantHooks = true
26085             }
26086         } else if (!hasWidgets && isWidget(child)) {
26087             if (typeof child.destroy === "function") {
26088                 hasWidgets = true
26089             }
26090         } else if (!hasThunks && isThunk(child)) {
26091             hasThunks = true;
26092         }
26093     }
26094
26095     this.count = count + descendants
26096     this.hasWidgets = hasWidgets
26097     this.hasThunks = hasThunks
26098     this.hooks = hooks
26099     this.descendantHooks = descendantHooks
26100 }
26101
26102 VirtualNode.prototype.version = version
26103 VirtualNode.prototype.type = "VirtualNode"
26104
26105 },{"./is-thunk":260,"./is-vhook":261,"./is-vnode":262,"./is-widget":264,"./version":265}],267:[function(require,module,exports){
26106 var version = require("./version")
26107
26108 VirtualPatch.NONE = 0
26109 VirtualPatch.VTEXT = 1
26110 VirtualPatch.VNODE = 2
26111 VirtualPatch.WIDGET = 3
26112 VirtualPatch.PROPS = 4
26113 VirtualPatch.ORDER = 5
26114 VirtualPatch.INSERT = 6
26115 VirtualPatch.REMOVE = 7
26116 VirtualPatch.THUNK = 8
26117
26118 module.exports = VirtualPatch
26119
26120 function VirtualPatch(type, vNode, patch) {
26121     this.type = Number(type)
26122     this.vNode = vNode
26123     this.patch = patch
26124 }
26125
26126 VirtualPatch.prototype.version = version
26127 VirtualPatch.prototype.type = "VirtualPatch"
26128
26129 },{"./version":265}],268:[function(require,module,exports){
26130 var version = require("./version")
26131
26132 module.exports = VirtualText
26133
26134 function VirtualText(text) {
26135     this.text = String(text)
26136 }
26137
26138 VirtualText.prototype.version = version
26139 VirtualText.prototype.type = "VirtualText"
26140
26141 },{"./version":265}],269:[function(require,module,exports){
26142 var isObject = require("is-object")
26143 var isHook = require("../vnode/is-vhook")
26144
26145 module.exports = diffProps
26146
26147 function diffProps(a, b) {
26148     var diff
26149
26150     for (var aKey in a) {
26151         if (!(aKey in b)) {
26152             diff = diff || {}
26153             diff[aKey] = undefined
26154         }
26155
26156         var aValue = a[aKey]
26157         var bValue = b[aKey]
26158
26159         if (aValue === bValue) {
26160             continue
26161         } else if (isObject(aValue) && isObject(bValue)) {
26162             if (getPrototype(bValue) !== getPrototype(aValue)) {
26163                 diff = diff || {}
26164                 diff[aKey] = bValue
26165             } else if (isHook(bValue)) {
26166                  diff = diff || {}
26167                  diff[aKey] = bValue
26168             } else {
26169                 var objectDiff = diffProps(aValue, bValue)
26170                 if (objectDiff) {
26171                     diff = diff || {}
26172                     diff[aKey] = objectDiff
26173                 }
26174             }
26175         } else {
26176             diff = diff || {}
26177             diff[aKey] = bValue
26178         }
26179     }
26180
26181     for (var bKey in b) {
26182         if (!(bKey in a)) {
26183             diff = diff || {}
26184             diff[bKey] = b[bKey]
26185         }
26186     }
26187
26188     return diff
26189 }
26190
26191 function getPrototype(value) {
26192   if (Object.getPrototypeOf) {
26193     return Object.getPrototypeOf(value)
26194   } else if (value.__proto__) {
26195     return value.__proto__
26196   } else if (value.constructor) {
26197     return value.constructor.prototype
26198   }
26199 }
26200
26201 },{"../vnode/is-vhook":261,"is-object":20}],270:[function(require,module,exports){
26202 var isArray = require("x-is-array")
26203
26204 var VPatch = require("../vnode/vpatch")
26205 var isVNode = require("../vnode/is-vnode")
26206 var isVText = require("../vnode/is-vtext")
26207 var isWidget = require("../vnode/is-widget")
26208 var isThunk = require("../vnode/is-thunk")
26209 var handleThunk = require("../vnode/handle-thunk")
26210
26211 var diffProps = require("./diff-props")
26212
26213 module.exports = diff
26214
26215 function diff(a, b) {
26216     var patch = { a: a }
26217     walk(a, b, patch, 0)
26218     return patch
26219 }
26220
26221 function walk(a, b, patch, index) {
26222     if (a === b) {
26223         return
26224     }
26225
26226     var apply = patch[index]
26227     var applyClear = false
26228
26229     if (isThunk(a) || isThunk(b)) {
26230         thunks(a, b, patch, index)
26231     } else if (b == null) {
26232
26233         // If a is a widget we will add a remove patch for it
26234         // Otherwise any child widgets/hooks must be destroyed.
26235         // This prevents adding two remove patches for a widget.
26236         if (!isWidget(a)) {
26237             clearState(a, patch, index)
26238             apply = patch[index]
26239         }
26240
26241         apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
26242     } else if (isVNode(b)) {
26243         if (isVNode(a)) {
26244             if (a.tagName === b.tagName &&
26245                 a.namespace === b.namespace &&
26246                 a.key === b.key) {
26247                 var propsPatch = diffProps(a.properties, b.properties)
26248                 if (propsPatch) {
26249                     apply = appendPatch(apply,
26250                         new VPatch(VPatch.PROPS, a, propsPatch))
26251                 }
26252                 apply = diffChildren(a, b, patch, apply, index)
26253             } else {
26254                 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
26255                 applyClear = true
26256             }
26257         } else {
26258             apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
26259             applyClear = true
26260         }
26261     } else if (isVText(b)) {
26262         if (!isVText(a)) {
26263             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
26264             applyClear = true
26265         } else if (a.text !== b.text) {
26266             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
26267         }
26268     } else if (isWidget(b)) {
26269         if (!isWidget(a)) {
26270             applyClear = true
26271         }
26272
26273         apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
26274     }
26275
26276     if (apply) {
26277         patch[index] = apply
26278     }
26279
26280     if (applyClear) {
26281         clearState(a, patch, index)
26282     }
26283 }
26284
26285 function diffChildren(a, b, patch, apply, index) {
26286     var aChildren = a.children
26287     var orderedSet = reorder(aChildren, b.children)
26288     var bChildren = orderedSet.children
26289
26290     var aLen = aChildren.length
26291     var bLen = bChildren.length
26292     var len = aLen > bLen ? aLen : bLen
26293
26294     for (var i = 0; i < len; i++) {
26295         var leftNode = aChildren[i]
26296         var rightNode = bChildren[i]
26297         index += 1
26298
26299         if (!leftNode) {
26300             if (rightNode) {
26301                 // Excess nodes in b need to be added
26302                 apply = appendPatch(apply,
26303                     new VPatch(VPatch.INSERT, null, rightNode))
26304             }
26305         } else {
26306             walk(leftNode, rightNode, patch, index)
26307         }
26308
26309         if (isVNode(leftNode) && leftNode.count) {
26310             index += leftNode.count
26311         }
26312     }
26313
26314     if (orderedSet.moves) {
26315         // Reorder nodes last
26316         apply = appendPatch(apply, new VPatch(
26317             VPatch.ORDER,
26318             a,
26319             orderedSet.moves
26320         ))
26321     }
26322
26323     return apply
26324 }
26325
26326 function clearState(vNode, patch, index) {
26327     // TODO: Make this a single walk, not two
26328     unhook(vNode, patch, index)
26329     destroyWidgets(vNode, patch, index)
26330 }
26331
26332 // Patch records for all destroyed widgets must be added because we need
26333 // a DOM node reference for the destroy function
26334 function destroyWidgets(vNode, patch, index) {
26335     if (isWidget(vNode)) {
26336         if (typeof vNode.destroy === "function") {
26337             patch[index] = appendPatch(
26338                 patch[index],
26339                 new VPatch(VPatch.REMOVE, vNode, null)
26340             )
26341         }
26342     } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
26343         var children = vNode.children
26344         var len = children.length
26345         for (var i = 0; i < len; i++) {
26346             var child = children[i]
26347             index += 1
26348
26349             destroyWidgets(child, patch, index)
26350
26351             if (isVNode(child) && child.count) {
26352                 index += child.count
26353             }
26354         }
26355     } else if (isThunk(vNode)) {
26356         thunks(vNode, null, patch, index)
26357     }
26358 }
26359
26360 // Create a sub-patch for thunks
26361 function thunks(a, b, patch, index) {
26362     var nodes = handleThunk(a, b)
26363     var thunkPatch = diff(nodes.a, nodes.b)
26364     if (hasPatches(thunkPatch)) {
26365         patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
26366     }
26367 }
26368
26369 function hasPatches(patch) {
26370     for (var index in patch) {
26371         if (index !== "a") {
26372             return true
26373         }
26374     }
26375
26376     return false
26377 }
26378
26379 // Execute hooks when two nodes are identical
26380 function unhook(vNode, patch, index) {
26381     if (isVNode(vNode)) {
26382         if (vNode.hooks) {
26383             patch[index] = appendPatch(
26384                 patch[index],
26385                 new VPatch(
26386                     VPatch.PROPS,
26387                     vNode,
26388                     undefinedKeys(vNode.hooks)
26389                 )
26390             )
26391         }
26392
26393         if (vNode.descendantHooks || vNode.hasThunks) {
26394             var children = vNode.children
26395             var len = children.length
26396             for (var i = 0; i < len; i++) {
26397                 var child = children[i]
26398                 index += 1
26399
26400                 unhook(child, patch, index)
26401
26402                 if (isVNode(child) && child.count) {
26403                     index += child.count
26404                 }
26405             }
26406         }
26407     } else if (isThunk(vNode)) {
26408         thunks(vNode, null, patch, index)
26409     }
26410 }
26411
26412 function undefinedKeys(obj) {
26413     var result = {}
26414
26415     for (var key in obj) {
26416         result[key] = undefined
26417     }
26418
26419     return result
26420 }
26421
26422 // List diff, naive left to right reordering
26423 function reorder(aChildren, bChildren) {
26424     // O(M) time, O(M) memory
26425     var bChildIndex = keyIndex(bChildren)
26426     var bKeys = bChildIndex.keys
26427     var bFree = bChildIndex.free
26428
26429     if (bFree.length === bChildren.length) {
26430         return {
26431             children: bChildren,
26432             moves: null
26433         }
26434     }
26435
26436     // O(N) time, O(N) memory
26437     var aChildIndex = keyIndex(aChildren)
26438     var aKeys = aChildIndex.keys
26439     var aFree = aChildIndex.free
26440
26441     if (aFree.length === aChildren.length) {
26442         return {
26443             children: bChildren,
26444             moves: null
26445         }
26446     }
26447
26448     // O(MAX(N, M)) memory
26449     var newChildren = []
26450
26451     var freeIndex = 0
26452     var freeCount = bFree.length
26453     var deletedItems = 0
26454
26455     // Iterate through a and match a node in b
26456     // O(N) time,
26457     for (var i = 0 ; i < aChildren.length; i++) {
26458         var aItem = aChildren[i]
26459         var itemIndex
26460
26461         if (aItem.key) {
26462             if (bKeys.hasOwnProperty(aItem.key)) {
26463                 // Match up the old keys
26464                 itemIndex = bKeys[aItem.key]
26465                 newChildren.push(bChildren[itemIndex])
26466
26467             } else {
26468                 // Remove old keyed items
26469                 itemIndex = i - deletedItems++
26470                 newChildren.push(null)
26471             }
26472         } else {
26473             // Match the item in a with the next free item in b
26474             if (freeIndex < freeCount) {
26475                 itemIndex = bFree[freeIndex++]
26476                 newChildren.push(bChildren[itemIndex])
26477             } else {
26478                 // There are no free items in b to match with
26479                 // the free items in a, so the extra free nodes
26480                 // are deleted.
26481                 itemIndex = i - deletedItems++
26482                 newChildren.push(null)
26483             }
26484         }
26485     }
26486
26487     var lastFreeIndex = freeIndex >= bFree.length ?
26488         bChildren.length :
26489         bFree[freeIndex]
26490
26491     // Iterate through b and append any new keys
26492     // O(M) time
26493     for (var j = 0; j < bChildren.length; j++) {
26494         var newItem = bChildren[j]
26495
26496         if (newItem.key) {
26497             if (!aKeys.hasOwnProperty(newItem.key)) {
26498                 // Add any new keyed items
26499                 // We are adding new items to the end and then sorting them
26500                 // in place. In future we should insert new items in place.
26501                 newChildren.push(newItem)
26502             }
26503         } else if (j >= lastFreeIndex) {
26504             // Add any leftover non-keyed items
26505             newChildren.push(newItem)
26506         }
26507     }
26508
26509     var simulate = newChildren.slice()
26510     var simulateIndex = 0
26511     var removes = []
26512     var inserts = []
26513     var simulateItem
26514
26515     for (var k = 0; k < bChildren.length;) {
26516         var wantedItem = bChildren[k]
26517         simulateItem = simulate[simulateIndex]
26518
26519         // remove items
26520         while (simulateItem === null && simulate.length) {
26521             removes.push(remove(simulate, simulateIndex, null))
26522             simulateItem = simulate[simulateIndex]
26523         }
26524
26525         if (!simulateItem || simulateItem.key !== wantedItem.key) {
26526             // if we need a key in this position...
26527             if (wantedItem.key) {
26528                 if (simulateItem && simulateItem.key) {
26529                     // if an insert doesn't put this key in place, it needs to move
26530                     if (bKeys[simulateItem.key] !== k + 1) {
26531                         removes.push(remove(simulate, simulateIndex, simulateItem.key))
26532                         simulateItem = simulate[simulateIndex]
26533                         // if the remove didn't put the wanted item in place, we need to insert it
26534                         if (!simulateItem || simulateItem.key !== wantedItem.key) {
26535                             inserts.push({key: wantedItem.key, to: k})
26536                         }
26537                         // items are matching, so skip ahead
26538                         else {
26539                             simulateIndex++
26540                         }
26541                     }
26542                     else {
26543                         inserts.push({key: wantedItem.key, to: k})
26544                     }
26545                 }
26546                 else {
26547                     inserts.push({key: wantedItem.key, to: k})
26548                 }
26549                 k++
26550             }
26551             // a key in simulate has no matching wanted key, remove it
26552             else if (simulateItem && simulateItem.key) {
26553                 removes.push(remove(simulate, simulateIndex, simulateItem.key))
26554             }
26555         }
26556         else {
26557             simulateIndex++
26558             k++
26559         }
26560     }
26561
26562     // remove all the remaining nodes from simulate
26563     while(simulateIndex < simulate.length) {
26564         simulateItem = simulate[simulateIndex]
26565         removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
26566     }
26567
26568     // If the only moves we have are deletes then we can just
26569     // let the delete patch remove these items.
26570     if (removes.length === deletedItems && !inserts.length) {
26571         return {
26572             children: newChildren,
26573             moves: null
26574         }
26575     }
26576
26577     return {
26578         children: newChildren,
26579         moves: {
26580             removes: removes,
26581             inserts: inserts
26582         }
26583     }
26584 }
26585
26586 function remove(arr, index, key) {
26587     arr.splice(index, 1)
26588
26589     return {
26590         from: index,
26591         key: key
26592     }
26593 }
26594
26595 function keyIndex(children) {
26596     var keys = {}
26597     var free = []
26598     var length = children.length
26599
26600     for (var i = 0; i < length; i++) {
26601         var child = children[i]
26602
26603         if (child.key) {
26604             keys[child.key] = i
26605         } else {
26606             free.push(i)
26607         }
26608     }
26609
26610     return {
26611         keys: keys,     // A hash of key name to index
26612         free: free      // An array of unkeyed item indices
26613     }
26614 }
26615
26616 function appendPatch(apply, patch) {
26617     if (apply) {
26618         if (isArray(apply)) {
26619             apply.push(patch)
26620         } else {
26621             apply = [apply, patch]
26622         }
26623
26624         return apply
26625     } else {
26626         return patch
26627     }
26628 }
26629
26630 },{"../vnode/handle-thunk":259,"../vnode/is-thunk":260,"../vnode/is-vnode":262,"../vnode/is-vtext":263,"../vnode/is-widget":264,"../vnode/vpatch":267,"./diff-props":269,"x-is-array":289}],271:[function(require,module,exports){
26631 /** @license MIT License (c) copyright 2010-2014 original author or authors */
26632 /** @author Brian Cavalier */
26633 /** @author John Hann */
26634
26635 (function(define) { 'use strict';
26636 define(function (require) {
26637
26638         var makePromise = require('./makePromise');
26639         var Scheduler = require('./Scheduler');
26640         var async = require('./env').asap;
26641
26642         return makePromise({
26643                 scheduler: new Scheduler(async)
26644         });
26645
26646 });
26647 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
26648
26649 },{"./Scheduler":272,"./env":284,"./makePromise":286}],272:[function(require,module,exports){
26650 /** @license MIT License (c) copyright 2010-2014 original author or authors */
26651 /** @author Brian Cavalier */
26652 /** @author John Hann */
26653
26654 (function(define) { 'use strict';
26655 define(function() {
26656
26657         // Credit to Twisol (https://github.com/Twisol) for suggesting
26658         // this type of extensible queue + trampoline approach for next-tick conflation.
26659
26660         /**
26661          * Async task scheduler
26662          * @param {function} async function to schedule a single async function
26663          * @constructor
26664          */
26665         function Scheduler(async) {
26666                 this._async = async;
26667                 this._running = false;
26668
26669                 this._queue = this;
26670                 this._queueLen = 0;
26671                 this._afterQueue = {};
26672                 this._afterQueueLen = 0;
26673
26674                 var self = this;
26675                 this.drain = function() {
26676                         self._drain();
26677                 };
26678         }
26679
26680         /**
26681          * Enqueue a task
26682          * @param {{ run:function }} task
26683          */
26684         Scheduler.prototype.enqueue = function(task) {
26685                 this._queue[this._queueLen++] = task;
26686                 this.run();
26687         };
26688
26689         /**
26690          * Enqueue a task to run after the main task queue
26691          * @param {{ run:function }} task
26692          */
26693         Scheduler.prototype.afterQueue = function(task) {
26694                 this._afterQueue[this._afterQueueLen++] = task;
26695                 this.run();
26696         };
26697
26698         Scheduler.prototype.run = function() {
26699                 if (!this._running) {
26700                         this._running = true;
26701                         this._async(this.drain);
26702                 }
26703         };
26704
26705         /**
26706          * Drain the handler queue entirely, and then the after queue
26707          */
26708         Scheduler.prototype._drain = function() {
26709                 var i = 0;
26710                 for (; i < this._queueLen; ++i) {
26711                         this._queue[i].run();
26712                         this._queue[i] = void 0;
26713                 }
26714
26715                 this._queueLen = 0;
26716                 this._running = false;
26717
26718                 for (i = 0; i < this._afterQueueLen; ++i) {
26719                         this._afterQueue[i].run();
26720                         this._afterQueue[i] = void 0;
26721                 }
26722
26723                 this._afterQueueLen = 0;
26724         };
26725
26726         return Scheduler;
26727
26728 });
26729 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
26730
26731 },{}],273:[function(require,module,exports){
26732 /** @license MIT License (c) copyright 2010-2014 original author or authors */
26733 /** @author Brian Cavalier */
26734 /** @author John Hann */
26735
26736 (function(define) { 'use strict';
26737 define(function() {
26738
26739         /**
26740          * Custom error type for promises rejected by promise.timeout
26741          * @param {string} message
26742          * @constructor
26743          */
26744         function TimeoutError (message) {
26745                 Error.call(this);
26746                 this.message = message;
26747                 this.name = TimeoutError.name;
26748                 if (typeof Error.captureStackTrace === 'function') {
26749                         Error.captureStackTrace(this, TimeoutError);
26750                 }
26751         }
26752
26753         TimeoutError.prototype = Object.create(Error.prototype);
26754         TimeoutError.prototype.constructor = TimeoutError;
26755
26756         return TimeoutError;
26757 });
26758 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
26759 },{}],274:[function(require,module,exports){
26760 /** @license MIT License (c) copyright 2010-2014 original author or authors */
26761 /** @author Brian Cavalier */
26762 /** @author John Hann */
26763
26764 (function(define) { 'use strict';
26765 define(function() {
26766
26767         makeApply.tryCatchResolve = tryCatchResolve;
26768
26769         return makeApply;
26770
26771         function makeApply(Promise, call) {
26772                 if(arguments.length < 2) {
26773                         call = tryCatchResolve;
26774                 }
26775
26776                 return apply;
26777
26778                 function apply(f, thisArg, args) {
26779                         var p = Promise._defer();
26780                         var l = args.length;
26781                         var params = new Array(l);
26782                         callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
26783
26784                         return p;
26785                 }
26786
26787                 function callAndResolve(c, h) {
26788                         if(c.i < 0) {
26789                                 return call(c.f, c.thisArg, c.params, h);
26790                         }
26791
26792                         var handler = Promise._handler(c.args[c.i]);
26793                         handler.fold(callAndResolveNext, c, void 0, h);
26794                 }
26795
26796                 function callAndResolveNext(c, x, h) {
26797                         c.params[c.i] = x;
26798                         c.i -= 1;
26799                         callAndResolve(c, h);
26800                 }
26801         }
26802
26803         function tryCatchResolve(f, thisArg, args, resolver) {
26804                 try {
26805                         resolver.resolve(f.apply(thisArg, args));
26806                 } catch(e) {
26807                         resolver.reject(e);
26808                 }
26809         }
26810
26811 });
26812 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
26813
26814
26815
26816 },{}],275:[function(require,module,exports){
26817 /** @license MIT License (c) copyright 2010-2014 original author or authors */
26818 /** @author Brian Cavalier */
26819 /** @author John Hann */
26820
26821 (function(define) { 'use strict';
26822 define(function(require) {
26823
26824         var state = require('../state');
26825         var applier = require('../apply');
26826
26827         return function array(Promise) {
26828
26829                 var applyFold = applier(Promise);
26830                 var toPromise = Promise.resolve;
26831                 var all = Promise.all;
26832
26833                 var ar = Array.prototype.reduce;
26834                 var arr = Array.prototype.reduceRight;
26835                 var slice = Array.prototype.slice;
26836
26837                 // Additional array combinators
26838
26839                 Promise.any = any;
26840                 Promise.some = some;
26841                 Promise.settle = settle;
26842
26843                 Promise.map = map;
26844                 Promise.filter = filter;
26845                 Promise.reduce = reduce;
26846                 Promise.reduceRight = reduceRight;
26847
26848                 /**
26849                  * When this promise fulfills with an array, do
26850                  * onFulfilled.apply(void 0, array)
26851                  * @param {function} onFulfilled function to apply
26852                  * @returns {Promise} promise for the result of applying onFulfilled
26853                  */
26854                 Promise.prototype.spread = function(onFulfilled) {
26855                         return this.then(all).then(function(array) {
26856                                 return onFulfilled.apply(this, array);
26857                         });
26858                 };
26859
26860                 return Promise;
26861
26862                 /**
26863                  * One-winner competitive race.
26864                  * Return a promise that will fulfill when one of the promises
26865                  * in the input array fulfills, or will reject when all promises
26866                  * have rejected.
26867                  * @param {array} promises
26868                  * @returns {Promise} promise for the first fulfilled value
26869                  */
26870                 function any(promises) {
26871                         var p = Promise._defer();
26872                         var resolver = p._handler;
26873                         var l = promises.length>>>0;
26874
26875                         var pending = l;
26876                         var errors = [];
26877
26878                         for (var h, x, i = 0; i < l; ++i) {
26879                                 x = promises[i];
26880                                 if(x === void 0 && !(i in promises)) {
26881                                         --pending;
26882                                         continue;
26883                                 }
26884
26885                                 h = Promise._handler(x);
26886                                 if(h.state() > 0) {
26887                                         resolver.become(h);
26888                                         Promise._visitRemaining(promises, i, h);
26889                                         break;
26890                                 } else {
26891                                         h.visit(resolver, handleFulfill, handleReject);
26892                                 }
26893                         }
26894
26895                         if(pending === 0) {
26896                                 resolver.reject(new RangeError('any(): array must not be empty'));
26897                         }
26898
26899                         return p;
26900
26901                         function handleFulfill(x) {
26902                                 /*jshint validthis:true*/
26903                                 errors = null;
26904                                 this.resolve(x); // this === resolver
26905                         }
26906
26907                         function handleReject(e) {
26908                                 /*jshint validthis:true*/
26909                                 if(this.resolved) { // this === resolver
26910                                         return;
26911                                 }
26912
26913                                 errors.push(e);
26914                                 if(--pending === 0) {
26915                                         this.reject(errors);
26916                                 }
26917                         }
26918                 }
26919
26920                 /**
26921                  * N-winner competitive race
26922                  * Return a promise that will fulfill when n input promises have
26923                  * fulfilled, or will reject when it becomes impossible for n
26924                  * input promises to fulfill (ie when promises.length - n + 1
26925                  * have rejected)
26926                  * @param {array} promises
26927                  * @param {number} n
26928                  * @returns {Promise} promise for the earliest n fulfillment values
26929                  *
26930                  * @deprecated
26931                  */
26932                 function some(promises, n) {
26933                         /*jshint maxcomplexity:7*/
26934                         var p = Promise._defer();
26935                         var resolver = p._handler;
26936
26937                         var results = [];
26938                         var errors = [];
26939
26940                         var l = promises.length>>>0;
26941                         var nFulfill = 0;
26942                         var nReject;
26943                         var x, i; // reused in both for() loops
26944
26945                         // First pass: count actual array items
26946                         for(i=0; i<l; ++i) {
26947                                 x = promises[i];
26948                                 if(x === void 0 && !(i in promises)) {
26949                                         continue;
26950                                 }
26951                                 ++nFulfill;
26952                         }
26953
26954                         // Compute actual goals
26955                         n = Math.max(n, 0);
26956                         nReject = (nFulfill - n + 1);
26957                         nFulfill = Math.min(n, nFulfill);
26958
26959                         if(n > nFulfill) {
26960                                 resolver.reject(new RangeError('some(): array must contain at least '
26961                                 + n + ' item(s), but had ' + nFulfill));
26962                         } else if(nFulfill === 0) {
26963                                 resolver.resolve(results);
26964                         }
26965
26966                         // Second pass: observe each array item, make progress toward goals
26967                         for(i=0; i<l; ++i) {
26968                                 x = promises[i];
26969                                 if(x === void 0 && !(i in promises)) {
26970                                         continue;
26971                                 }
26972
26973                                 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
26974                         }
26975
26976                         return p;
26977
26978                         function fulfill(x) {
26979                                 /*jshint validthis:true*/
26980                                 if(this.resolved) { // this === resolver
26981                                         return;
26982                                 }
26983
26984                                 results.push(x);
26985                                 if(--nFulfill === 0) {
26986                                         errors = null;
26987                                         this.resolve(results);
26988                                 }
26989                         }
26990
26991                         function reject(e) {
26992                                 /*jshint validthis:true*/
26993                                 if(this.resolved) { // this === resolver
26994                                         return;
26995                                 }
26996
26997                                 errors.push(e);
26998                                 if(--nReject === 0) {
26999                                         results = null;
27000                                         this.reject(errors);
27001                                 }
27002                         }
27003                 }
27004
27005                 /**
27006                  * Apply f to the value of each promise in a list of promises
27007                  * and return a new list containing the results.
27008                  * @param {array} promises
27009                  * @param {function(x:*, index:Number):*} f mapping function
27010                  * @returns {Promise}
27011                  */
27012                 function map(promises, f) {
27013                         return Promise._traverse(f, promises);
27014                 }
27015
27016                 /**
27017                  * Filter the provided array of promises using the provided predicate.  Input may
27018                  * contain promises and values
27019                  * @param {Array} promises array of promises and values
27020                  * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
27021                  *  Must return truthy (or promise for truthy) for items to retain.
27022                  * @returns {Promise} promise that will fulfill with an array containing all items
27023                  *  for which predicate returned truthy.
27024                  */
27025                 function filter(promises, predicate) {
27026                         var a = slice.call(promises);
27027                         return Promise._traverse(predicate, a).then(function(keep) {
27028                                 return filterSync(a, keep);
27029                         });
27030                 }
27031
27032                 function filterSync(promises, keep) {
27033                         // Safe because we know all promises have fulfilled if we've made it this far
27034                         var l = keep.length;
27035                         var filtered = new Array(l);
27036                         for(var i=0, j=0; i<l; ++i) {
27037                                 if(keep[i]) {
27038                                         filtered[j++] = Promise._handler(promises[i]).value;
27039                                 }
27040                         }
27041                         filtered.length = j;
27042                         return filtered;
27043
27044                 }
27045
27046                 /**
27047                  * Return a promise that will always fulfill with an array containing
27048                  * the outcome states of all input promises.  The returned promise
27049                  * will never reject.
27050                  * @param {Array} promises
27051                  * @returns {Promise} promise for array of settled state descriptors
27052                  */
27053                 function settle(promises) {
27054                         return all(promises.map(settleOne));
27055                 }
27056
27057                 function settleOne(p) {
27058                         // Optimize the case where we get an already-resolved when.js promise
27059                         //  by extracting its state:
27060                         var handler;
27061                         if (p instanceof Promise) {
27062                                 // This is our own Promise type and we can reach its handler internals:
27063                                 handler = p._handler.join();
27064                         }
27065                         if((handler && handler.state() === 0) || !handler) {
27066                                 // Either still pending, or not a Promise at all:
27067                                 return toPromise(p).then(state.fulfilled, state.rejected);
27068                         }
27069
27070                         // The promise is our own, but it is already resolved. Take a shortcut.
27071                         // Since we're not actually handling the resolution, we need to disable
27072                         // rejection reporting.
27073                         handler._unreport();
27074                         return state.inspect(handler);
27075                 }
27076
27077                 /**
27078                  * Traditional reduce function, similar to `Array.prototype.reduce()`, but
27079                  * input may contain promises and/or values, and reduceFunc
27080                  * may return either a value or a promise, *and* initialValue may
27081                  * be a promise for the starting value.
27082                  * @param {Array|Promise} promises array or promise for an array of anything,
27083                  *      may contain a mix of promises and values.
27084                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
27085                  * @returns {Promise} that will resolve to the final reduced value
27086                  */
27087                 function reduce(promises, f /*, initialValue */) {
27088                         return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
27089                                         : ar.call(promises, liftCombine(f));
27090                 }
27091
27092                 /**
27093                  * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
27094                  * input may contain promises and/or values, and reduceFunc
27095                  * may return either a value or a promise, *and* initialValue may
27096                  * be a promise for the starting value.
27097                  * @param {Array|Promise} promises array or promise for an array of anything,
27098                  *      may contain a mix of promises and values.
27099                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
27100                  * @returns {Promise} that will resolve to the final reduced value
27101                  */
27102                 function reduceRight(promises, f /*, initialValue */) {
27103                         return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
27104                                         : arr.call(promises, liftCombine(f));
27105                 }
27106
27107                 function liftCombine(f) {
27108                         return function(z, x, i) {
27109                                 return applyFold(f, void 0, [z,x,i]);
27110                         };
27111                 }
27112         };
27113
27114 });
27115 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
27116
27117 },{"../apply":274,"../state":287}],276:[function(require,module,exports){
27118 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27119 /** @author Brian Cavalier */
27120 /** @author John Hann */
27121
27122 (function(define) { 'use strict';
27123 define(function() {
27124
27125         return function flow(Promise) {
27126
27127                 var resolve = Promise.resolve;
27128                 var reject = Promise.reject;
27129                 var origCatch = Promise.prototype['catch'];
27130
27131                 /**
27132                  * Handle the ultimate fulfillment value or rejection reason, and assume
27133                  * responsibility for all errors.  If an error propagates out of result
27134                  * or handleFatalError, it will be rethrown to the host, resulting in a
27135                  * loud stack track on most platforms and a crash on some.
27136                  * @param {function?} onResult
27137                  * @param {function?} onError
27138                  * @returns {undefined}
27139                  */
27140                 Promise.prototype.done = function(onResult, onError) {
27141                         this._handler.visit(this._handler.receiver, onResult, onError);
27142                 };
27143
27144                 /**
27145                  * Add Error-type and predicate matching to catch.  Examples:
27146                  * promise.catch(TypeError, handleTypeError)
27147                  *   .catch(predicate, handleMatchedErrors)
27148                  *   .catch(handleRemainingErrors)
27149                  * @param onRejected
27150                  * @returns {*}
27151                  */
27152                 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
27153                         if (arguments.length < 2) {
27154                                 return origCatch.call(this, onRejected);
27155                         }
27156
27157                         if(typeof onRejected !== 'function') {
27158                                 return this.ensure(rejectInvalidPredicate);
27159                         }
27160
27161                         return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
27162                 };
27163
27164                 /**
27165                  * Wraps the provided catch handler, so that it will only be called
27166                  * if the predicate evaluates truthy
27167                  * @param {?function} handler
27168                  * @param {function} predicate
27169                  * @returns {function} conditional catch handler
27170                  */
27171                 function createCatchFilter(handler, predicate) {
27172                         return function(e) {
27173                                 return evaluatePredicate(e, predicate)
27174                                         ? handler.call(this, e)
27175                                         : reject(e);
27176                         };
27177                 }
27178
27179                 /**
27180                  * Ensures that onFulfilledOrRejected will be called regardless of whether
27181                  * this promise is fulfilled or rejected.  onFulfilledOrRejected WILL NOT
27182                  * receive the promises' value or reason.  Any returned value will be disregarded.
27183                  * onFulfilledOrRejected may throw or return a rejected promise to signal
27184                  * an additional error.
27185                  * @param {function} handler handler to be called regardless of
27186                  *  fulfillment or rejection
27187                  * @returns {Promise}
27188                  */
27189                 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
27190                         if(typeof handler !== 'function') {
27191                                 return this;
27192                         }
27193
27194                         return this.then(function(x) {
27195                                 return runSideEffect(handler, this, identity, x);
27196                         }, function(e) {
27197                                 return runSideEffect(handler, this, reject, e);
27198                         });
27199                 };
27200
27201                 function runSideEffect (handler, thisArg, propagate, value) {
27202                         var result = handler.call(thisArg);
27203                         return maybeThenable(result)
27204                                 ? propagateValue(result, propagate, value)
27205                                 : propagate(value);
27206                 }
27207
27208                 function propagateValue (result, propagate, x) {
27209                         return resolve(result).then(function () {
27210                                 return propagate(x);
27211                         });
27212                 }
27213
27214                 /**
27215                  * Recover from a failure by returning a defaultValue.  If defaultValue
27216                  * is a promise, it's fulfillment value will be used.  If defaultValue is
27217                  * a promise that rejects, the returned promise will reject with the
27218                  * same reason.
27219                  * @param {*} defaultValue
27220                  * @returns {Promise} new promise
27221                  */
27222                 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
27223                         return this.then(void 0, function() {
27224                                 return defaultValue;
27225                         });
27226                 };
27227
27228                 /**
27229                  * Shortcut for .then(function() { return value; })
27230                  * @param  {*} value
27231                  * @return {Promise} a promise that:
27232                  *  - is fulfilled if value is not a promise, or
27233                  *  - if value is a promise, will fulfill with its value, or reject
27234                  *    with its reason.
27235                  */
27236                 Promise.prototype['yield'] = function(value) {
27237                         return this.then(function() {
27238                                 return value;
27239                         });
27240                 };
27241
27242                 /**
27243                  * Runs a side effect when this promise fulfills, without changing the
27244                  * fulfillment value.
27245                  * @param {function} onFulfilledSideEffect
27246                  * @returns {Promise}
27247                  */
27248                 Promise.prototype.tap = function(onFulfilledSideEffect) {
27249                         return this.then(onFulfilledSideEffect)['yield'](this);
27250                 };
27251
27252                 return Promise;
27253         };
27254
27255         function rejectInvalidPredicate() {
27256                 throw new TypeError('catch predicate must be a function');
27257         }
27258
27259         function evaluatePredicate(e, predicate) {
27260                 return isError(predicate) ? e instanceof predicate : predicate(e);
27261         }
27262
27263         function isError(predicate) {
27264                 return predicate === Error
27265                         || (predicate != null && predicate.prototype instanceof Error);
27266         }
27267
27268         function maybeThenable(x) {
27269                 return (typeof x === 'object' || typeof x === 'function') && x !== null;
27270         }
27271
27272         function identity(x) {
27273                 return x;
27274         }
27275
27276 });
27277 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
27278
27279 },{}],277:[function(require,module,exports){
27280 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27281 /** @author Brian Cavalier */
27282 /** @author John Hann */
27283 /** @author Jeff Escalante */
27284
27285 (function(define) { 'use strict';
27286 define(function() {
27287
27288         return function fold(Promise) {
27289
27290                 Promise.prototype.fold = function(f, z) {
27291                         var promise = this._beget();
27292
27293                         this._handler.fold(function(z, x, to) {
27294                                 Promise._handler(z).fold(function(x, z, to) {
27295                                         to.resolve(f.call(this, z, x));
27296                                 }, x, this, to);
27297                         }, z, promise._handler.receiver, promise._handler);
27298
27299                         return promise;
27300                 };
27301
27302                 return Promise;
27303         };
27304
27305 });
27306 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
27307
27308 },{}],278:[function(require,module,exports){
27309 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27310 /** @author Brian Cavalier */
27311 /** @author John Hann */
27312
27313 (function(define) { 'use strict';
27314 define(function(require) {
27315
27316         var inspect = require('../state').inspect;
27317
27318         return function inspection(Promise) {
27319
27320                 Promise.prototype.inspect = function() {
27321                         return inspect(Promise._handler(this));
27322                 };
27323
27324                 return Promise;
27325         };
27326
27327 });
27328 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
27329
27330 },{"../state":287}],279:[function(require,module,exports){
27331 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27332 /** @author Brian Cavalier */
27333 /** @author John Hann */
27334
27335 (function(define) { 'use strict';
27336 define(function() {
27337
27338         return function generate(Promise) {
27339
27340                 var resolve = Promise.resolve;
27341
27342                 Promise.iterate = iterate;
27343                 Promise.unfold = unfold;
27344
27345                 return Promise;
27346
27347                 /**
27348                  * @deprecated Use github.com/cujojs/most streams and most.iterate
27349                  * Generate a (potentially infinite) stream of promised values:
27350                  * x, f(x), f(f(x)), etc. until condition(x) returns true
27351                  * @param {function} f function to generate a new x from the previous x
27352                  * @param {function} condition function that, given the current x, returns
27353                  *  truthy when the iterate should stop
27354                  * @param {function} handler function to handle the value produced by f
27355                  * @param {*|Promise} x starting value, may be a promise
27356                  * @return {Promise} the result of the last call to f before
27357                  *  condition returns true
27358                  */
27359                 function iterate(f, condition, handler, x) {
27360                         return unfold(function(x) {
27361                                 return [x, f(x)];
27362                         }, condition, handler, x);
27363                 }
27364
27365                 /**
27366                  * @deprecated Use github.com/cujojs/most streams and most.unfold
27367                  * Generate a (potentially infinite) stream of promised values
27368                  * by applying handler(generator(seed)) iteratively until
27369                  * condition(seed) returns true.
27370                  * @param {function} unspool function that generates a [value, newSeed]
27371                  *  given a seed.
27372                  * @param {function} condition function that, given the current seed, returns
27373                  *  truthy when the unfold should stop
27374                  * @param {function} handler function to handle the value produced by unspool
27375                  * @param x {*|Promise} starting value, may be a promise
27376                  * @return {Promise} the result of the last value produced by unspool before
27377                  *  condition returns true
27378                  */
27379                 function unfold(unspool, condition, handler, x) {
27380                         return resolve(x).then(function(seed) {
27381                                 return resolve(condition(seed)).then(function(done) {
27382                                         return done ? seed : resolve(unspool(seed)).spread(next);
27383                                 });
27384                         });
27385
27386                         function next(item, newSeed) {
27387                                 return resolve(handler(item)).then(function() {
27388                                         return unfold(unspool, condition, handler, newSeed);
27389                                 });
27390                         }
27391                 }
27392         };
27393
27394 });
27395 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
27396
27397 },{}],280:[function(require,module,exports){
27398 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27399 /** @author Brian Cavalier */
27400 /** @author John Hann */
27401
27402 (function(define) { 'use strict';
27403 define(function() {
27404
27405         return function progress(Promise) {
27406
27407                 /**
27408                  * @deprecated
27409                  * Register a progress handler for this promise
27410                  * @param {function} onProgress
27411                  * @returns {Promise}
27412                  */
27413                 Promise.prototype.progress = function(onProgress) {
27414                         return this.then(void 0, void 0, onProgress);
27415                 };
27416
27417                 return Promise;
27418         };
27419
27420 });
27421 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
27422
27423 },{}],281:[function(require,module,exports){
27424 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27425 /** @author Brian Cavalier */
27426 /** @author John Hann */
27427
27428 (function(define) { 'use strict';
27429 define(function(require) {
27430
27431         var env = require('../env');
27432         var TimeoutError = require('../TimeoutError');
27433
27434         function setTimeout(f, ms, x, y) {
27435                 return env.setTimer(function() {
27436                         f(x, y, ms);
27437                 }, ms);
27438         }
27439
27440         return function timed(Promise) {
27441                 /**
27442                  * Return a new promise whose fulfillment value is revealed only
27443                  * after ms milliseconds
27444                  * @param {number} ms milliseconds
27445                  * @returns {Promise}
27446                  */
27447                 Promise.prototype.delay = function(ms) {
27448                         var p = this._beget();
27449                         this._handler.fold(handleDelay, ms, void 0, p._handler);
27450                         return p;
27451                 };
27452
27453                 function handleDelay(ms, x, h) {
27454                         setTimeout(resolveDelay, ms, x, h);
27455                 }
27456
27457                 function resolveDelay(x, h) {
27458                         h.resolve(x);
27459                 }
27460
27461                 /**
27462                  * Return a new promise that rejects after ms milliseconds unless
27463                  * this promise fulfills earlier, in which case the returned promise
27464                  * fulfills with the same value.
27465                  * @param {number} ms milliseconds
27466                  * @param {Error|*=} reason optional rejection reason to use, defaults
27467                  *   to a TimeoutError if not provided
27468                  * @returns {Promise}
27469                  */
27470                 Promise.prototype.timeout = function(ms, reason) {
27471                         var p = this._beget();
27472                         var h = p._handler;
27473
27474                         var t = setTimeout(onTimeout, ms, reason, p._handler);
27475
27476                         this._handler.visit(h,
27477                                 function onFulfill(x) {
27478                                         env.clearTimer(t);
27479                                         this.resolve(x); // this = h
27480                                 },
27481                                 function onReject(x) {
27482                                         env.clearTimer(t);
27483                                         this.reject(x); // this = h
27484                                 },
27485                                 h.notify);
27486
27487                         return p;
27488                 };
27489
27490                 function onTimeout(reason, h, ms) {
27491                         var e = typeof reason === 'undefined'
27492                                 ? new TimeoutError('timed out after ' + ms + 'ms')
27493                                 : reason;
27494                         h.reject(e);
27495                 }
27496
27497                 return Promise;
27498         };
27499
27500 });
27501 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
27502
27503 },{"../TimeoutError":273,"../env":284}],282:[function(require,module,exports){
27504 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27505 /** @author Brian Cavalier */
27506 /** @author John Hann */
27507
27508 (function(define) { 'use strict';
27509 define(function(require) {
27510
27511         var setTimer = require('../env').setTimer;
27512         var format = require('../format');
27513
27514         return function unhandledRejection(Promise) {
27515
27516                 var logError = noop;
27517                 var logInfo = noop;
27518                 var localConsole;
27519
27520                 if(typeof console !== 'undefined') {
27521                         // Alias console to prevent things like uglify's drop_console option from
27522                         // removing console.log/error. Unhandled rejections fall into the same
27523                         // category as uncaught exceptions, and build tools shouldn't silence them.
27524                         localConsole = console;
27525                         logError = typeof localConsole.error !== 'undefined'
27526                                 ? function (e) { localConsole.error(e); }
27527                                 : function (e) { localConsole.log(e); };
27528
27529                         logInfo = typeof localConsole.info !== 'undefined'
27530                                 ? function (e) { localConsole.info(e); }
27531                                 : function (e) { localConsole.log(e); };
27532                 }
27533
27534                 Promise.onPotentiallyUnhandledRejection = function(rejection) {
27535                         enqueue(report, rejection);
27536                 };
27537
27538                 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
27539                         enqueue(unreport, rejection);
27540                 };
27541
27542                 Promise.onFatalRejection = function(rejection) {
27543                         enqueue(throwit, rejection.value);
27544                 };
27545
27546                 var tasks = [];
27547                 var reported = [];
27548                 var running = null;
27549
27550                 function report(r) {
27551                         if(!r.handled) {
27552                                 reported.push(r);
27553                                 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
27554                         }
27555                 }
27556
27557                 function unreport(r) {
27558                         var i = reported.indexOf(r);
27559                         if(i >= 0) {
27560                                 reported.splice(i, 1);
27561                                 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
27562                         }
27563                 }
27564
27565                 function enqueue(f, x) {
27566                         tasks.push(f, x);
27567                         if(running === null) {
27568                                 running = setTimer(flush, 0);
27569                         }
27570                 }
27571
27572                 function flush() {
27573                         running = null;
27574                         while(tasks.length > 0) {
27575                                 tasks.shift()(tasks.shift());
27576                         }
27577                 }
27578
27579                 return Promise;
27580         };
27581
27582         function throwit(e) {
27583                 throw e;
27584         }
27585
27586         function noop() {}
27587
27588 });
27589 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
27590
27591 },{"../env":284,"../format":285}],283:[function(require,module,exports){
27592 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27593 /** @author Brian Cavalier */
27594 /** @author John Hann */
27595
27596 (function(define) { 'use strict';
27597 define(function() {
27598
27599         return function addWith(Promise) {
27600                 /**
27601                  * Returns a promise whose handlers will be called with `this` set to
27602                  * the supplied receiver.  Subsequent promises derived from the
27603                  * returned promise will also have their handlers called with receiver
27604                  * as `this`. Calling `with` with undefined or no arguments will return
27605                  * a promise whose handlers will again be called in the usual Promises/A+
27606                  * way (no `this`) thus safely undoing any previous `with` in the
27607                  * promise chain.
27608                  *
27609                  * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
27610                  * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
27611                  *
27612                  * @param {object} receiver `this` value for all handlers attached to
27613                  *  the returned promise.
27614                  * @returns {Promise}
27615                  */
27616                 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
27617                         var p = this._beget();
27618                         var child = p._handler;
27619                         child.receiver = receiver;
27620                         this._handler.chain(child, receiver);
27621                         return p;
27622                 };
27623
27624                 return Promise;
27625         };
27626
27627 });
27628 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
27629
27630
27631 },{}],284:[function(require,module,exports){
27632 (function (process){
27633 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27634 /** @author Brian Cavalier */
27635 /** @author John Hann */
27636
27637 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
27638 (function(define) { 'use strict';
27639 define(function(require) {
27640         /*jshint maxcomplexity:6*/
27641
27642         // Sniff "best" async scheduling option
27643         // Prefer process.nextTick or MutationObserver, then check for
27644         // setTimeout, and finally vertx, since its the only env that doesn't
27645         // have setTimeout
27646
27647         var MutationObs;
27648         var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
27649
27650         // Default env
27651         var setTimer = function(f, ms) { return setTimeout(f, ms); };
27652         var clearTimer = function(t) { return clearTimeout(t); };
27653         var asap = function (f) { return capturedSetTimeout(f, 0); };
27654
27655         // Detect specific env
27656         if (isNode()) { // Node
27657                 asap = function (f) { return process.nextTick(f); };
27658
27659         } else if (MutationObs = hasMutationObserver()) { // Modern browser
27660                 asap = initMutationObserver(MutationObs);
27661
27662         } else if (!capturedSetTimeout) { // vert.x
27663                 var vertxRequire = require;
27664                 var vertx = vertxRequire('vertx');
27665                 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
27666                 clearTimer = vertx.cancelTimer;
27667                 asap = vertx.runOnLoop || vertx.runOnContext;
27668         }
27669
27670         return {
27671                 setTimer: setTimer,
27672                 clearTimer: clearTimer,
27673                 asap: asap
27674         };
27675
27676         function isNode () {
27677                 return typeof process !== 'undefined' &&
27678                         Object.prototype.toString.call(process) === '[object process]';
27679         }
27680
27681         function hasMutationObserver () {
27682             return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
27683                         (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
27684         }
27685
27686         function initMutationObserver(MutationObserver) {
27687                 var scheduled;
27688                 var node = document.createTextNode('');
27689                 var o = new MutationObserver(run);
27690                 o.observe(node, { characterData: true });
27691
27692                 function run() {
27693                         var f = scheduled;
27694                         scheduled = void 0;
27695                         f();
27696                 }
27697
27698                 var i = 0;
27699                 return function (f) {
27700                         scheduled = f;
27701                         node.data = (i ^= 1);
27702                 };
27703         }
27704 });
27705 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
27706
27707 }).call(this,require('_process'))
27708
27709 },{"_process":6}],285:[function(require,module,exports){
27710 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27711 /** @author Brian Cavalier */
27712 /** @author John Hann */
27713
27714 (function(define) { 'use strict';
27715 define(function() {
27716
27717         return {
27718                 formatError: formatError,
27719                 formatObject: formatObject,
27720                 tryStringify: tryStringify
27721         };
27722
27723         /**
27724          * Format an error into a string.  If e is an Error and has a stack property,
27725          * it's returned.  Otherwise, e is formatted using formatObject, with a
27726          * warning added about e not being a proper Error.
27727          * @param {*} e
27728          * @returns {String} formatted string, suitable for output to developers
27729          */
27730         function formatError(e) {
27731                 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
27732                 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
27733         }
27734
27735         /**
27736          * Format an object, detecting "plain" objects and running them through
27737          * JSON.stringify if possible.
27738          * @param {Object} o
27739          * @returns {string}
27740          */
27741         function formatObject(o) {
27742                 var s = String(o);
27743                 if(s === '[object Object]' && typeof JSON !== 'undefined') {
27744                         s = tryStringify(o, s);
27745                 }
27746                 return s;
27747         }
27748
27749         /**
27750          * Try to return the result of JSON.stringify(x).  If that fails, return
27751          * defaultValue
27752          * @param {*} x
27753          * @param {*} defaultValue
27754          * @returns {String|*} JSON.stringify(x) or defaultValue
27755          */
27756         function tryStringify(x, defaultValue) {
27757                 try {
27758                         return JSON.stringify(x);
27759                 } catch(e) {
27760                         return defaultValue;
27761                 }
27762         }
27763
27764 });
27765 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
27766
27767 },{}],286:[function(require,module,exports){
27768 (function (process){
27769 /** @license MIT License (c) copyright 2010-2014 original author or authors */
27770 /** @author Brian Cavalier */
27771 /** @author John Hann */
27772
27773 (function(define) { 'use strict';
27774 define(function() {
27775
27776         return function makePromise(environment) {
27777
27778                 var tasks = environment.scheduler;
27779                 var emitRejection = initEmitRejection();
27780
27781                 var objectCreate = Object.create ||
27782                         function(proto) {
27783                                 function Child() {}
27784                                 Child.prototype = proto;
27785                                 return new Child();
27786                         };
27787
27788                 /**
27789                  * Create a promise whose fate is determined by resolver
27790                  * @constructor
27791                  * @returns {Promise} promise
27792                  * @name Promise
27793                  */
27794                 function Promise(resolver, handler) {
27795                         this._handler = resolver === Handler ? handler : init(resolver);
27796                 }
27797
27798                 /**
27799                  * Run the supplied resolver
27800                  * @param resolver
27801                  * @returns {Pending}
27802                  */
27803                 function init(resolver) {
27804                         var handler = new Pending();
27805
27806                         try {
27807                                 resolver(promiseResolve, promiseReject, promiseNotify);
27808                         } catch (e) {
27809                                 promiseReject(e);
27810                         }
27811
27812                         return handler;
27813
27814                         /**
27815                          * Transition from pre-resolution state to post-resolution state, notifying
27816                          * all listeners of the ultimate fulfillment or rejection
27817                          * @param {*} x resolution value
27818                          */
27819                         function promiseResolve (x) {
27820                                 handler.resolve(x);
27821                         }
27822                         /**
27823                          * Reject this promise with reason, which will be used verbatim
27824                          * @param {Error|*} reason rejection reason, strongly suggested
27825                          *   to be an Error type
27826                          */
27827                         function promiseReject (reason) {
27828                                 handler.reject(reason);
27829                         }
27830
27831                         /**
27832                          * @deprecated
27833                          * Issue a progress event, notifying all progress listeners
27834                          * @param {*} x progress event payload to pass to all listeners
27835                          */
27836                         function promiseNotify (x) {
27837                                 handler.notify(x);
27838                         }
27839                 }
27840
27841                 // Creation
27842
27843                 Promise.resolve = resolve;
27844                 Promise.reject = reject;
27845                 Promise.never = never;
27846
27847                 Promise._defer = defer;
27848                 Promise._handler = getHandler;
27849
27850                 /**
27851                  * Returns a trusted promise. If x is already a trusted promise, it is
27852                  * returned, otherwise returns a new trusted Promise which follows x.
27853                  * @param  {*} x
27854                  * @return {Promise} promise
27855                  */
27856                 function resolve(x) {
27857                         return isPromise(x) ? x
27858                                 : new Promise(Handler, new Async(getHandler(x)));
27859                 }
27860
27861                 /**
27862                  * Return a reject promise with x as its reason (x is used verbatim)
27863                  * @param {*} x
27864                  * @returns {Promise} rejected promise
27865                  */
27866                 function reject(x) {
27867                         return new Promise(Handler, new Async(new Rejected(x)));
27868                 }
27869
27870                 /**
27871                  * Return a promise that remains pending forever
27872                  * @returns {Promise} forever-pending promise.
27873                  */
27874                 function never() {
27875                         return foreverPendingPromise; // Should be frozen
27876                 }
27877
27878                 /**
27879                  * Creates an internal {promise, resolver} pair
27880                  * @private
27881                  * @returns {Promise}
27882                  */
27883                 function defer() {
27884                         return new Promise(Handler, new Pending());
27885                 }
27886
27887                 // Transformation and flow control
27888
27889                 /**
27890                  * Transform this promise's fulfillment value, returning a new Promise
27891                  * for the transformed result.  If the promise cannot be fulfilled, onRejected
27892                  * is called with the reason.  onProgress *may* be called with updates toward
27893                  * this promise's fulfillment.
27894                  * @param {function=} onFulfilled fulfillment handler
27895                  * @param {function=} onRejected rejection handler
27896                  * @param {function=} onProgress @deprecated progress handler
27897                  * @return {Promise} new promise
27898                  */
27899                 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
27900                         var parent = this._handler;
27901                         var state = parent.join().state();
27902
27903                         if ((typeof onFulfilled !== 'function' && state > 0) ||
27904                                 (typeof onRejected !== 'function' && state < 0)) {
27905                                 // Short circuit: value will not change, simply share handler
27906                                 return new this.constructor(Handler, parent);
27907                         }
27908
27909                         var p = this._beget();
27910                         var child = p._handler;
27911
27912                         parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
27913
27914                         return p;
27915                 };
27916
27917                 /**
27918                  * If this promise cannot be fulfilled due to an error, call onRejected to
27919                  * handle the error. Shortcut for .then(undefined, onRejected)
27920                  * @param {function?} onRejected
27921                  * @return {Promise}
27922                  */
27923                 Promise.prototype['catch'] = function(onRejected) {
27924                         return this.then(void 0, onRejected);
27925                 };
27926
27927                 /**
27928                  * Creates a new, pending promise of the same type as this promise
27929                  * @private
27930                  * @returns {Promise}
27931                  */
27932                 Promise.prototype._beget = function() {
27933                         return begetFrom(this._handler, this.constructor);
27934                 };
27935
27936                 function begetFrom(parent, Promise) {
27937                         var child = new Pending(parent.receiver, parent.join().context);
27938                         return new Promise(Handler, child);
27939                 }
27940
27941                 // Array combinators
27942
27943                 Promise.all = all;
27944                 Promise.race = race;
27945                 Promise._traverse = traverse;
27946
27947                 /**
27948                  * Return a promise that will fulfill when all promises in the
27949                  * input array have fulfilled, or will reject when one of the
27950                  * promises rejects.
27951                  * @param {array} promises array of promises
27952                  * @returns {Promise} promise for array of fulfillment values
27953                  */
27954                 function all(promises) {
27955                         return traverseWith(snd, null, promises);
27956                 }
27957
27958                 /**
27959                  * Array<Promise<X>> -> Promise<Array<f(X)>>
27960                  * @private
27961                  * @param {function} f function to apply to each promise's value
27962                  * @param {Array} promises array of promises
27963                  * @returns {Promise} promise for transformed values
27964                  */
27965                 function traverse(f, promises) {
27966                         return traverseWith(tryCatch2, f, promises);
27967                 }
27968
27969                 function traverseWith(tryMap, f, promises) {
27970                         var handler = typeof f === 'function' ? mapAt : settleAt;
27971
27972                         var resolver = new Pending();
27973                         var pending = promises.length >>> 0;
27974                         var results = new Array(pending);
27975
27976                         for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
27977                                 x = promises[i];
27978
27979                                 if (x === void 0 && !(i in promises)) {
27980                                         --pending;
27981                                         continue;
27982                                 }
27983
27984                                 traverseAt(promises, handler, i, x, resolver);
27985                         }
27986
27987                         if(pending === 0) {
27988                                 resolver.become(new Fulfilled(results));
27989                         }
27990
27991                         return new Promise(Handler, resolver);
27992
27993                         function mapAt(i, x, resolver) {
27994                                 if(!resolver.resolved) {
27995                                         traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
27996                                 }
27997                         }
27998
27999                         function settleAt(i, x, resolver) {
28000                                 results[i] = x;
28001                                 if(--pending === 0) {
28002                                         resolver.become(new Fulfilled(results));
28003                                 }
28004                         }
28005                 }
28006
28007                 function traverseAt(promises, handler, i, x, resolver) {
28008                         if (maybeThenable(x)) {
28009                                 var h = getHandlerMaybeThenable(x);
28010                                 var s = h.state();
28011
28012                                 if (s === 0) {
28013                                         h.fold(handler, i, void 0, resolver);
28014                                 } else if (s > 0) {
28015                                         handler(i, h.value, resolver);
28016                                 } else {
28017                                         resolver.become(h);
28018                                         visitRemaining(promises, i+1, h);
28019                                 }
28020                         } else {
28021                                 handler(i, x, resolver);
28022                         }
28023                 }
28024
28025                 Promise._visitRemaining = visitRemaining;
28026                 function visitRemaining(promises, start, handler) {
28027                         for(var i=start; i<promises.length; ++i) {
28028                                 markAsHandled(getHandler(promises[i]), handler);
28029                         }
28030                 }
28031
28032                 function markAsHandled(h, handler) {
28033                         if(h === handler) {
28034                                 return;
28035                         }
28036
28037                         var s = h.state();
28038                         if(s === 0) {
28039                                 h.visit(h, void 0, h._unreport);
28040                         } else if(s < 0) {
28041                                 h._unreport();
28042                         }
28043                 }
28044
28045                 /**
28046                  * Fulfill-reject competitive race. Return a promise that will settle
28047                  * to the same state as the earliest input promise to settle.
28048                  *
28049                  * WARNING: The ES6 Promise spec requires that race()ing an empty array
28050                  * must return a promise that is pending forever.  This implementation
28051                  * returns a singleton forever-pending promise, the same singleton that is
28052                  * returned by Promise.never(), thus can be checked with ===
28053                  *
28054                  * @param {array} promises array of promises to race
28055                  * @returns {Promise} if input is non-empty, a promise that will settle
28056                  * to the same outcome as the earliest input promise to settle. if empty
28057                  * is empty, returns a promise that will never settle.
28058                  */
28059                 function race(promises) {
28060                         if(typeof promises !== 'object' || promises === null) {
28061                                 return reject(new TypeError('non-iterable passed to race()'));
28062                         }
28063
28064                         // Sigh, race([]) is untestable unless we return *something*
28065                         // that is recognizable without calling .then() on it.
28066                         return promises.length === 0 ? never()
28067                                  : promises.length === 1 ? resolve(promises[0])
28068                                  : runRace(promises);
28069                 }
28070
28071                 function runRace(promises) {
28072                         var resolver = new Pending();
28073                         var i, x, h;
28074                         for(i=0; i<promises.length; ++i) {
28075                                 x = promises[i];
28076                                 if (x === void 0 && !(i in promises)) {
28077                                         continue;
28078                                 }
28079
28080                                 h = getHandler(x);
28081                                 if(h.state() !== 0) {
28082                                         resolver.become(h);
28083                                         visitRemaining(promises, i+1, h);
28084                                         break;
28085                                 } else {
28086                                         h.visit(resolver, resolver.resolve, resolver.reject);
28087                                 }
28088                         }
28089                         return new Promise(Handler, resolver);
28090                 }
28091
28092                 // Promise internals
28093                 // Below this, everything is @private
28094
28095                 /**
28096                  * Get an appropriate handler for x, without checking for cycles
28097                  * @param {*} x
28098                  * @returns {object} handler
28099                  */
28100                 function getHandler(x) {
28101                         if(isPromise(x)) {
28102                                 return x._handler.join();
28103                         }
28104                         return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
28105                 }
28106
28107                 /**
28108                  * Get a handler for thenable x.
28109                  * NOTE: You must only call this if maybeThenable(x) == true
28110                  * @param {object|function|Promise} x
28111                  * @returns {object} handler
28112                  */
28113                 function getHandlerMaybeThenable(x) {
28114                         return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
28115                 }
28116
28117                 /**
28118                  * Get a handler for potentially untrusted thenable x
28119                  * @param {*} x
28120                  * @returns {object} handler
28121                  */
28122                 function getHandlerUntrusted(x) {
28123                         try {
28124                                 var untrustedThen = x.then;
28125                                 return typeof untrustedThen === 'function'
28126                                         ? new Thenable(untrustedThen, x)
28127                                         : new Fulfilled(x);
28128                         } catch(e) {
28129                                 return new Rejected(e);
28130                         }
28131                 }
28132
28133                 /**
28134                  * Handler for a promise that is pending forever
28135                  * @constructor
28136                  */
28137                 function Handler() {}
28138
28139                 Handler.prototype.when
28140                         = Handler.prototype.become
28141                         = Handler.prototype.notify // deprecated
28142                         = Handler.prototype.fail
28143                         = Handler.prototype._unreport
28144                         = Handler.prototype._report
28145                         = noop;
28146
28147                 Handler.prototype._state = 0;
28148
28149                 Handler.prototype.state = function() {
28150                         return this._state;
28151                 };
28152
28153                 /**
28154                  * Recursively collapse handler chain to find the handler
28155                  * nearest to the fully resolved value.
28156                  * @returns {object} handler nearest the fully resolved value
28157                  */
28158                 Handler.prototype.join = function() {
28159                         var h = this;
28160                         while(h.handler !== void 0) {
28161                                 h = h.handler;
28162                         }
28163                         return h;
28164                 };
28165
28166                 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
28167                         this.when({
28168                                 resolver: to,
28169                                 receiver: receiver,
28170                                 fulfilled: fulfilled,
28171                                 rejected: rejected,
28172                                 progress: progress
28173                         });
28174                 };
28175
28176                 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
28177                         this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
28178                 };
28179
28180                 Handler.prototype.fold = function(f, z, c, to) {
28181                         this.when(new Fold(f, z, c, to));
28182                 };
28183
28184                 /**
28185                  * Handler that invokes fail() on any handler it becomes
28186                  * @constructor
28187                  */
28188                 function FailIfRejected() {}
28189
28190                 inherit(Handler, FailIfRejected);
28191
28192                 FailIfRejected.prototype.become = function(h) {
28193                         h.fail();
28194                 };
28195
28196                 var failIfRejected = new FailIfRejected();
28197
28198                 /**
28199                  * Handler that manages a queue of consumers waiting on a pending promise
28200                  * @constructor
28201                  */
28202                 function Pending(receiver, inheritedContext) {
28203                         Promise.createContext(this, inheritedContext);
28204
28205                         this.consumers = void 0;
28206                         this.receiver = receiver;
28207                         this.handler = void 0;
28208                         this.resolved = false;
28209                 }
28210
28211                 inherit(Handler, Pending);
28212
28213                 Pending.prototype._state = 0;
28214
28215                 Pending.prototype.resolve = function(x) {
28216                         this.become(getHandler(x));
28217                 };
28218
28219                 Pending.prototype.reject = function(x) {
28220                         if(this.resolved) {
28221                                 return;
28222                         }
28223
28224                         this.become(new Rejected(x));
28225                 };
28226
28227                 Pending.prototype.join = function() {
28228                         if (!this.resolved) {
28229                                 return this;
28230                         }
28231
28232                         var h = this;
28233
28234                         while (h.handler !== void 0) {
28235                                 h = h.handler;
28236                                 if (h === this) {
28237                                         return this.handler = cycle();
28238                                 }
28239                         }
28240
28241                         return h;
28242                 };
28243
28244                 Pending.prototype.run = function() {
28245                         var q = this.consumers;
28246                         var handler = this.handler;
28247                         this.handler = this.handler.join();
28248                         this.consumers = void 0;
28249
28250                         for (var i = 0; i < q.length; ++i) {
28251                                 handler.when(q[i]);
28252                         }
28253                 };
28254
28255                 Pending.prototype.become = function(handler) {
28256                         if(this.resolved) {
28257                                 return;
28258                         }
28259
28260                         this.resolved = true;
28261                         this.handler = handler;
28262                         if(this.consumers !== void 0) {
28263                                 tasks.enqueue(this);
28264                         }
28265
28266                         if(this.context !== void 0) {
28267                                 handler._report(this.context);
28268                         }
28269                 };
28270
28271                 Pending.prototype.when = function(continuation) {
28272                         if(this.resolved) {
28273                                 tasks.enqueue(new ContinuationTask(continuation, this.handler));
28274                         } else {
28275                                 if(this.consumers === void 0) {
28276                                         this.consumers = [continuation];
28277                                 } else {
28278                                         this.consumers.push(continuation);
28279                                 }
28280                         }
28281                 };
28282
28283                 /**
28284                  * @deprecated
28285                  */
28286                 Pending.prototype.notify = function(x) {
28287                         if(!this.resolved) {
28288                                 tasks.enqueue(new ProgressTask(x, this));
28289                         }
28290                 };
28291
28292                 Pending.prototype.fail = function(context) {
28293                         var c = typeof context === 'undefined' ? this.context : context;
28294                         this.resolved && this.handler.join().fail(c);
28295                 };
28296
28297                 Pending.prototype._report = function(context) {
28298                         this.resolved && this.handler.join()._report(context);
28299                 };
28300
28301                 Pending.prototype._unreport = function() {
28302                         this.resolved && this.handler.join()._unreport();
28303                 };
28304
28305                 /**
28306                  * Wrap another handler and force it into a future stack
28307                  * @param {object} handler
28308                  * @constructor
28309                  */
28310                 function Async(handler) {
28311                         this.handler = handler;
28312                 }
28313
28314                 inherit(Handler, Async);
28315
28316                 Async.prototype.when = function(continuation) {
28317                         tasks.enqueue(new ContinuationTask(continuation, this));
28318                 };
28319
28320                 Async.prototype._report = function(context) {
28321                         this.join()._report(context);
28322                 };
28323
28324                 Async.prototype._unreport = function() {
28325                         this.join()._unreport();
28326                 };
28327
28328                 /**
28329                  * Handler that wraps an untrusted thenable and assimilates it in a future stack
28330                  * @param {function} then
28331                  * @param {{then: function}} thenable
28332                  * @constructor
28333                  */
28334                 function Thenable(then, thenable) {
28335                         Pending.call(this);
28336                         tasks.enqueue(new AssimilateTask(then, thenable, this));
28337                 }
28338
28339                 inherit(Pending, Thenable);
28340
28341                 /**
28342                  * Handler for a fulfilled promise
28343                  * @param {*} x fulfillment value
28344                  * @constructor
28345                  */
28346                 function Fulfilled(x) {
28347                         Promise.createContext(this);
28348                         this.value = x;
28349                 }
28350
28351                 inherit(Handler, Fulfilled);
28352
28353                 Fulfilled.prototype._state = 1;
28354
28355                 Fulfilled.prototype.fold = function(f, z, c, to) {
28356                         runContinuation3(f, z, this, c, to);
28357                 };
28358
28359                 Fulfilled.prototype.when = function(cont) {
28360                         runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
28361                 };
28362
28363                 var errorId = 0;
28364
28365                 /**
28366                  * Handler for a rejected promise
28367                  * @param {*} x rejection reason
28368                  * @constructor
28369                  */
28370                 function Rejected(x) {
28371                         Promise.createContext(this);
28372
28373                         this.id = ++errorId;
28374                         this.value = x;
28375                         this.handled = false;
28376                         this.reported = false;
28377
28378                         this._report();
28379                 }
28380
28381                 inherit(Handler, Rejected);
28382
28383                 Rejected.prototype._state = -1;
28384
28385                 Rejected.prototype.fold = function(f, z, c, to) {
28386                         to.become(this);
28387                 };
28388
28389                 Rejected.prototype.when = function(cont) {
28390                         if(typeof cont.rejected === 'function') {
28391                                 this._unreport();
28392                         }
28393                         runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
28394                 };
28395
28396                 Rejected.prototype._report = function(context) {
28397                         tasks.afterQueue(new ReportTask(this, context));
28398                 };
28399
28400                 Rejected.prototype._unreport = function() {
28401                         if(this.handled) {
28402                                 return;
28403                         }
28404                         this.handled = true;
28405                         tasks.afterQueue(new UnreportTask(this));
28406                 };
28407
28408                 Rejected.prototype.fail = function(context) {
28409                         this.reported = true;
28410                         emitRejection('unhandledRejection', this);
28411                         Promise.onFatalRejection(this, context === void 0 ? this.context : context);
28412                 };
28413
28414                 function ReportTask(rejection, context) {
28415                         this.rejection = rejection;
28416                         this.context = context;
28417                 }
28418
28419                 ReportTask.prototype.run = function() {
28420                         if(!this.rejection.handled && !this.rejection.reported) {
28421                                 this.rejection.reported = true;
28422                                 emitRejection('unhandledRejection', this.rejection) ||
28423                                         Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
28424                         }
28425                 };
28426
28427                 function UnreportTask(rejection) {
28428                         this.rejection = rejection;
28429                 }
28430
28431                 UnreportTask.prototype.run = function() {
28432                         if(this.rejection.reported) {
28433                                 emitRejection('rejectionHandled', this.rejection) ||
28434                                         Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
28435                         }
28436                 };
28437
28438                 // Unhandled rejection hooks
28439                 // By default, everything is a noop
28440
28441                 Promise.createContext
28442                         = Promise.enterContext
28443                         = Promise.exitContext
28444                         = Promise.onPotentiallyUnhandledRejection
28445                         = Promise.onPotentiallyUnhandledRejectionHandled
28446                         = Promise.onFatalRejection
28447                         = noop;
28448
28449                 // Errors and singletons
28450
28451                 var foreverPendingHandler = new Handler();
28452                 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
28453
28454                 function cycle() {
28455                         return new Rejected(new TypeError('Promise cycle'));
28456                 }
28457
28458                 // Task runners
28459
28460                 /**
28461                  * Run a single consumer
28462                  * @constructor
28463                  */
28464                 function ContinuationTask(continuation, handler) {
28465                         this.continuation = continuation;
28466                         this.handler = handler;
28467                 }
28468
28469                 ContinuationTask.prototype.run = function() {
28470                         this.handler.join().when(this.continuation);
28471                 };
28472
28473                 /**
28474                  * Run a queue of progress handlers
28475                  * @constructor
28476                  */
28477                 function ProgressTask(value, handler) {
28478                         this.handler = handler;
28479                         this.value = value;
28480                 }
28481
28482                 ProgressTask.prototype.run = function() {
28483                         var q = this.handler.consumers;
28484                         if(q === void 0) {
28485                                 return;
28486                         }
28487
28488                         for (var c, i = 0; i < q.length; ++i) {
28489                                 c = q[i];
28490                                 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
28491                         }
28492                 };
28493
28494                 /**
28495                  * Assimilate a thenable, sending it's value to resolver
28496                  * @param {function} then
28497                  * @param {object|function} thenable
28498                  * @param {object} resolver
28499                  * @constructor
28500                  */
28501                 function AssimilateTask(then, thenable, resolver) {
28502                         this._then = then;
28503                         this.thenable = thenable;
28504                         this.resolver = resolver;
28505                 }
28506
28507                 AssimilateTask.prototype.run = function() {
28508                         var h = this.resolver;
28509                         tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
28510
28511                         function _resolve(x) { h.resolve(x); }
28512                         function _reject(x)  { h.reject(x); }
28513                         function _notify(x)  { h.notify(x); }
28514                 };
28515
28516                 function tryAssimilate(then, thenable, resolve, reject, notify) {
28517                         try {
28518                                 then.call(thenable, resolve, reject, notify);
28519                         } catch (e) {
28520                                 reject(e);
28521                         }
28522                 }
28523
28524                 /**
28525                  * Fold a handler value with z
28526                  * @constructor
28527                  */
28528                 function Fold(f, z, c, to) {
28529                         this.f = f; this.z = z; this.c = c; this.to = to;
28530                         this.resolver = failIfRejected;
28531                         this.receiver = this;
28532                 }
28533
28534                 Fold.prototype.fulfilled = function(x) {
28535                         this.f.call(this.c, this.z, x, this.to);
28536                 };
28537
28538                 Fold.prototype.rejected = function(x) {
28539                         this.to.reject(x);
28540                 };
28541
28542                 Fold.prototype.progress = function(x) {
28543                         this.to.notify(x);
28544                 };
28545
28546                 // Other helpers
28547
28548                 /**
28549                  * @param {*} x
28550                  * @returns {boolean} true iff x is a trusted Promise
28551                  */
28552                 function isPromise(x) {
28553                         return x instanceof Promise;
28554                 }
28555
28556                 /**
28557                  * Test just enough to rule out primitives, in order to take faster
28558                  * paths in some code
28559                  * @param {*} x
28560                  * @returns {boolean} false iff x is guaranteed *not* to be a thenable
28561                  */
28562                 function maybeThenable(x) {
28563                         return (typeof x === 'object' || typeof x === 'function') && x !== null;
28564                 }
28565
28566                 function runContinuation1(f, h, receiver, next) {
28567                         if(typeof f !== 'function') {
28568                                 return next.become(h);
28569                         }
28570
28571                         Promise.enterContext(h);
28572                         tryCatchReject(f, h.value, receiver, next);
28573                         Promise.exitContext();
28574                 }
28575
28576                 function runContinuation3(f, x, h, receiver, next) {
28577                         if(typeof f !== 'function') {
28578                                 return next.become(h);
28579                         }
28580
28581                         Promise.enterContext(h);
28582                         tryCatchReject3(f, x, h.value, receiver, next);
28583                         Promise.exitContext();
28584                 }
28585
28586                 /**
28587                  * @deprecated
28588                  */
28589                 function runNotify(f, x, h, receiver, next) {
28590                         if(typeof f !== 'function') {
28591                                 return next.notify(x);
28592                         }
28593
28594                         Promise.enterContext(h);
28595                         tryCatchReturn(f, x, receiver, next);
28596                         Promise.exitContext();
28597                 }
28598
28599                 function tryCatch2(f, a, b) {
28600                         try {
28601                                 return f(a, b);
28602                         } catch(e) {
28603                                 return reject(e);
28604                         }
28605                 }
28606
28607                 /**
28608                  * Return f.call(thisArg, x), or if it throws return a rejected promise for
28609                  * the thrown exception
28610                  */
28611                 function tryCatchReject(f, x, thisArg, next) {
28612                         try {
28613                                 next.become(getHandler(f.call(thisArg, x)));
28614                         } catch(e) {
28615                                 next.become(new Rejected(e));
28616                         }
28617                 }
28618
28619                 /**
28620                  * Same as above, but includes the extra argument parameter.
28621                  */
28622                 function tryCatchReject3(f, x, y, thisArg, next) {
28623                         try {
28624                                 f.call(thisArg, x, y, next);
28625                         } catch(e) {
28626                                 next.become(new Rejected(e));
28627                         }
28628                 }
28629
28630                 /**
28631                  * @deprecated
28632                  * Return f.call(thisArg, x), or if it throws, *return* the exception
28633                  */
28634                 function tryCatchReturn(f, x, thisArg, next) {
28635                         try {
28636                                 next.notify(f.call(thisArg, x));
28637                         } catch(e) {
28638                                 next.notify(e);
28639                         }
28640                 }
28641
28642                 function inherit(Parent, Child) {
28643                         Child.prototype = objectCreate(Parent.prototype);
28644                         Child.prototype.constructor = Child;
28645                 }
28646
28647                 function snd(x, y) {
28648                         return y;
28649                 }
28650
28651                 function noop() {}
28652
28653                 function hasCustomEvent() {
28654                         if(typeof CustomEvent === 'function') {
28655                                 try {
28656                                         var ev = new CustomEvent('unhandledRejection');
28657                                         return ev instanceof CustomEvent;
28658                                 } catch (ignoredException) {}
28659                         }
28660                         return false;
28661                 }
28662
28663                 function hasInternetExplorerCustomEvent() {
28664                         if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
28665                                 try {
28666                                         // Try to create one event to make sure it's supported
28667                                         var ev = document.createEvent('CustomEvent');
28668                                         ev.initCustomEvent('eventType', false, true, {});
28669                                         return true;
28670                                 } catch (ignoredException) {}
28671                         }
28672                         return false;
28673                 }
28674
28675                 function initEmitRejection() {
28676                         /*global process, self, CustomEvent*/
28677                         if(typeof process !== 'undefined' && process !== null
28678                                 && typeof process.emit === 'function') {
28679                                 // Returning falsy here means to call the default
28680                                 // onPotentiallyUnhandledRejection API.  This is safe even in
28681                                 // browserify since process.emit always returns falsy in browserify:
28682                                 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
28683                                 return function(type, rejection) {
28684                                         return type === 'unhandledRejection'
28685                                                 ? process.emit(type, rejection.value, rejection)
28686                                                 : process.emit(type, rejection);
28687                                 };
28688                         } else if(typeof self !== 'undefined' && hasCustomEvent()) {
28689                                 return (function (self, CustomEvent) {
28690                                         return function (type, rejection) {
28691                                                 var ev = new CustomEvent(type, {
28692                                                         detail: {
28693                                                                 reason: rejection.value,
28694                                                                 key: rejection
28695                                                         },
28696                                                         bubbles: false,
28697                                                         cancelable: true
28698                                                 });
28699
28700                                                 return !self.dispatchEvent(ev);
28701                                         };
28702                                 }(self, CustomEvent));
28703                         } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
28704                                 return (function(self, document) {
28705                                         return function(type, rejection) {
28706                                                 var ev = document.createEvent('CustomEvent');
28707                                                 ev.initCustomEvent(type, false, true, {
28708                                                         reason: rejection.value,
28709                                                         key: rejection
28710                                                 });
28711
28712                                                 return !self.dispatchEvent(ev);
28713                                         };
28714                                 }(self, document));
28715                         }
28716
28717                         return noop;
28718                 }
28719
28720                 return Promise;
28721         };
28722 });
28723 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
28724
28725 }).call(this,require('_process'))
28726
28727 },{"_process":6}],287:[function(require,module,exports){
28728 /** @license MIT License (c) copyright 2010-2014 original author or authors */
28729 /** @author Brian Cavalier */
28730 /** @author John Hann */
28731
28732 (function(define) { 'use strict';
28733 define(function() {
28734
28735         return {
28736                 pending: toPendingState,
28737                 fulfilled: toFulfilledState,
28738                 rejected: toRejectedState,
28739                 inspect: inspect
28740         };
28741
28742         function toPendingState() {
28743                 return { state: 'pending' };
28744         }
28745
28746         function toRejectedState(e) {
28747                 return { state: 'rejected', reason: e };
28748         }
28749
28750         function toFulfilledState(x) {
28751                 return { state: 'fulfilled', value: x };
28752         }
28753
28754         function inspect(handler) {
28755                 var state = handler.state();
28756                 return state === 0 ? toPendingState()
28757                          : state > 0   ? toFulfilledState(handler.value)
28758                                        : toRejectedState(handler.value);
28759         }
28760
28761 });
28762 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
28763
28764 },{}],288:[function(require,module,exports){
28765 /** @license MIT License (c) copyright 2010-2014 original author or authors */
28766
28767 /**
28768  * Promises/A+ and when() implementation
28769  * when is part of the cujoJS family of libraries (http://cujojs.com/)
28770  * @author Brian Cavalier
28771  * @author John Hann
28772  */
28773 (function(define) { 'use strict';
28774 define(function (require) {
28775
28776         var timed = require('./lib/decorators/timed');
28777         var array = require('./lib/decorators/array');
28778         var flow = require('./lib/decorators/flow');
28779         var fold = require('./lib/decorators/fold');
28780         var inspect = require('./lib/decorators/inspect');
28781         var generate = require('./lib/decorators/iterate');
28782         var progress = require('./lib/decorators/progress');
28783         var withThis = require('./lib/decorators/with');
28784         var unhandledRejection = require('./lib/decorators/unhandledRejection');
28785         var TimeoutError = require('./lib/TimeoutError');
28786
28787         var Promise = [array, flow, fold, generate, progress,
28788                 inspect, withThis, timed, unhandledRejection]
28789                 .reduce(function(Promise, feature) {
28790                         return feature(Promise);
28791                 }, require('./lib/Promise'));
28792
28793         var apply = require('./lib/apply')(Promise);
28794
28795         // Public API
28796
28797         when.promise     = promise;              // Create a pending promise
28798         when.resolve     = Promise.resolve;      // Create a resolved promise
28799         when.reject      = Promise.reject;       // Create a rejected promise
28800
28801         when.lift        = lift;                 // lift a function to return promises
28802         when['try']      = attempt;              // call a function and return a promise
28803         when.attempt     = attempt;              // alias for when.try
28804
28805         when.iterate     = Promise.iterate;      // DEPRECATED (use cujojs/most streams) Generate a stream of promises
28806         when.unfold      = Promise.unfold;       // DEPRECATED (use cujojs/most streams) Generate a stream of promises
28807
28808         when.join        = join;                 // Join 2 or more promises
28809
28810         when.all         = all;                  // Resolve a list of promises
28811         when.settle      = settle;               // Settle a list of promises
28812
28813         when.any         = lift(Promise.any);    // One-winner race
28814         when.some        = lift(Promise.some);   // Multi-winner race
28815         when.race        = lift(Promise.race);   // First-to-settle race
28816
28817         when.map         = map;                  // Array.map() for promises
28818         when.filter      = filter;               // Array.filter() for promises
28819         when.reduce      = lift(Promise.reduce);       // Array.reduce() for promises
28820         when.reduceRight = lift(Promise.reduceRight);  // Array.reduceRight() for promises
28821
28822         when.isPromiseLike = isPromiseLike;      // Is something promise-like, aka thenable
28823
28824         when.Promise     = Promise;              // Promise constructor
28825         when.defer       = defer;                // Create a {promise, resolve, reject} tuple
28826
28827         // Error types
28828
28829         when.TimeoutError = TimeoutError;
28830
28831         /**
28832          * Get a trusted promise for x, or by transforming x with onFulfilled
28833          *
28834          * @param {*} x
28835          * @param {function?} onFulfilled callback to be called when x is
28836          *   successfully fulfilled.  If promiseOrValue is an immediate value, callback
28837          *   will be invoked immediately.
28838          * @param {function?} onRejected callback to be called when x is
28839          *   rejected.
28840          * @param {function?} onProgress callback to be called when progress updates
28841          *   are issued for x. @deprecated
28842          * @returns {Promise} a new promise that will fulfill with the return
28843          *   value of callback or errback or the completion value of promiseOrValue if
28844          *   callback and/or errback is not supplied.
28845          */
28846         function when(x, onFulfilled, onRejected, onProgress) {
28847                 var p = Promise.resolve(x);
28848                 if (arguments.length < 2) {
28849                         return p;
28850                 }
28851
28852                 return p.then(onFulfilled, onRejected, onProgress);
28853         }
28854
28855         /**
28856          * Creates a new promise whose fate is determined by resolver.
28857          * @param {function} resolver function(resolve, reject, notify)
28858          * @returns {Promise} promise whose fate is determine by resolver
28859          */
28860         function promise(resolver) {
28861                 return new Promise(resolver);
28862         }
28863
28864         /**
28865          * Lift the supplied function, creating a version of f that returns
28866          * promises, and accepts promises as arguments.
28867          * @param {function} f
28868          * @returns {Function} version of f that returns promises
28869          */
28870         function lift(f) {
28871                 return function() {
28872                         for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
28873                                 a[i] = arguments[i];
28874                         }
28875                         return apply(f, this, a);
28876                 };
28877         }
28878
28879         /**
28880          * Call f in a future turn, with the supplied args, and return a promise
28881          * for the result.
28882          * @param {function} f
28883          * @returns {Promise}
28884          */
28885         function attempt(f /*, args... */) {
28886                 /*jshint validthis:true */
28887                 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
28888                         a[i] = arguments[i+1];
28889                 }
28890                 return apply(f, this, a);
28891         }
28892
28893         /**
28894          * Creates a {promise, resolver} pair, either or both of which
28895          * may be given out safely to consumers.
28896          * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
28897          */
28898         function defer() {
28899                 return new Deferred();
28900         }
28901
28902         function Deferred() {
28903                 var p = Promise._defer();
28904
28905                 function resolve(x) { p._handler.resolve(x); }
28906                 function reject(x) { p._handler.reject(x); }
28907                 function notify(x) { p._handler.notify(x); }
28908
28909                 this.promise = p;
28910                 this.resolve = resolve;
28911                 this.reject = reject;
28912                 this.notify = notify;
28913                 this.resolver = { resolve: resolve, reject: reject, notify: notify };
28914         }
28915
28916         /**
28917          * Determines if x is promise-like, i.e. a thenable object
28918          * NOTE: Will return true for *any thenable object*, and isn't truly
28919          * safe, since it may attempt to access the `then` property of x (i.e.
28920          *  clever/malicious getters may do weird things)
28921          * @param {*} x anything
28922          * @returns {boolean} true if x is promise-like
28923          */
28924         function isPromiseLike(x) {
28925                 return x && typeof x.then === 'function';
28926         }
28927
28928         /**
28929          * Return a promise that will resolve only once all the supplied arguments
28930          * have resolved. The resolution value of the returned promise will be an array
28931          * containing the resolution values of each of the arguments.
28932          * @param {...*} arguments may be a mix of promises and values
28933          * @returns {Promise}
28934          */
28935         function join(/* ...promises */) {
28936                 return Promise.all(arguments);
28937         }
28938
28939         /**
28940          * Return a promise that will fulfill once all input promises have
28941          * fulfilled, or reject when any one input promise rejects.
28942          * @param {array|Promise} promises array (or promise for an array) of promises
28943          * @returns {Promise}
28944          */
28945         function all(promises) {
28946                 return when(promises, Promise.all);
28947         }
28948
28949         /**
28950          * Return a promise that will always fulfill with an array containing
28951          * the outcome states of all input promises.  The returned promise
28952          * will only reject if `promises` itself is a rejected promise.
28953          * @param {array|Promise} promises array (or promise for an array) of promises
28954          * @returns {Promise} promise for array of settled state descriptors
28955          */
28956         function settle(promises) {
28957                 return when(promises, Promise.settle);
28958         }
28959
28960         /**
28961          * Promise-aware array map function, similar to `Array.prototype.map()`,
28962          * but input array may contain promises or values.
28963          * @param {Array|Promise} promises array of anything, may contain promises and values
28964          * @param {function(x:*, index:Number):*} mapFunc map function which may
28965          *  return a promise or value
28966          * @returns {Promise} promise that will fulfill with an array of mapped values
28967          *  or reject if any input promise rejects.
28968          */
28969         function map(promises, mapFunc) {
28970                 return when(promises, function(promises) {
28971                         return Promise.map(promises, mapFunc);
28972                 });
28973         }
28974
28975         /**
28976          * Filter the provided array of promises using the provided predicate.  Input may
28977          * contain promises and values
28978          * @param {Array|Promise} promises array of promises and values
28979          * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
28980          *  Must return truthy (or promise for truthy) for items to retain.
28981          * @returns {Promise} promise that will fulfill with an array containing all items
28982          *  for which predicate returned truthy.
28983          */
28984         function filter(promises, predicate) {
28985                 return when(promises, function(promises) {
28986                         return Promise.filter(promises, predicate);
28987                 });
28988         }
28989
28990         return when;
28991 });
28992 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
28993
28994 },{"./lib/Promise":271,"./lib/TimeoutError":273,"./lib/apply":274,"./lib/decorators/array":275,"./lib/decorators/flow":276,"./lib/decorators/fold":277,"./lib/decorators/inspect":278,"./lib/decorators/iterate":279,"./lib/decorators/progress":280,"./lib/decorators/timed":281,"./lib/decorators/unhandledRejection":282,"./lib/decorators/with":283}],289:[function(require,module,exports){
28995 var nativeIsArray = Array.isArray
28996 var toString = Object.prototype.toString
28997
28998 module.exports = nativeIsArray || isArray
28999
29000 function isArray(obj) {
29001     return toString.call(obj) === "[object Array]"
29002 }
29003
29004 },{}],290:[function(require,module,exports){
29005 "use strict";
29006 Object.defineProperty(exports, "__esModule", { value: true });
29007 var APIv3_1 = require("./api/APIv3");
29008 exports.APIv3 = APIv3_1.APIv3;
29009 var ModelCreator_1 = require("./api/ModelCreator");
29010 exports.ModelCreator = ModelCreator_1.ModelCreator;
29011
29012 },{"./api/APIv3":303,"./api/ModelCreator":304}],291:[function(require,module,exports){
29013 "use strict";
29014 function __export(m) {
29015     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
29016 }
29017 Object.defineProperty(exports, "__esModule", { value: true });
29018 var Component_1 = require("./component/Component");
29019 exports.Component = Component_1.Component;
29020 var ComponentService_1 = require("./component/ComponentService");
29021 exports.ComponentService = ComponentService_1.ComponentService;
29022 var HandlerBase_1 = require("./component/utils/HandlerBase");
29023 exports.HandlerBase = HandlerBase_1.HandlerBase;
29024 var MeshFactory_1 = require("./component/utils/MeshFactory");
29025 exports.MeshFactory = MeshFactory_1.MeshFactory;
29026 var MeshScene_1 = require("./component/utils/MeshScene");
29027 exports.MeshScene = MeshScene_1.MeshScene;
29028 var MouseOperator_1 = require("./component/utils/MouseOperator");
29029 exports.MouseOperator = MouseOperator_1.MouseOperator;
29030 var ComponentSize_1 = require("./component/utils/ComponentSize");
29031 exports.ComponentSize = ComponentSize_1.ComponentSize;
29032 var AttributionComponent_1 = require("./component/AttributionComponent");
29033 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
29034 var BackgroundComponent_1 = require("./component/BackgroundComponent");
29035 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
29036 var BearingComponent_1 = require("./component/BearingComponent");
29037 exports.BearingComponent = BearingComponent_1.BearingComponent;
29038 var CacheComponent_1 = require("./component/CacheComponent");
29039 exports.CacheComponent = CacheComponent_1.CacheComponent;
29040 var CoverComponent_1 = require("./component/CoverComponent");
29041 exports.CoverComponent = CoverComponent_1.CoverComponent;
29042 var DebugComponent_1 = require("./component/DebugComponent");
29043 exports.DebugComponent = DebugComponent_1.DebugComponent;
29044 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
29045 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
29046 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
29047 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
29048 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
29049 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
29050 var ImageComponent_1 = require("./component/ImageComponent");
29051 exports.ImageComponent = ImageComponent_1.ImageComponent;
29052 var KeyboardComponent_1 = require("./component/keyboard/KeyboardComponent");
29053 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
29054 var KeyPlayHandler_1 = require("./component/keyboard/KeyPlayHandler");
29055 exports.KeyPlayHandler = KeyPlayHandler_1.KeyPlayHandler;
29056 var KeyZoomHandler_1 = require("./component/keyboard/KeyZoomHandler");
29057 exports.KeyZoomHandler = KeyZoomHandler_1.KeyZoomHandler;
29058 var KeySequenceNavigationHandler_1 = require("./component/keyboard/KeySequenceNavigationHandler");
29059 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler_1.KeySequenceNavigationHandler;
29060 var KeySpatialNavigationHandler_1 = require("./component/keyboard/KeySpatialNavigationHandler");
29061 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler_1.KeySpatialNavigationHandler;
29062 var LoadingComponent_1 = require("./component/LoadingComponent");
29063 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
29064 var Marker_1 = require("./component/marker/marker/Marker");
29065 exports.Marker = Marker_1.Marker;
29066 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
29067 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
29068 var MarkerScene_1 = require("./component/marker/MarkerScene");
29069 exports.MarkerScene = MarkerScene_1.MarkerScene;
29070 var MarkerSet_1 = require("./component/marker/MarkerSet");
29071 exports.MarkerSet = MarkerSet_1.MarkerSet;
29072 var MouseComponent_1 = require("./component/mouse/MouseComponent");
29073 exports.MouseComponent = MouseComponent_1.MouseComponent;
29074 var BounceHandler_1 = require("./component/mouse/BounceHandler");
29075 exports.BounceHandler = BounceHandler_1.BounceHandler;
29076 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
29077 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
29078 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
29079 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
29080 var EarthControlHandler_1 = require("./component/mouse/EarthControlHandler");
29081 exports.EarthControlHandler = EarthControlHandler_1.EarthControlHandler;
29082 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
29083 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
29084 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
29085 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
29086 var ImageBoundary = require("./component/mouse/ImageBoundary");
29087 exports.ImageBoundary = ImageBoundary;
29088 var Popup_1 = require("./component/popup/popup/Popup");
29089 exports.Popup = Popup_1.Popup;
29090 var PopupComponent_1 = require("./component/popup/PopupComponent");
29091 exports.PopupComponent = PopupComponent_1.PopupComponent;
29092 var NavigationComponent_1 = require("./component/NavigationComponent");
29093 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
29094 var RouteComponent_1 = require("./component/RouteComponent");
29095 exports.RouteComponent = RouteComponent_1.RouteComponent;
29096 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
29097 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
29098 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
29099 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
29100 var SequenceMode_1 = require("./component/sequence/SequenceMode");
29101 exports.SequenceMode = SequenceMode_1.SequenceMode;
29102 var SpatialDataCache_1 = require("./component/spatialdata/SpatialDataCache");
29103 exports.SpatialDataCache = SpatialDataCache_1.SpatialDataCache;
29104 var SpatialDataComponent_1 = require("./component/spatialdata/SpatialDataComponent");
29105 exports.SpatialDataComponent = SpatialDataComponent_1.SpatialDataComponent;
29106 var SpatialDataScene_1 = require("./component/spatialdata/SpatialDataScene");
29107 exports.SpatialDataScene = SpatialDataScene_1.SpatialDataScene;
29108 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
29109 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
29110 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
29111 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
29112 var Shaders_1 = require("./component/shaders/Shaders");
29113 exports.Shaders = Shaders_1.Shaders;
29114 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
29115 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
29116 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
29117 exports.CircleMarker = CircleMarker_1.CircleMarker;
29118 var SliderComponent_1 = require("./component/slider/SliderComponent");
29119 exports.SliderComponent = SliderComponent_1.SliderComponent;
29120 var SliderDOMRenderer_1 = require("./component/slider/SliderDOMRenderer");
29121 exports.SliderDOMRenderer = SliderDOMRenderer_1.SliderDOMRenderer;
29122 var SliderGLRenderer_1 = require("./component/slider/SliderGLRenderer");
29123 exports.SliderGLRenderer = SliderGLRenderer_1.SliderGLRenderer;
29124 var StatsComponent_1 = require("./component/StatsComponent");
29125 exports.StatsComponent = StatsComponent_1.StatsComponent;
29126 var TagHandlerBase_1 = require("./component/tag/handlers/TagHandlerBase");
29127 exports.TagHandlerBase = TagHandlerBase_1.TagHandlerBase;
29128 var CreateHandlerBase_1 = require("./component/tag/handlers/CreateHandlerBase");
29129 exports.CreateHandlerBase = CreateHandlerBase_1.CreateHandlerBase;
29130 var CreatePointHandler_1 = require("./component/tag/handlers/CreatePointHandler");
29131 exports.CreatePointHandler = CreatePointHandler_1.CreatePointHandler;
29132 var CreateVertexHandler_1 = require("./component/tag/handlers/CreateVertexHandler");
29133 exports.CreateVertexHandler = CreateVertexHandler_1.CreateVertexHandler;
29134 var CreatePointsHandler_1 = require("./component/tag/handlers/CreatePointsHandler");
29135 exports.CreatePointsHandler = CreatePointsHandler_1.CreatePointsHandler;
29136 var CreatePolygonHandler_1 = require("./component/tag/handlers/CreatePolygonHandler");
29137 exports.CreatePolygonHandler = CreatePolygonHandler_1.CreatePolygonHandler;
29138 var CreateRectHandler_1 = require("./component/tag/handlers/CreateRectHandler");
29139 exports.CreateRectHandler = CreateRectHandler_1.CreateRectHandler;
29140 var CreateRectDragHandler_1 = require("./component/tag/handlers/CreateRectDragHandler");
29141 exports.CreateRectDragHandler = CreateRectDragHandler_1.CreateRectDragHandler;
29142 var EditVertexHandler_1 = require("./component/tag/handlers/EditVertexHandler");
29143 exports.EditVertexHandler = EditVertexHandler_1.EditVertexHandler;
29144 var Tag_1 = require("./component/tag/tag/Tag");
29145 exports.Tag = Tag_1.Tag;
29146 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
29147 exports.OutlineTag = OutlineTag_1.OutlineTag;
29148 var ExtremePointTag_1 = require("./component/tag/tag/ExtremePointTag");
29149 exports.ExtremePointTag = ExtremePointTag_1.ExtremePointTag;
29150 var RenderTag_1 = require("./component/tag/tag/RenderTag");
29151 exports.RenderTag = RenderTag_1.RenderTag;
29152 var OutlineRenderTagBase_1 = require("./component/tag/tag/OutlineRenderTagBase");
29153 exports.OutlineRenderTagBase = OutlineRenderTagBase_1.OutlineRenderTagBase;
29154 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
29155 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
29156 var ExtremePointRenderTag_1 = require("./component/tag/tag/ExtremePointRenderTag");
29157 exports.ExtremePointRenderTag = ExtremePointRenderTag_1.ExtremePointRenderTag;
29158 var SpotTag_1 = require("./component/tag/tag/SpotTag");
29159 exports.SpotTag = SpotTag_1.SpotTag;
29160 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
29161 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
29162 var TagDomain_1 = require("./component/tag/tag/TagDomain");
29163 exports.TagDomain = TagDomain_1.TagDomain;
29164 var TagComponent_1 = require("./component/tag/TagComponent");
29165 exports.TagComponent = TagComponent_1.TagComponent;
29166 var TagCreator_1 = require("./component/tag/TagCreator");
29167 exports.TagCreator = TagCreator_1.TagCreator;
29168 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
29169 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
29170 var TagMode_1 = require("./component/tag/TagMode");
29171 exports.TagMode = TagMode_1.TagMode;
29172 var TagOperation_1 = require("./component/tag/TagOperation");
29173 exports.TagOperation = TagOperation_1.TagOperation;
29174 var TagScene_1 = require("./component/tag/TagScene");
29175 exports.TagScene = TagScene_1.TagScene;
29176 var TagSet_1 = require("./component/tag/TagSet");
29177 exports.TagSet = TagSet_1.TagSet;
29178 var Geometry_1 = require("./component/tag/geometry/Geometry");
29179 exports.Geometry = Geometry_1.Geometry;
29180 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
29181 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
29182 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
29183 exports.RectGeometry = RectGeometry_1.RectGeometry;
29184 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
29185 exports.PointGeometry = PointGeometry_1.PointGeometry;
29186 var PointsGeometry_1 = require("./component/tag/geometry/PointsGeometry");
29187 exports.PointsGeometry = PointsGeometry_1.PointsGeometry;
29188 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
29189 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
29190 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
29191 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
29192 var ZoomComponent_1 = require("./component/zoom/ZoomComponent");
29193 exports.ZoomComponent = ZoomComponent_1.ZoomComponent;
29194 var CreateTag_1 = require("./component/tag/tag/CreateTag");
29195 exports.CreateTag = CreateTag_1.CreateTag;
29196 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
29197 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
29198 var ExtremePointCreateTag_1 = require("./component/tag/tag/ExtremePointCreateTag");
29199 exports.ExtremePointCreateTag = ExtremePointCreateTag_1.ExtremePointCreateTag;
29200 __export(require("./component/interfaces/interfaces"));
29201
29202 },{"./component/AttributionComponent":305,"./component/BackgroundComponent":306,"./component/BearingComponent":307,"./component/CacheComponent":308,"./component/Component":309,"./component/ComponentService":310,"./component/CoverComponent":311,"./component/DebugComponent":312,"./component/ImageComponent":313,"./component/LoadingComponent":314,"./component/NavigationComponent":315,"./component/RouteComponent":316,"./component/StatsComponent":317,"./component/direction/DirectionComponent":318,"./component/direction/DirectionDOMCalculator":319,"./component/direction/DirectionDOMRenderer":320,"./component/imageplane/ImagePlaneComponent":321,"./component/imageplane/ImagePlaneGLRenderer":322,"./component/interfaces/interfaces":325,"./component/keyboard/KeyPlayHandler":326,"./component/keyboard/KeySequenceNavigationHandler":327,"./component/keyboard/KeySpatialNavigationHandler":328,"./component/keyboard/KeyZoomHandler":329,"./component/keyboard/KeyboardComponent":330,"./component/marker/MarkerComponent":332,"./component/marker/MarkerScene":333,"./component/marker/MarkerSet":334,"./component/marker/marker/CircleMarker":335,"./component/marker/marker/Marker":336,"./component/marker/marker/SimpleMarker":337,"./component/mouse/BounceHandler":338,"./component/mouse/DoubleClickZoomHandler":339,"./component/mouse/DragPanHandler":340,"./component/mouse/EarthControlHandler":341,"./component/mouse/ImageBoundary":342,"./component/mouse/MouseComponent":343,"./component/mouse/ScrollZoomHandler":344,"./component/mouse/TouchZoomHandler":345,"./component/popup/PopupComponent":347,"./component/popup/popup/Popup":348,"./component/sequence/SequenceComponent":349,"./component/sequence/SequenceDOMRenderer":350,"./component/sequence/SequenceMode":351,"./component/shaders/Shaders":352,"./component/slider/SliderComponent":353,"./component/slider/SliderDOMRenderer":354,"./component/slider/SliderGLRenderer":355,"./component/spatialdata/SpatialDataCache":358,"./component/spatialdata/SpatialDataComponent":359,"./component/spatialdata/SpatialDataScene":360,"./component/tag/TagComponent":362,"./component/tag/TagCreator":363,"./component/tag/TagDOMRenderer":364,"./component/tag/TagMode":365,"./component/tag/TagOperation":366,"./component/tag/TagScene":367,"./component/tag/TagSet":368,"./component/tag/error/GeometryTagError":369,"./component/tag/geometry/Geometry":370,"./component/tag/geometry/PointGeometry":371,"./component/tag/geometry/PointsGeometry":372,"./component/tag/geometry/PolygonGeometry":373,"./component/tag/geometry/RectGeometry":374,"./component/tag/geometry/VertexGeometry":375,"./component/tag/handlers/CreateHandlerBase":376,"./component/tag/handlers/CreatePointHandler":377,"./component/tag/handlers/CreatePointsHandler":378,"./component/tag/handlers/CreatePolygonHandler":379,"./component/tag/handlers/CreateRectDragHandler":380,"./component/tag/handlers/CreateRectHandler":381,"./component/tag/handlers/CreateVertexHandler":382,"./component/tag/handlers/EditVertexHandler":383,"./component/tag/handlers/TagHandlerBase":384,"./component/tag/tag/CreateTag":385,"./component/tag/tag/ExtremePointCreateTag":386,"./component/tag/tag/ExtremePointRenderTag":387,"./component/tag/tag/ExtremePointTag":388,"./component/tag/tag/OutlineCreateTag":389,"./component/tag/tag/OutlineRenderTag":390,"./component/tag/tag/OutlineRenderTagBase":391,"./component/tag/tag/OutlineTag":392,"./component/tag/tag/RenderTag":393,"./component/tag/tag/SpotRenderTag":394,"./component/tag/tag/SpotTag":395,"./component/tag/tag/Tag":396,"./component/tag/tag/TagDomain":397,"./component/utils/ComponentSize":398,"./component/utils/HandlerBase":399,"./component/utils/MeshFactory":400,"./component/utils/MeshScene":401,"./component/utils/MouseOperator":402,"./component/zoom/ZoomComponent":403}],292:[function(require,module,exports){
29203 "use strict";
29204 Object.defineProperty(exports, "__esModule", { value: true });
29205 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
29206 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
29207 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
29208 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
29209 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
29210 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
29211 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
29212 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
29213 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
29214 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
29215
29216 },{"./graph/edge/EdgeCalculator":425,"./graph/edge/EdgeCalculatorCoefficients":426,"./graph/edge/EdgeCalculatorDirections":427,"./graph/edge/EdgeCalculatorSettings":428,"./graph/edge/EdgeDirection":429}],293:[function(require,module,exports){
29217 "use strict";
29218 Object.defineProperty(exports, "__esModule", { value: true });
29219 var AbortMapillaryError_1 = require("./error/AbortMapillaryError");
29220 exports.AbortMapillaryError = AbortMapillaryError_1.AbortMapillaryError;
29221 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
29222 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
29223 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
29224 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
29225 var MapillaryError_1 = require("./error/MapillaryError");
29226 exports.MapillaryError = MapillaryError_1.MapillaryError;
29227
29228 },{"./error/AbortMapillaryError":404,"./error/ArgumentMapillaryError":405,"./error/GraphMapillaryError":406,"./error/MapillaryError":407}],294:[function(require,module,exports){
29229 "use strict";
29230 Object.defineProperty(exports, "__esModule", { value: true });
29231 var Camera_1 = require("./geo/Camera");
29232 exports.Camera = Camera_1.Camera;
29233 var GeoCoords_1 = require("./geo/GeoCoords");
29234 exports.GeoCoords = GeoCoords_1.GeoCoords;
29235 var ViewportCoords_1 = require("./geo/ViewportCoords");
29236 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
29237 var Spatial_1 = require("./geo/Spatial");
29238 exports.Spatial = Spatial_1.Spatial;
29239 var Transform_1 = require("./geo/Transform");
29240 exports.Transform = Transform_1.Transform;
29241 var Geo = require("./geo/Geo");
29242 exports.Geo = Geo;
29243 var Lines = require("./geo/Lines");
29244 exports.Lines = Lines;
29245
29246 },{"./geo/Camera":408,"./geo/Geo":409,"./geo/GeoCoords":410,"./geo/Lines":411,"./geo/Spatial":412,"./geo/Transform":413,"./geo/ViewportCoords":414}],295:[function(require,module,exports){
29247 "use strict";
29248 Object.defineProperty(exports, "__esModule", { value: true });
29249 var FilterCreator_1 = require("./graph/FilterCreator");
29250 exports.FilterCreator = FilterCreator_1.FilterCreator;
29251 var Graph_1 = require("./graph/Graph");
29252 exports.Graph = Graph_1.Graph;
29253 var GraphCalculator_1 = require("./graph/GraphCalculator");
29254 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
29255 var GraphMode_1 = require("./graph/GraphMode");
29256 exports.GraphMode = GraphMode_1.GraphMode;
29257 var GraphService_1 = require("./graph/GraphService");
29258 exports.GraphService = GraphService_1.GraphService;
29259 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
29260 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
29261 var MeshReader_1 = require("./graph/MeshReader");
29262 exports.MeshReader = MeshReader_1.MeshReader;
29263 var Node_1 = require("./graph/Node");
29264 exports.Node = Node_1.Node;
29265 var NodeCache_1 = require("./graph/NodeCache");
29266 exports.NodeCache = NodeCache_1.NodeCache;
29267 var Sequence_1 = require("./graph/Sequence");
29268 exports.Sequence = Sequence_1.Sequence;
29269
29270 },{"./graph/FilterCreator":415,"./graph/Graph":416,"./graph/GraphCalculator":417,"./graph/GraphMode":418,"./graph/GraphService":419,"./graph/ImageLoadingService":420,"./graph/MeshReader":421,"./graph/Node":422,"./graph/NodeCache":423,"./graph/Sequence":424}],296:[function(require,module,exports){
29271 "use strict";
29272 /**
29273  * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
29274  * @name Mapillary
29275  */
29276 function __export(m) {
29277     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
29278 }
29279 Object.defineProperty(exports, "__esModule", { value: true });
29280 __export(require("./Support"));
29281 var Edge_1 = require("./Edge");
29282 exports.EdgeDirection = Edge_1.EdgeDirection;
29283 var Error_1 = require("./Error");
29284 exports.AbortMapillaryError = Error_1.AbortMapillaryError;
29285 var Render_1 = require("./Render");
29286 exports.RenderMode = Render_1.RenderMode;
29287 var State_1 = require("./State");
29288 exports.TransitionMode = State_1.TransitionMode;
29289 var Viewer_1 = require("./Viewer");
29290 exports.Alignment = Viewer_1.Alignment;
29291 exports.ImageSize = Viewer_1.ImageSize;
29292 exports.Viewer = Viewer_1.Viewer;
29293 var Component_1 = require("./Component");
29294 exports.SliderMode = Component_1.SliderMode;
29295 exports.ComponentSize = Component_1.ComponentSize;
29296 var TagComponent = require("./component/tag/Tag");
29297 exports.TagComponent = TagComponent;
29298 var MarkerComponent = require("./component/marker/Marker");
29299 exports.MarkerComponent = MarkerComponent;
29300 var PopupComponent = require("./component/popup/Popup");
29301 exports.PopupComponent = PopupComponent;
29302 var SpatialDataComponent = require("./component/spatialdata/SpatialData");
29303 exports.SpatialDataComponent = SpatialDataComponent;
29304
29305 },{"./Component":291,"./Edge":292,"./Error":293,"./Render":297,"./State":298,"./Support":299,"./Viewer":302,"./component/marker/Marker":331,"./component/popup/Popup":346,"./component/spatialdata/SpatialData":357,"./component/tag/Tag":361}],297:[function(require,module,exports){
29306 "use strict";
29307 Object.defineProperty(exports, "__esModule", { value: true });
29308 var DOMRenderer_1 = require("./render/DOMRenderer");
29309 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
29310 var GLRenderer_1 = require("./render/GLRenderer");
29311 exports.GLRenderer = GLRenderer_1.GLRenderer;
29312 var GLRenderStage_1 = require("./render/GLRenderStage");
29313 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
29314 var RenderCamera_1 = require("./render/RenderCamera");
29315 exports.RenderCamera = RenderCamera_1.RenderCamera;
29316 var RenderMode_1 = require("./render/RenderMode");
29317 exports.RenderMode = RenderMode_1.RenderMode;
29318 var RenderService_1 = require("./render/RenderService");
29319 exports.RenderService = RenderService_1.RenderService;
29320
29321 },{"./render/DOMRenderer":430,"./render/GLRenderStage":431,"./render/GLRenderer":432,"./render/RenderCamera":433,"./render/RenderMode":434,"./render/RenderService":435}],298:[function(require,module,exports){
29322 "use strict";
29323 Object.defineProperty(exports, "__esModule", { value: true });
29324 var FrameGenerator_1 = require("./state/FrameGenerator");
29325 exports.FrameGenerator = FrameGenerator_1.FrameGenerator;
29326 var RotationDelta_1 = require("./state/RotationDelta");
29327 exports.RotationDelta = RotationDelta_1.RotationDelta;
29328 var State_1 = require("./state/State");
29329 exports.State = State_1.State;
29330 var StateBase_1 = require("./state/states/StateBase");
29331 exports.StateBase = StateBase_1.StateBase;
29332 var StateContext_1 = require("./state/StateContext");
29333 exports.StateContext = StateContext_1.StateContext;
29334 var StateService_1 = require("./state/StateService");
29335 exports.StateService = StateService_1.StateService;
29336 var TransitionMode_1 = require("./state/TransitionMode");
29337 exports.TransitionMode = TransitionMode_1.TransitionMode;
29338 var EarthState_1 = require("./state/states/EarthState");
29339 exports.EarthState = EarthState_1.EarthState;
29340 var InteractiveStateBase_1 = require("./state/states/InteractiveStateBase");
29341 exports.InteractiveStateBase = InteractiveStateBase_1.InteractiveStateBase;
29342 var InteractiveWaitingState_1 = require("./state/states/InteractiveWaitingState");
29343 exports.InteractiveWaitingState = InteractiveWaitingState_1.InteractiveWaitingState;
29344 var TraversingState_1 = require("./state/states/TraversingState");
29345 exports.TraversingState = TraversingState_1.TraversingState;
29346 var WaitingState_1 = require("./state/states/WaitingState");
29347 exports.WaitingState = WaitingState_1.WaitingState;
29348
29349 },{"./state/FrameGenerator":436,"./state/RotationDelta":437,"./state/State":438,"./state/StateContext":439,"./state/StateService":440,"./state/TransitionMode":441,"./state/states/EarthState":442,"./state/states/InteractiveStateBase":443,"./state/states/InteractiveWaitingState":444,"./state/states/StateBase":445,"./state/states/TraversingState":446,"./state/states/WaitingState":447}],299:[function(require,module,exports){
29350 "use strict";
29351 Object.defineProperty(exports, "__esModule", { value: true });
29352 var support = require("./utils/Support");
29353 /**
29354  * Test whether the current browser supports the full
29355  * functionality of MapillaryJS.
29356  *
29357  * @description The full functionality includes WebGL rendering.
29358  *
29359  * @return {boolean}
29360  *
29361  * @example `var supported = Mapillary.isSupported();`
29362  */
29363 function isSupported() {
29364     return isFallbackSupported() &&
29365         support.isWebGLSupportedCached();
29366 }
29367 exports.isSupported = isSupported;
29368 /**
29369  * Test whether the current browser supports the fallback
29370  * functionality of MapillaryJS.
29371  *
29372  * @description The fallback functionality does not include WebGL
29373  * rendering, only 2D canvas rendering.
29374  *
29375  * @return {boolean}
29376  *
29377  * @example `var fallbackSupported = Mapillary.isFallbackSupported();`
29378  */
29379 function isFallbackSupported() {
29380     return support.isBrowser() &&
29381         support.isBlobSupported() &&
29382         support.isArraySupported() &&
29383         support.isFunctionSupported() &&
29384         support.isJSONSupported() &&
29385         support.isObjectSupported();
29386 }
29387 exports.isFallbackSupported = isFallbackSupported;
29388
29389 },{"./utils/Support":455}],300:[function(require,module,exports){
29390 "use strict";
29391 Object.defineProperty(exports, "__esModule", { value: true });
29392 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
29393 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
29394 var ImageTileStore_1 = require("./tiles/ImageTileStore");
29395 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
29396 var TextureProvider_1 = require("./tiles/TextureProvider");
29397 exports.TextureProvider = TextureProvider_1.TextureProvider;
29398 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
29399 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
29400
29401 },{"./tiles/ImageTileLoader":448,"./tiles/ImageTileStore":449,"./tiles/RegionOfInterestCalculator":450,"./tiles/TextureProvider":451}],301:[function(require,module,exports){
29402 "use strict";
29403 function __export(m) {
29404     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
29405 }
29406 Object.defineProperty(exports, "__esModule", { value: true });
29407 var DOM_1 = require("./utils/DOM");
29408 exports.DOM = DOM_1.DOM;
29409 var EventEmitter_1 = require("./utils/EventEmitter");
29410 exports.EventEmitter = EventEmitter_1.EventEmitter;
29411 var Settings_1 = require("./utils/Settings");
29412 exports.Settings = Settings_1.Settings;
29413 __export(require("./utils/Support"));
29414 var Urls_1 = require("./utils/Urls");
29415 exports.Urls = Urls_1.Urls;
29416
29417 },{"./utils/DOM":452,"./utils/EventEmitter":453,"./utils/Settings":454,"./utils/Support":455,"./utils/Urls":456}],302:[function(require,module,exports){
29418 "use strict";
29419 Object.defineProperty(exports, "__esModule", { value: true });
29420 var Alignment_1 = require("./viewer/Alignment");
29421 exports.Alignment = Alignment_1.Alignment;
29422 var CacheService_1 = require("./viewer/CacheService");
29423 exports.CacheService = CacheService_1.CacheService;
29424 var ComponentController_1 = require("./viewer/ComponentController");
29425 exports.ComponentController = ComponentController_1.ComponentController;
29426 var Container_1 = require("./viewer/Container");
29427 exports.Container = Container_1.Container;
29428 var Observer_1 = require("./viewer/Observer");
29429 exports.Observer = Observer_1.Observer;
29430 var ImageSize_1 = require("./viewer/ImageSize");
29431 exports.ImageSize = ImageSize_1.ImageSize;
29432 var KeyboardService_1 = require("./viewer/KeyboardService");
29433 exports.KeyboardService = KeyboardService_1.KeyboardService;
29434 var LoadingService_1 = require("./viewer/LoadingService");
29435 exports.LoadingService = LoadingService_1.LoadingService;
29436 var MouseService_1 = require("./viewer/MouseService");
29437 exports.MouseService = MouseService_1.MouseService;
29438 var Navigator_1 = require("./viewer/Navigator");
29439 exports.Navigator = Navigator_1.Navigator;
29440 var PlayService_1 = require("./viewer/PlayService");
29441 exports.PlayService = PlayService_1.PlayService;
29442 var Projection_1 = require("./viewer/Projection");
29443 exports.Projection = Projection_1.Projection;
29444 var SpriteService_1 = require("./viewer/SpriteService");
29445 exports.SpriteService = SpriteService_1.SpriteService;
29446 var TouchService_1 = require("./viewer/TouchService");
29447 exports.TouchService = TouchService_1.TouchService;
29448 var Viewer_1 = require("./viewer/Viewer");
29449 exports.Viewer = Viewer_1.Viewer;
29450
29451 },{"./viewer/Alignment":457,"./viewer/CacheService":458,"./viewer/ComponentController":459,"./viewer/Container":460,"./viewer/ImageSize":461,"./viewer/KeyboardService":462,"./viewer/LoadingService":463,"./viewer/MouseService":464,"./viewer/Navigator":465,"./viewer/Observer":466,"./viewer/PlayService":468,"./viewer/Projection":469,"./viewer/SpriteService":470,"./viewer/TouchService":471,"./viewer/Viewer":472}],303:[function(require,module,exports){
29452 "use strict";
29453 Object.defineProperty(exports, "__esModule", { value: true });
29454 var operators_1 = require("rxjs/operators");
29455 var rxjs_1 = require("rxjs");
29456 var API_1 = require("../API");
29457 /**
29458  * @class APIv3
29459  *
29460  * @classdesc Provides methods for access of API v3.
29461  */
29462 var APIv3 = /** @class */ (function () {
29463     /**
29464      * Create a new api v3 instance.
29465      *
29466      * @param {number} clientId - Client id for API requests.
29467      * @param {number} [token] - Optional bearer token for API requests of
29468      * protected resources.
29469      * @param {ModelCreator} [creator] - Optional model creator instance.
29470      */
29471     function APIv3(clientId, token, creator) {
29472         this._clientId = clientId;
29473         this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
29474         this._model = this._modelCreator.createModel(clientId, token);
29475         this._pageCount = 999;
29476         this._pathImageByKey = "imageByKey";
29477         this._pathImageCloseTo = "imageCloseTo";
29478         this._pathImagesByH = "imagesByH";
29479         this._pathImageViewAdd = "imageViewAdd";
29480         this._pathSequenceByKey = "sequenceByKey";
29481         this._pathSequenceViewAdd = "sequenceViewAdd";
29482         this._propertiesCore = [
29483             "cl",
29484             "l",
29485             "sequence_key",
29486         ];
29487         this._propertiesFill = [
29488             "captured_at",
29489             "captured_with_camera_uuid",
29490             "user",
29491             "organization_key",
29492             "private",
29493             "project",
29494         ];
29495         this._propertiesKey = [
29496             "key",
29497         ];
29498         this._propertiesSequence = [
29499             "keys",
29500         ];
29501         this._propertiesSpatial = [
29502             "atomic_scale",
29503             "cluster_key",
29504             "c_rotation",
29505             "ca",
29506             "calt",
29507             "camera_projection_type",
29508             "cca",
29509             "cfocal",
29510             "ck1",
29511             "ck2",
29512             "gpano",
29513             "height",
29514             "merge_cc",
29515             "merge_version",
29516             "orientation",
29517             "width",
29518         ];
29519         this._propertiesUser = [
29520             "username",
29521         ];
29522     }
29523     APIv3.prototype.imageByKeyFill$ = function (keys) {
29524         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
29525             this._pathImageByKey,
29526             keys,
29527             this._propertiesKey
29528                 .concat(this._propertiesFill)
29529                 .concat(this._propertiesSpatial),
29530             this._propertiesKey
29531                 .concat(this._propertiesUser)
29532         ])).pipe(operators_1.map(function (value) {
29533             if (!value) {
29534                 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
29535             }
29536             return value.json.imageByKey;
29537         })), this._pathImageByKey, keys);
29538     };
29539     APIv3.prototype.imageByKeyFull$ = function (keys) {
29540         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
29541             this._pathImageByKey,
29542             keys,
29543             this._propertiesKey
29544                 .concat(this._propertiesCore)
29545                 .concat(this._propertiesFill)
29546                 .concat(this._propertiesSpatial),
29547             this._propertiesKey
29548                 .concat(this._propertiesUser)
29549         ])).pipe(operators_1.map(function (value) {
29550             if (!value) {
29551                 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
29552             }
29553             return value.json.imageByKey;
29554         })), this._pathImageByKey, keys);
29555     };
29556     APIv3.prototype.imageCloseTo$ = function (lat, lon) {
29557         var lonLat = lon + ":" + lat;
29558         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
29559             this._pathImageCloseTo,
29560             [lonLat],
29561             this._propertiesKey
29562                 .concat(this._propertiesCore)
29563                 .concat(this._propertiesFill)
29564                 .concat(this._propertiesSpatial),
29565             this._propertiesKey
29566                 .concat(this._propertiesUser)
29567         ])).pipe(operators_1.map(function (value) {
29568             return value != null ? value.json.imageCloseTo[lonLat] : null;
29569         })), this._pathImageCloseTo, [lonLat]);
29570     };
29571     APIv3.prototype.imagesByH$ = function (hs) {
29572         var _this = this;
29573         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
29574             this._pathImagesByH,
29575             hs,
29576             { from: 0, to: this._pageCount },
29577             this._propertiesKey
29578                 .concat(this._propertiesCore)
29579         ])).pipe(operators_1.map(function (value) {
29580             if (!value) {
29581                 value = { json: { imagesByH: {} } };
29582                 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
29583                     var h = hs_1[_i];
29584                     value.json.imagesByH[h] = {};
29585                     for (var i = 0; i <= _this._pageCount; i++) {
29586                         value.json.imagesByH[h][i] = null;
29587                     }
29588                 }
29589             }
29590             return value.json.imagesByH;
29591         })), this._pathImagesByH, hs);
29592     };
29593     APIv3.prototype.imageViewAdd$ = function (keys) {
29594         return this._catchInvalidateCall$(this._wrapCallModelResponse$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
29595     };
29596     APIv3.prototype.invalidateImageByKey = function (keys) {
29597         this._invalidateGet(this._pathImageByKey, keys);
29598     };
29599     APIv3.prototype.invalidateImagesByH = function (hs) {
29600         this._invalidateGet(this._pathImagesByH, hs);
29601     };
29602     APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
29603         this._invalidateGet(this._pathSequenceByKey, sKeys);
29604     };
29605     APIv3.prototype.setToken = function (token) {
29606         this._model.invalidate([]);
29607         this._model = null;
29608         this._model = this._modelCreator.createModel(this._clientId, token);
29609     };
29610     APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
29611         return this._catchInvalidateGet$(this._wrapModelResponse$(this._model.get([
29612             this._pathSequenceByKey,
29613             sequenceKeys,
29614             this._propertiesKey
29615                 .concat(this._propertiesSequence)
29616         ])).pipe(operators_1.map(function (value) {
29617             if (!value) {
29618                 value = { json: { sequenceByKey: {} } };
29619             }
29620             for (var _i = 0, sequenceKeys_1 = sequenceKeys; _i < sequenceKeys_1.length; _i++) {
29621                 var sequenceKey = sequenceKeys_1[_i];
29622                 if (!(sequenceKey in value.json.sequenceByKey)) {
29623                     console.warn("Sequence data missing (" + sequenceKey + ")");
29624                     value.json.sequenceByKey[sequenceKey] = { key: sequenceKey, keys: [] };
29625                 }
29626             }
29627             return value.json.sequenceByKey;
29628         })), this._pathSequenceByKey, sequenceKeys);
29629     };
29630     APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
29631         return this._catchInvalidateCall$(this._wrapCallModelResponse$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
29632     };
29633     Object.defineProperty(APIv3.prototype, "clientId", {
29634         get: function () {
29635             return this._clientId;
29636         },
29637         enumerable: true,
29638         configurable: true
29639     });
29640     APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
29641         var _this = this;
29642         return observable.pipe(operators_1.catchError(function (error) {
29643             _this._invalidateGet(path, paths);
29644             throw error;
29645         }));
29646     };
29647     APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
29648         var _this = this;
29649         return observable.pipe(operators_1.catchError(function (error) {
29650             _this._invalidateCall(path, paths);
29651             throw error;
29652         }));
29653     };
29654     APIv3.prototype._invalidateGet = function (path, paths) {
29655         this._model.invalidate([path, paths]);
29656     };
29657     APIv3.prototype._invalidateCall = function (path, paths) {
29658         this._model.invalidate([path], [paths]);
29659     };
29660     APIv3.prototype._wrapModelResponse$ = function (modelResponse) {
29661         return rxjs_1.Observable
29662             .create(function (subscriber) {
29663             modelResponse
29664                 .then(function (value) {
29665                 subscriber.next(value);
29666                 subscriber.complete();
29667             }, function (error) {
29668                 subscriber.error(error);
29669             });
29670         });
29671     };
29672     APIv3.prototype._wrapCallModelResponse$ = function (modelResponse) {
29673         return this._wrapModelResponse$(modelResponse).pipe(operators_1.map(function (value) {
29674             return;
29675         }));
29676     };
29677     return APIv3;
29678 }());
29679 exports.APIv3 = APIv3;
29680 exports.default = APIv3;
29681
29682 },{"../API":290,"rxjs":43,"rxjs/operators":241}],304:[function(require,module,exports){
29683 "use strict";
29684 Object.defineProperty(exports, "__esModule", { value: true });
29685 var falcor = require("falcor");
29686 var falcor_http_datasource_1 = require("falcor-http-datasource");
29687 var Utils_1 = require("../Utils");
29688 /**
29689  * @class ModelCreator
29690  *
29691  * @classdesc Creates API models.
29692  */
29693 var ModelCreator = /** @class */ (function () {
29694     function ModelCreator() {
29695     }
29696     /**
29697      * Creates a Falcor model.
29698      *
29699      * @description Max cache size will be set to 16 MB. Authorization
29700      * header will be added if bearer token is supplied.
29701      *
29702      * @param {number} clientId - Client id for API requests.
29703      * @param {number} [token] - Optional bearer token for API requests of
29704      * protected resources.
29705      * @returns {falcor.Model} Falcor model for HTTP requests.
29706      */
29707     ModelCreator.prototype.createModel = function (clientId, token) {
29708         var configuration = {
29709             crossDomain: true,
29710             withCredentials: false,
29711         };
29712         if (token != null) {
29713             configuration.headers = { "Authorization": "Bearer " + token };
29714         }
29715         return new falcor.Model({
29716             maxSize: 16 * 1024 * 1024,
29717             source: new falcor_http_datasource_1.default(Utils_1.Urls.falcorModel(clientId), configuration),
29718         });
29719     };
29720     return ModelCreator;
29721 }());
29722 exports.ModelCreator = ModelCreator;
29723 exports.default = ModelCreator;
29724
29725 },{"../Utils":301,"falcor":15,"falcor-http-datasource":10}],305:[function(require,module,exports){
29726 "use strict";
29727 var __extends = (this && this.__extends) || (function () {
29728     var extendStatics = function (d, b) {
29729         extendStatics = Object.setPrototypeOf ||
29730             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29731             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29732         return extendStatics(d, b);
29733     }
29734     return function (d, b) {
29735         extendStatics(d, b);
29736         function __() { this.constructor = d; }
29737         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29738     };
29739 })();
29740 Object.defineProperty(exports, "__esModule", { value: true });
29741 var rxjs_1 = require("rxjs");
29742 var operators_1 = require("rxjs/operators");
29743 var vd = require("virtual-dom");
29744 var Component_1 = require("../Component");
29745 var Utils_1 = require("../Utils");
29746 var AttributionComponent = /** @class */ (function (_super) {
29747     __extends(AttributionComponent, _super);
29748     function AttributionComponent(name, container, navigator) {
29749         return _super.call(this, name, container, navigator) || this;
29750     }
29751     AttributionComponent.prototype._activate = function () {
29752         var _this = this;
29753         this._disposable = rxjs_1.combineLatest(this._navigator.stateService.currentNode$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
29754             var node = _a[0], size = _a[1];
29755             return {
29756                 name: _this._name,
29757                 vnode: _this._getAttributionNode(node.username, node.key, node.capturedAt, size.width),
29758             };
29759         }))
29760             .subscribe(this._container.domRenderer.render$);
29761     };
29762     AttributionComponent.prototype._deactivate = function () {
29763         this._disposable.unsubscribe();
29764     };
29765     AttributionComponent.prototype._getDefaultConfiguration = function () {
29766         return {};
29767     };
29768     AttributionComponent.prototype._getAttributionNode = function (username, key, capturedAt, width) {
29769         var compact = width <= 640;
29770         var mapillaryIcon = vd.h("div.AttributionMapillaryLogo", []);
29771         var mapillaryLink = vd.h("a.AttributionIconContainer", { href: Utils_1.Urls.explore, target: "_blank" }, [mapillaryIcon]);
29772         var imageBy = compact ? "" + username : "image by " + username;
29773         var imageByContent = vd.h("div.AttributionUsername", { textContent: imageBy }, []);
29774         var date = new Date(capturedAt).toDateString().split(" ");
29775         var formatted = (date.length > 3 ?
29776             compact ?
29777                 [date[3]] :
29778                 [date[1], date[2] + ",", date[3]] :
29779             date).join(" ");
29780         var dateContent = vd.h("div.AttributionDate", { textContent: formatted }, []);
29781         var imageLink = vd.h("a.AttributionImageContainer", { href: Utils_1.Urls.exporeImage(key), target: "_blank" }, [imageByContent, dateContent]);
29782         var compactClass = compact ? ".AttributionCompact" : "";
29783         return vd.h("div.AttributionContainer" + compactClass, {}, [mapillaryLink, imageLink]);
29784     };
29785     AttributionComponent.componentName = "attribution";
29786     return AttributionComponent;
29787 }(Component_1.Component));
29788 exports.AttributionComponent = AttributionComponent;
29789 Component_1.ComponentService.register(AttributionComponent);
29790 exports.default = AttributionComponent;
29791
29792 },{"../Component":291,"../Utils":301,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],306:[function(require,module,exports){
29793 "use strict";
29794 var __extends = (this && this.__extends) || (function () {
29795     var extendStatics = function (d, b) {
29796         extendStatics = Object.setPrototypeOf ||
29797             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29798             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29799         return extendStatics(d, b);
29800     }
29801     return function (d, b) {
29802         extendStatics(d, b);
29803         function __() { this.constructor = d; }
29804         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29805     };
29806 })();
29807 Object.defineProperty(exports, "__esModule", { value: true });
29808 var vd = require("virtual-dom");
29809 var Component_1 = require("../Component");
29810 var BackgroundComponent = /** @class */ (function (_super) {
29811     __extends(BackgroundComponent, _super);
29812     function BackgroundComponent(name, container, navigator) {
29813         return _super.call(this, name, container, navigator) || this;
29814     }
29815     BackgroundComponent.prototype._activate = function () {
29816         this._container.domRenderer.render$
29817             .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given image.") });
29818     };
29819     BackgroundComponent.prototype._deactivate = function () {
29820         return;
29821     };
29822     BackgroundComponent.prototype._getDefaultConfiguration = function () {
29823         return {};
29824     };
29825     BackgroundComponent.prototype._getBackgroundNode = function (notice) {
29826         // todo: add condition for when to display the DOM node
29827         return vd.h("div.BackgroundWrapper", {}, [
29828             vd.h("p", { textContent: notice }, []),
29829         ]);
29830     };
29831     BackgroundComponent.componentName = "background";
29832     return BackgroundComponent;
29833 }(Component_1.Component));
29834 exports.BackgroundComponent = BackgroundComponent;
29835 Component_1.ComponentService.register(BackgroundComponent);
29836 exports.default = BackgroundComponent;
29837
29838 },{"../Component":291,"virtual-dom":247}],307:[function(require,module,exports){
29839 "use strict";
29840 var __extends = (this && this.__extends) || (function () {
29841     var extendStatics = function (d, b) {
29842         extendStatics = Object.setPrototypeOf ||
29843             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29844             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29845         return extendStatics(d, b);
29846     }
29847     return function (d, b) {
29848         extendStatics(d, b);
29849         function __() { this.constructor = d; }
29850         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29851     };
29852 })();
29853 Object.defineProperty(exports, "__esModule", { value: true });
29854 var operators_1 = require("rxjs/operators");
29855 var vd = require("virtual-dom");
29856 var UnitBezier = require("@mapbox/unitbezier");
29857 var rxjs_1 = require("rxjs");
29858 var Component_1 = require("../Component");
29859 var Geo_1 = require("../Geo");
29860 var ViewportCoords_1 = require("../geo/ViewportCoords");
29861 var ComponentSize_1 = require("./utils/ComponentSize");
29862 /**
29863  * @class BearingComponent
29864  *
29865  * @classdesc Component for indicating bearing and field of view.
29866  *
29867  * @example
29868  * ```
29869  * var viewer = new Mapillary.Viewer(
29870  *     "<element-id>",
29871  *     "<client-id>",
29872  *     "<my key>");
29873  *
29874  * var bearingComponent = viewer.getComponent("bearing");
29875  * bearingComponent.configure({ size: Mapillary.ComponentSize.Small });
29876  * ```
29877  */
29878 var BearingComponent = /** @class */ (function (_super) {
29879     __extends(BearingComponent, _super);
29880     function BearingComponent(name, container, navigator) {
29881         var _this = _super.call(this, name, container, navigator) || this;
29882         _this._spatial = new Geo_1.Spatial();
29883         _this._viewportCoords = new ViewportCoords_1.default();
29884         _this._svgNamespace = "http://www.w3.org/2000/svg";
29885         _this._distinctThreshold = Math.PI / 360;
29886         _this._animationSpeed = 0.075;
29887         _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
29888         return _this;
29889     }
29890     BearingComponent.prototype._activate = function () {
29891         var _this = this;
29892         var cameraBearingFov$ = this._container.renderService.renderCamera$.pipe(operators_1.map(function (rc) {
29893             var vFov = _this._spatial.degToRad(rc.perspective.fov);
29894             var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
29895                 Math.PI :
29896                 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
29897             return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
29898         }), operators_1.distinctUntilChanged(function (a1, a2) {
29899             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
29900                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
29901         }));
29902         var nodeFov$ = rxjs_1.combineLatest(this._navigator.stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
29903             return frame.state.currentNode.key;
29904         })), this._navigator.panService.panNodes$).pipe(operators_1.map(function (_a) {
29905             var frame = _a[0], panNodes = _a[1];
29906             var node = frame.state.currentNode;
29907             var transform = frame.state.currentTransform;
29908             if (node.pano) {
29909                 var panoHFov = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
29910                 return [panoHFov / 2, panoHFov / 2];
29911             }
29912             var currentProjectedPoints = _this._computeProjectedPoints(transform);
29913             var hFov = _this._spatial.degToRad(_this._computeHorizontalFov(currentProjectedPoints));
29914             var hFovLeft = hFov / 2;
29915             var hFovRight = hFov / 2;
29916             for (var _i = 0, panNodes_1 = panNodes; _i < panNodes_1.length; _i++) {
29917                 var _b = panNodes_1[_i], n = _b[0], f = _b[2];
29918                 var diff = _this._spatial.wrap(n.ca - node.ca, -180, 180);
29919                 if (diff < 0) {
29920                     hFovLeft = _this._spatial.degToRad(Math.abs(diff)) + f / 2;
29921                 }
29922                 else {
29923                     hFovRight = _this._spatial.degToRad(Math.abs(diff)) + f / 2;
29924                 }
29925             }
29926             return [hFovLeft, hFovRight];
29927         }), operators_1.distinctUntilChanged(function (_a, _b) {
29928             var hFovLeft1 = _a[0], hFovRight1 = _a[1];
29929             var hFovLeft2 = _b[0], hFovRight2 = _b[1];
29930             return Math.abs(hFovLeft2 - hFovLeft1) < _this._distinctThreshold &&
29931                 Math.abs(hFovRight2 - hFovRight1) < _this._distinctThreshold;
29932         }));
29933         var offset$ = rxjs_1.combineLatest(this._navigator.stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
29934             return frame.state.currentNode.key;
29935         })), this._container.renderService.bearing$).pipe(operators_1.map(function (_a) {
29936             var frame = _a[0], bearing = _a[1];
29937             var offset = _this._spatial.degToRad(frame.state.currentNode.ca - bearing);
29938             return offset;
29939         }));
29940         var nodeFovOperation$ = new rxjs_1.Subject();
29941         var smoothNodeFov$ = nodeFovOperation$.pipe(operators_1.scan(function (state, operation) {
29942             return operation(state);
29943         }, { alpha: 0, curr: [0, 0, 0], prev: [0, 0, 0] }), operators_1.map(function (state) {
29944             var alpha = _this._unitBezier.solve(state.alpha);
29945             var curr = state.curr;
29946             var prev = state.prev;
29947             return [
29948                 _this._interpolate(prev[0], curr[0], alpha),
29949                 _this._interpolate(prev[1], curr[1], alpha),
29950             ];
29951         }));
29952         this._fovSubscription = nodeFov$.pipe(operators_1.map(function (nbf) {
29953             return function (state) {
29954                 var a = _this._unitBezier.solve(state.alpha);
29955                 var c = state.curr;
29956                 var p = state.prev;
29957                 var prev = [
29958                     _this._interpolate(p[0], c[0], a),
29959                     _this._interpolate(p[1], c[1], a),
29960                 ];
29961                 var curr = nbf.slice();
29962                 return {
29963                     alpha: 0,
29964                     curr: curr,
29965                     prev: prev,
29966                 };
29967             };
29968         }))
29969             .subscribe(nodeFovOperation$);
29970         this._fovAnimationSubscription = nodeFov$.pipe(operators_1.switchMap(function () {
29971             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.skip(1), operators_1.scan(function (alpha) {
29972                 return alpha + _this._animationSpeed;
29973             }, 0), operators_1.takeWhile(function (alpha) {
29974                 return alpha <= 1 + _this._animationSpeed;
29975             }), operators_1.map(function (alpha) {
29976                 return Math.min(alpha, 1);
29977             }));
29978         }), operators_1.map(function (alpha) {
29979             return function (nbfState) {
29980                 return {
29981                     alpha: alpha,
29982                     curr: nbfState.curr.slice(),
29983                     prev: nbfState.prev.slice(),
29984                 };
29985             };
29986         }))
29987             .subscribe(nodeFovOperation$);
29988         var nodeBearingFov$ = rxjs_1.combineLatest(offset$, smoothNodeFov$).pipe(operators_1.map(function (_a) {
29989             var offset = _a[0], fov = _a[1];
29990             return [offset, fov[0], fov[1]];
29991         }));
29992         this._renderSubscription = rxjs_1.combineLatest(cameraBearingFov$, nodeBearingFov$, this._configuration$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
29993             var _b = _a[0], cb = _b[0], cf = _b[1], _c = _a[1], no = _c[0], nfl = _c[1], nfr = _c[2], configuration = _a[2], size = _a[3];
29994             var background = _this._createBackground(cb);
29995             var fovIndicator = _this._createFovIndicator(nfl, nfr, no);
29996             var north = _this._createNorth(cb);
29997             var cameraSector = _this._createCircleSectorCompass(_this._createCircleSector(Math.max(Math.PI / 20, cf), "#FFF"));
29998             var compact = configuration.size === ComponentSize_1.default.Small ||
29999                 configuration.size === ComponentSize_1.default.Automatic && size.width < 640 ?
30000                 ".BearingCompact" : "";
30001             return {
30002                 name: _this._name,
30003                 vnode: vd.h("div.BearingIndicatorContainer" + compact, { oncontextmenu: function (event) { event.preventDefault(); } }, [
30004                     background,
30005                     fovIndicator,
30006                     north,
30007                     cameraSector,
30008                 ]),
30009             };
30010         }))
30011             .subscribe(this._container.domRenderer.render$);
30012     };
30013     BearingComponent.prototype._deactivate = function () {
30014         this._renderSubscription.unsubscribe();
30015         this._fovSubscription.unsubscribe();
30016         this._fovAnimationSubscription.unsubscribe();
30017     };
30018     BearingComponent.prototype._getDefaultConfiguration = function () {
30019         return { size: ComponentSize_1.default.Automatic };
30020     };
30021     BearingComponent.prototype._createFovIndicator = function (fovLeft, fovRigth, offset) {
30022         var arc = this._createFovArc(fovLeft, fovRigth);
30023         var group = vd.h("g", {
30024             attributes: { transform: "translate(18,18)" },
30025             namespace: this._svgNamespace,
30026         }, [arc]);
30027         var svg = vd.h("svg", {
30028             attributes: { viewBox: "0 0 36 36" },
30029             namespace: this._svgNamespace,
30030             style: {
30031                 height: "36px",
30032                 left: "2px",
30033                 position: "absolute",
30034                 top: "2px",
30035                 transform: "rotateZ(" + this._spatial.radToDeg(offset) + "deg)",
30036                 width: "36px",
30037             },
30038         }, [group]);
30039         return svg;
30040     };
30041     BearingComponent.prototype._createFovArc = function (fovLeft, fovRigth) {
30042         var radius = 16.75;
30043         var strokeWidth = 2.5;
30044         var fov = fovLeft + fovRigth;
30045         if (fov > 2 * Math.PI - Math.PI / 90) {
30046             return vd.h("circle", {
30047                 attributes: {
30048                     cx: "0",
30049                     cy: "0",
30050                     "fill-opacity": "0",
30051                     r: "" + radius,
30052                     stroke: "#FFF",
30053                     "stroke-width": "" + strokeWidth,
30054                 },
30055                 namespace: this._svgNamespace,
30056             }, []);
30057         }
30058         var arcStart = -Math.PI / 2 - fovLeft;
30059         var arcEnd = arcStart + fov;
30060         var startX = radius * Math.cos(arcStart);
30061         var startY = radius * Math.sin(arcStart);
30062         var endX = radius * Math.cos(arcEnd);
30063         var endY = radius * Math.sin(arcEnd);
30064         var largeArc = fov >= Math.PI ? 1 : 0;
30065         var description = "M " + startX + " " + startY + " A " + radius + " " + radius + " 0 " + largeArc + " 1 " + endX + " " + endY;
30066         return vd.h("path", {
30067             attributes: {
30068                 d: description,
30069                 "fill-opacity": "0",
30070                 stroke: "#FFF",
30071                 "stroke-width": "" + strokeWidth,
30072             },
30073             namespace: this._svgNamespace,
30074         }, []);
30075     };
30076     BearingComponent.prototype._createCircleSectorCompass = function (cameraSector) {
30077         var group = vd.h("g", {
30078             attributes: { transform: "translate(1,1)" },
30079             namespace: this._svgNamespace,
30080         }, [cameraSector]);
30081         var svg = vd.h("svg", {
30082             attributes: { viewBox: "0 0 2 2" },
30083             namespace: this._svgNamespace,
30084             style: {
30085                 height: "26px",
30086                 left: "7px",
30087                 position: "absolute",
30088                 top: "7px",
30089                 width: "26px",
30090             },
30091         }, [group]);
30092         return svg;
30093     };
30094     BearingComponent.prototype._createCircleSector = function (fov, fill) {
30095         if (fov > 2 * Math.PI - Math.PI / 90) {
30096             return vd.h("circle", {
30097                 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
30098                 namespace: this._svgNamespace,
30099             }, []);
30100         }
30101         var arcStart = -Math.PI / 2 - fov / 2;
30102         var arcEnd = arcStart + fov;
30103         var startX = Math.cos(arcStart);
30104         var startY = Math.sin(arcStart);
30105         var endX = Math.cos(arcEnd);
30106         var endY = Math.sin(arcEnd);
30107         var largeArc = fov >= Math.PI ? 1 : 0;
30108         var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
30109         return vd.h("path", {
30110             attributes: { d: description, fill: fill },
30111             namespace: this._svgNamespace,
30112         }, []);
30113     };
30114     BearingComponent.prototype._createNorth = function (bearing) {
30115         var north = vd.h("div.BearingNorth", []);
30116         var container = vd.h("div.BearingNorthContainer", { style: { transform: "rotateZ(" + this._spatial.radToDeg(-bearing) + "deg)" } }, [north]);
30117         return container;
30118     };
30119     BearingComponent.prototype._createBackground = function (bearing) {
30120         return vd.h("div.BearingIndicatorBackground", { style: { transform: "rotateZ(" + this._spatial.radToDeg(-bearing) + "deg)" } }, [
30121             vd.h("div.BearingIndicatorBackgroundCircle", []),
30122             vd.h("div.BearingIndicatorBackgroundArrowContainer", [
30123                 vd.h("div.BearingIndicatorBackgroundArrow", []),
30124             ]),
30125         ]);
30126     };
30127     BearingComponent.prototype._computeProjectedPoints = function (transform) {
30128         var vertices = [[1, 0]];
30129         var directions = [[0, 0.5]];
30130         var pointsPerLine = 12;
30131         return Geo_1.Geo.computeProjectedPoints(transform, vertices, directions, pointsPerLine, this._viewportCoords);
30132     };
30133     BearingComponent.prototype._computeHorizontalFov = function (projectedPoints) {
30134         var _this = this;
30135         var fovs = projectedPoints
30136             .map(function (projectedPoint) {
30137             return _this._coordToFov(projectedPoint[0]);
30138         });
30139         var fov = Math.min.apply(Math, fovs);
30140         return fov;
30141     };
30142     BearingComponent.prototype._coordToFov = function (x) {
30143         return this._spatial.radToDeg(2 * Math.atan(x));
30144     };
30145     BearingComponent.prototype._interpolate = function (x1, x2, alpha) {
30146         return (1 - alpha) * x1 + alpha * x2;
30147     };
30148     BearingComponent.componentName = "bearing";
30149     return BearingComponent;
30150 }(Component_1.Component));
30151 exports.BearingComponent = BearingComponent;
30152 Component_1.ComponentService.register(BearingComponent);
30153 exports.default = BearingComponent;
30154
30155
30156 },{"../Component":291,"../Geo":294,"../geo/ViewportCoords":414,"./utils/ComponentSize":398,"@mapbox/unitbezier":2,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],308:[function(require,module,exports){
30157 "use strict";
30158 var __extends = (this && this.__extends) || (function () {
30159     var extendStatics = function (d, b) {
30160         extendStatics = Object.setPrototypeOf ||
30161             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30162             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30163         return extendStatics(d, b);
30164     }
30165     return function (d, b) {
30166         extendStatics(d, b);
30167         function __() { this.constructor = d; }
30168         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30169     };
30170 })();
30171 Object.defineProperty(exports, "__esModule", { value: true });
30172 var rxjs_1 = require("rxjs");
30173 var operators_1 = require("rxjs/operators");
30174 var Edge_1 = require("../Edge");
30175 var Component_1 = require("../Component");
30176 var CacheComponent = /** @class */ (function (_super) {
30177     __extends(CacheComponent, _super);
30178     function CacheComponent(name, container, navigator) {
30179         return _super.call(this, name, container, navigator) || this;
30180     }
30181     /**
30182      * Set the cache depth.
30183      *
30184      * Configures the cache depth. The cache depth can be different for
30185      * different edge direction types.
30186      *
30187      * @param {ICacheDepth} depth - Cache depth structure.
30188      */
30189     CacheComponent.prototype.setDepth = function (depth) {
30190         this.configure({ depth: depth });
30191     };
30192     CacheComponent.prototype._activate = function () {
30193         var _this = this;
30194         this._sequenceSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
30195             return node.sequenceEdges$;
30196         }), operators_1.filter(function (status) {
30197             return status.cached;
30198         })), this._configuration$).pipe(operators_1.switchMap(function (nc) {
30199             var status = nc[0];
30200             var configuration = nc[1];
30201             var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
30202             var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
30203             var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
30204             return rxjs_1.merge(next$, prev$).pipe(operators_1.catchError(function (error, caught) {
30205                 console.error("Failed to cache sequence edges.", error);
30206                 return rxjs_1.empty();
30207             }));
30208         }))
30209             .subscribe(function () { });
30210         this._spatialSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
30211             return rxjs_1.combineLatest(rxjs_1.of(node), node.spatialEdges$.pipe(operators_1.filter(function (status) {
30212                 return status.cached;
30213             })));
30214         })), this._configuration$).pipe(operators_1.switchMap(function (_a) {
30215             var _b = _a[0], node = _b[0], edgeStatus = _b[1], configuration = _a[1];
30216             var edges = edgeStatus.edges;
30217             var depth = configuration.depth;
30218             var panoDepth = Math.max(0, Math.min(2, depth.pano));
30219             var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
30220             var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
30221             var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
30222             var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
30223             var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
30224             var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
30225             var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
30226             var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
30227             var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
30228             var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
30229             return rxjs_1.merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$).pipe(operators_1.catchError(function (error, caught) {
30230                 console.error("Failed to cache spatial edges.", error);
30231                 return rxjs_1.empty();
30232             }));
30233         }))
30234             .subscribe(function () { });
30235     };
30236     CacheComponent.prototype._deactivate = function () {
30237         this._sequenceSubscription.unsubscribe();
30238         this._spatialSubscription.unsubscribe();
30239     };
30240     CacheComponent.prototype._getDefaultConfiguration = function () {
30241         return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
30242     };
30243     CacheComponent.prototype._cache$ = function (edges, direction, depth) {
30244         var _this = this;
30245         return rxjs_1.zip(rxjs_1.of(edges), rxjs_1.of(depth)).pipe(operators_1.expand(function (ed) {
30246             var es = ed[0];
30247             var d = ed[1];
30248             var edgesDepths$ = [];
30249             if (d > 0) {
30250                 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
30251                     var edge = es_1[_i];
30252                     if (edge.data.direction === direction) {
30253                         edgesDepths$.push(rxjs_1.zip(_this._navigator.graphService.cacheNode$(edge.to).pipe(operators_1.mergeMap(function (n) {
30254                             return _this._nodeToEdges$(n, direction);
30255                         })), rxjs_1.of(d - 1)));
30256                     }
30257                 }
30258             }
30259             return rxjs_1.from(edgesDepths$).pipe(operators_1.mergeAll());
30260         }), operators_1.skip(1));
30261     };
30262     CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
30263         return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
30264             node.sequenceEdges$ :
30265             node.spatialEdges$).pipe(operators_1.first(function (status) {
30266             return status.cached;
30267         }), operators_1.map(function (status) {
30268             return status.edges;
30269         }));
30270     };
30271     CacheComponent.componentName = "cache";
30272     return CacheComponent;
30273 }(Component_1.Component));
30274 exports.CacheComponent = CacheComponent;
30275 Component_1.ComponentService.register(CacheComponent);
30276 exports.default = CacheComponent;
30277
30278 },{"../Component":291,"../Edge":292,"rxjs":43,"rxjs/operators":241}],309:[function(require,module,exports){
30279 "use strict";
30280 var __extends = (this && this.__extends) || (function () {
30281     var extendStatics = function (d, b) {
30282         extendStatics = Object.setPrototypeOf ||
30283             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30284             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30285         return extendStatics(d, b);
30286     }
30287     return function (d, b) {
30288         extendStatics(d, b);
30289         function __() { this.constructor = d; }
30290         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30291     };
30292 })();
30293 Object.defineProperty(exports, "__esModule", { value: true });
30294 var operators_1 = require("rxjs/operators");
30295 var rxjs_1 = require("rxjs");
30296 var Utils_1 = require("../Utils");
30297 var Component = /** @class */ (function (_super) {
30298     __extends(Component, _super);
30299     function Component(name, container, navigator) {
30300         var _this = _super.call(this) || this;
30301         _this._activated$ = new rxjs_1.BehaviorSubject(false);
30302         _this._configurationSubject$ = new rxjs_1.Subject();
30303         _this._activated = false;
30304         _this._container = container;
30305         _this._name = name;
30306         _this._navigator = navigator;
30307         _this._configuration$ =
30308             _this._configurationSubject$.pipe(operators_1.startWith(_this.defaultConfiguration), operators_1.scan(function (conf, newConf) {
30309                 for (var key in newConf) {
30310                     if (newConf.hasOwnProperty(key)) {
30311                         conf[key] = newConf[key];
30312                     }
30313                 }
30314                 return conf;
30315             }), operators_1.publishReplay(1), operators_1.refCount());
30316         _this._configuration$.subscribe(function () { });
30317         return _this;
30318     }
30319     Object.defineProperty(Component.prototype, "activated", {
30320         get: function () {
30321             return this._activated;
30322         },
30323         enumerable: true,
30324         configurable: true
30325     });
30326     Object.defineProperty(Component.prototype, "activated$", {
30327         /** @ignore */
30328         get: function () {
30329             return this._activated$;
30330         },
30331         enumerable: true,
30332         configurable: true
30333     });
30334     Object.defineProperty(Component.prototype, "defaultConfiguration", {
30335         /**
30336          * Get default configuration.
30337          *
30338          * @returns {TConfiguration} Default configuration for component.
30339          */
30340         get: function () {
30341             return this._getDefaultConfiguration();
30342         },
30343         enumerable: true,
30344         configurable: true
30345     });
30346     Object.defineProperty(Component.prototype, "configuration$", {
30347         /** @ignore */
30348         get: function () {
30349             return this._configuration$;
30350         },
30351         enumerable: true,
30352         configurable: true
30353     });
30354     Object.defineProperty(Component.prototype, "name", {
30355         /**
30356          * Get name.
30357          *
30358          * @description The name of the component. Used when interacting with the
30359          * component through the Viewer's API.
30360          */
30361         get: function () {
30362             return this._name;
30363         },
30364         enumerable: true,
30365         configurable: true
30366     });
30367     Component.prototype.activate = function (conf) {
30368         if (this._activated) {
30369             return;
30370         }
30371         if (conf !== undefined) {
30372             this._configurationSubject$.next(conf);
30373         }
30374         this._activated = true;
30375         this._activate();
30376         this._activated$.next(true);
30377     };
30378     Component.prototype.configure = function (conf) {
30379         this._configurationSubject$.next(conf);
30380     };
30381     Component.prototype.deactivate = function () {
30382         if (!this._activated) {
30383             return;
30384         }
30385         this._activated = false;
30386         this._deactivate();
30387         this._container.domRenderer.clear(this._name);
30388         this._container.glRenderer.clear(this._name);
30389         this._activated$.next(false);
30390     };
30391     /**
30392      * Detect the viewer's new width and height and resize the component's
30393      * rendered elements accordingly if applicable.
30394      *
30395      * @ignore
30396      */
30397     Component.prototype.resize = function () { return; };
30398     Component.componentName = "not_worthy";
30399     return Component;
30400 }(Utils_1.EventEmitter));
30401 exports.Component = Component;
30402 exports.default = Component;
30403
30404 },{"../Utils":301,"rxjs":43,"rxjs/operators":241}],310:[function(require,module,exports){
30405 "use strict";
30406 Object.defineProperty(exports, "__esModule", { value: true });
30407 var Error_1 = require("../Error");
30408 var ComponentService = /** @class */ (function () {
30409     function ComponentService(container, navigator) {
30410         this._components = {};
30411         for (var componentName in ComponentService.registeredComponents) {
30412             if (!ComponentService.registeredComponents.hasOwnProperty(componentName)) {
30413                 continue;
30414             }
30415             var component = ComponentService.registeredComponents[componentName];
30416             this._components[componentName] = {
30417                 active: false,
30418                 component: new component(componentName, container, navigator),
30419             };
30420         }
30421         this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
30422         this._coverComponent.activate();
30423         this._coverActivated = true;
30424     }
30425     ComponentService.register = function (component) {
30426         if (ComponentService.registeredComponents[component.componentName] === undefined) {
30427             ComponentService.registeredComponents[component.componentName] = component;
30428         }
30429     };
30430     ComponentService.registerCover = function (coverComponent) {
30431         ComponentService.registeredCoverComponent = coverComponent;
30432     };
30433     Object.defineProperty(ComponentService.prototype, "coverActivated", {
30434         get: function () {
30435             return this._coverActivated;
30436         },
30437         enumerable: true,
30438         configurable: true
30439     });
30440     ComponentService.prototype.activateCover = function () {
30441         if (this._coverActivated) {
30442             return;
30443         }
30444         this._coverActivated = true;
30445         for (var componentName in this._components) {
30446             if (!this._components.hasOwnProperty(componentName)) {
30447                 continue;
30448             }
30449             var component = this._components[componentName];
30450             if (component.active) {
30451                 component.component.deactivate();
30452             }
30453         }
30454     };
30455     ComponentService.prototype.deactivateCover = function () {
30456         if (!this._coverActivated) {
30457             return;
30458         }
30459         this._coverActivated = false;
30460         for (var componentName in this._components) {
30461             if (!this._components.hasOwnProperty(componentName)) {
30462                 continue;
30463             }
30464             var component = this._components[componentName];
30465             if (component.active) {
30466                 component.component.activate();
30467             }
30468         }
30469     };
30470     ComponentService.prototype.activate = function (name) {
30471         this._checkName(name);
30472         this._components[name].active = true;
30473         if (!this._coverActivated) {
30474             this.get(name).activate();
30475         }
30476     };
30477     ComponentService.prototype.configure = function (name, conf) {
30478         this._checkName(name);
30479         this.get(name).configure(conf);
30480     };
30481     ComponentService.prototype.deactivate = function (name) {
30482         this._checkName(name);
30483         this._components[name].active = false;
30484         if (!this._coverActivated) {
30485             this.get(name).deactivate();
30486         }
30487     };
30488     ComponentService.prototype.get = function (name) {
30489         return this._components[name].component;
30490     };
30491     ComponentService.prototype.getCover = function () {
30492         return this._coverComponent;
30493     };
30494     ComponentService.prototype._checkName = function (name) {
30495         if (!(name in this._components)) {
30496             throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
30497         }
30498     };
30499     ComponentService.registeredComponents = {};
30500     return ComponentService;
30501 }());
30502 exports.ComponentService = ComponentService;
30503 exports.default = ComponentService;
30504
30505 },{"../Error":293}],311:[function(require,module,exports){
30506 "use strict";
30507 var __extends = (this && this.__extends) || (function () {
30508     var extendStatics = function (d, b) {
30509         extendStatics = Object.setPrototypeOf ||
30510             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30511             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30512         return extendStatics(d, b);
30513     }
30514     return function (d, b) {
30515         extendStatics(d, b);
30516         function __() { this.constructor = d; }
30517         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30518     };
30519 })();
30520 Object.defineProperty(exports, "__esModule", { value: true });
30521 var rxjs_1 = require("rxjs");
30522 var operators_1 = require("rxjs/operators");
30523 var vd = require("virtual-dom");
30524 var Component_1 = require("../Component");
30525 var Utils_1 = require("../Utils");
30526 var Viewer_1 = require("../Viewer");
30527 var CoverComponent = /** @class */ (function (_super) {
30528     __extends(CoverComponent, _super);
30529     function CoverComponent(name, container, navigator) {
30530         return _super.call(this, name, container, navigator) || this;
30531     }
30532     CoverComponent.prototype._activate = function () {
30533         var _this = this;
30534         this._configuration$.pipe(operators_1.distinctUntilChanged(undefined, function (configuration) {
30535             return configuration.state;
30536         }), operators_1.switchMap(function (configuration) {
30537             return rxjs_1.combineLatest(rxjs_1.of(configuration.state), _this._navigator.stateService.currentNode$);
30538         }), operators_1.switchMap(function (_a) {
30539             var state = _a[0], node = _a[1];
30540             var keySrc$ = rxjs_1.combineLatest(rxjs_1.of(node.key), node.image$.pipe(operators_1.filter(function (image) {
30541                 return !!image;
30542             }), operators_1.map(function (image) {
30543                 return image.src;
30544             })));
30545             return state === Component_1.CoverState.Visible ? keySrc$.pipe(operators_1.first()) : keySrc$;
30546         }), operators_1.distinctUntilChanged(function (_a, _b) {
30547             var k1 = _a[0], s1 = _a[1];
30548             var k2 = _b[0], s2 = _b[1];
30549             return k1 === k2 && s1 === s2;
30550         }), operators_1.map(function (_a) {
30551             var key = _a[0], src = _a[1];
30552             return { key: key, src: src };
30553         }))
30554             .subscribe(this._configurationSubject$);
30555         this._renderSubscription = rxjs_1.combineLatest(this._configuration$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
30556             var configuration = _a[0], size = _a[1];
30557             if (!configuration.key) {
30558                 return { name: _this._name, vnode: vd.h("div", []) };
30559             }
30560             var compactClass = size.width <= 640 || size.height <= 480 ? ".CoverCompact" : "";
30561             if (configuration.state === Component_1.CoverState.Hidden) {
30562                 var doneContainer = vd.h("div.CoverContainer.CoverDone" + compactClass, [_this._getCoverBackgroundVNode(configuration)]);
30563                 return { name: _this._name, vnode: doneContainer };
30564             }
30565             var container = vd.h("div.CoverContainer" + compactClass, [_this._getCoverButtonVNode(configuration)]);
30566             return { name: _this._name, vnode: container };
30567         }))
30568             .subscribe(this._container.domRenderer.render$);
30569     };
30570     CoverComponent.prototype._deactivate = function () {
30571         this._renderSubscription.unsubscribe();
30572         this._keySubscription.unsubscribe();
30573     };
30574     CoverComponent.prototype._getDefaultConfiguration = function () {
30575         return { state: Component_1.CoverState.Visible };
30576     };
30577     CoverComponent.prototype._getCoverButtonVNode = function (configuration) {
30578         var _this = this;
30579         var cover = configuration.state === Component_1.CoverState.Loading ? "div.Cover.CoverLoading" : "div.Cover";
30580         var coverButton = vd.h("div.CoverButton", [vd.h("div.CoverButtonIcon", [])]);
30581         var coverLogo = vd.h("a.CoverLogo", { href: Utils_1.Urls.explore, target: "_blank" }, []);
30582         var coverIndicator = vd.h("div.CoverIndicator", { onclick: function () { _this.configure({ state: Component_1.CoverState.Loading }); } }, []);
30583         return vd.h(cover, [
30584             this._getCoverBackgroundVNode(configuration),
30585             coverIndicator,
30586             coverButton,
30587             coverLogo,
30588         ]);
30589     };
30590     CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
30591         var url = conf.src != null ?
30592             conf.src : Utils_1.Urls.thumbnail(conf.key, Viewer_1.ImageSize.Size640);
30593         var properties = { style: { backgroundImage: "url(" + url + ")" } };
30594         var children = [];
30595         if (conf.state === Component_1.CoverState.Loading) {
30596             children.push(vd.h("div.Spinner", {}, []));
30597         }
30598         return vd.h("div.CoverBackground", properties, children);
30599     };
30600     CoverComponent.componentName = "cover";
30601     return CoverComponent;
30602 }(Component_1.Component));
30603 exports.CoverComponent = CoverComponent;
30604 Component_1.ComponentService.registerCover(CoverComponent);
30605 exports.default = CoverComponent;
30606
30607 },{"../Component":291,"../Utils":301,"../Viewer":302,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],312:[function(require,module,exports){
30608 "use strict";
30609 var __extends = (this && this.__extends) || (function () {
30610     var extendStatics = function (d, b) {
30611         extendStatics = Object.setPrototypeOf ||
30612             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30613             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30614         return extendStatics(d, b);
30615     }
30616     return function (d, b) {
30617         extendStatics(d, b);
30618         function __() { this.constructor = d; }
30619         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30620     };
30621 })();
30622 Object.defineProperty(exports, "__esModule", { value: true });
30623 var rxjs_1 = require("rxjs");
30624 var operators_1 = require("rxjs/operators");
30625 var vd = require("virtual-dom");
30626 var Component_1 = require("../Component");
30627 var DebugComponent = /** @class */ (function (_super) {
30628     __extends(DebugComponent, _super);
30629     function DebugComponent() {
30630         var _this = _super !== null && _super.apply(this, arguments) || this;
30631         _this._open$ = new rxjs_1.BehaviorSubject(false);
30632         return _this;
30633     }
30634     DebugComponent.prototype._activate = function () {
30635         var _this = this;
30636         this._disposable = rxjs_1.combineLatest(this._navigator.stateService.currentState$, this._open$, this._navigator.imageLoadingService.loadstatus$).pipe(operators_1.map(function (_a) {
30637             var frame = _a[0], open = _a[1], loadStatus = _a[2];
30638             return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
30639         }))
30640             .subscribe(this._container.domRenderer.render$);
30641     };
30642     DebugComponent.prototype._deactivate = function () {
30643         this._disposable.unsubscribe();
30644     };
30645     DebugComponent.prototype._getDefaultConfiguration = function () {
30646         return {};
30647     };
30648     DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
30649         var ret = [];
30650         ret.push(vd.h("h2", "Node"));
30651         if (frame.state.currentNode) {
30652             ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
30653         }
30654         if (frame.state.previousNode) {
30655             ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
30656         }
30657         ret.push(vd.h("h2", "Loading"));
30658         var total = 0;
30659         var loaded = 0;
30660         var loading = 0;
30661         for (var key in loadStatus) {
30662             if (!loadStatus.hasOwnProperty(key)) {
30663                 continue;
30664             }
30665             var status_1 = loadStatus[key];
30666             total += status_1.loaded;
30667             if (status_1.loaded !== status_1.total) {
30668                 loading++;
30669             }
30670             else {
30671                 loaded++;
30672             }
30673         }
30674         ret.push(vd.h("p", "Loaded Images: " + loaded));
30675         ret.push(vd.h("p", "Loading Images: " + loading));
30676         ret.push(vd.h("p", "Total bytes loaded: " + total));
30677         ret.push(vd.h("h2", "Camera"));
30678         ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
30679         ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
30680         ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
30681         ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
30682         ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
30683         ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
30684         ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
30685         ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
30686         ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
30687         return ret;
30688     };
30689     DebugComponent.prototype._getDebugVNode = function (open, info) {
30690         if (open) {
30691             return vd.h("div.Debug", {}, [
30692                 vd.h("h2", {}, ["Debug"]),
30693                 this._getDebugVNodeButton(open),
30694                 vd.h("pre", {}, info),
30695             ]);
30696         }
30697         else {
30698             return this._getDebugVNodeButton(open);
30699         }
30700     };
30701     DebugComponent.prototype._getDebugVNodeButton = function (open) {
30702         var buttonText = open ? "Disable Debug" : "D";
30703         var buttonCssClass = open ? "" : ".DebugButtonFixed";
30704         if (open) {
30705             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
30706         }
30707         else {
30708             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
30709         }
30710     };
30711     DebugComponent.prototype._closeDebugElement = function (open) {
30712         this._open$.next(false);
30713     };
30714     DebugComponent.prototype._openDebugElement = function () {
30715         this._open$.next(true);
30716     };
30717     DebugComponent.componentName = "debug";
30718     return DebugComponent;
30719 }(Component_1.Component));
30720 exports.DebugComponent = DebugComponent;
30721 Component_1.ComponentService.register(DebugComponent);
30722 exports.default = DebugComponent;
30723
30724 },{"../Component":291,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],313:[function(require,module,exports){
30725 "use strict";
30726 var __extends = (this && this.__extends) || (function () {
30727     var extendStatics = function (d, b) {
30728         extendStatics = Object.setPrototypeOf ||
30729             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30730             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30731         return extendStatics(d, b);
30732     }
30733     return function (d, b) {
30734         extendStatics(d, b);
30735         function __() { this.constructor = d; }
30736         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30737     };
30738 })();
30739 Object.defineProperty(exports, "__esModule", { value: true });
30740 var rxjs_1 = require("rxjs");
30741 var operators_1 = require("rxjs/operators");
30742 var vd = require("virtual-dom");
30743 var Component_1 = require("../Component");
30744 var Utils_1 = require("../Utils");
30745 var ImageComponent = /** @class */ (function (_super) {
30746     __extends(ImageComponent, _super);
30747     function ImageComponent(name, container, navigator, dom) {
30748         var _this = _super.call(this, name, container, navigator) || this;
30749         _this._canvasId = container.id + "-" + _this._name;
30750         _this._dom = !!dom ? dom : new Utils_1.DOM();
30751         return _this;
30752     }
30753     ImageComponent.prototype._activate = function () {
30754         var _this = this;
30755         var canvasSize$ = this._container.domRenderer.element$.pipe(operators_1.map(function (element) {
30756             return _this._dom.document.getElementById(_this._canvasId);
30757         }), operators_1.filter(function (canvas) {
30758             return !!canvas;
30759         }), operators_1.map(function (canvas) {
30760             var adaptableDomRenderer = canvas.parentElement;
30761             var width = adaptableDomRenderer.offsetWidth;
30762             var height = adaptableDomRenderer.offsetHeight;
30763             return [canvas, { height: height, width: width }];
30764         }), operators_1.distinctUntilChanged(function (s1, s2) {
30765             return s1.height === s2.height && s1.width === s2.width;
30766         }, function (_a) {
30767             var canvas = _a[0], size = _a[1];
30768             return size;
30769         }));
30770         this.drawSubscription = rxjs_1.combineLatest(canvasSize$, this._navigator.stateService.currentNode$)
30771             .subscribe(function (_a) {
30772             var _b = _a[0], canvas = _b[0], size = _b[1], node = _a[1];
30773             canvas.width = size.width;
30774             canvas.height = size.height;
30775             canvas
30776                 .getContext("2d")
30777                 .drawImage(node.image, 0, 0, size.width, size.height);
30778         });
30779         this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
30780     };
30781     ImageComponent.prototype._deactivate = function () {
30782         this.drawSubscription.unsubscribe();
30783     };
30784     ImageComponent.prototype._getDefaultConfiguration = function () {
30785         return {};
30786     };
30787     ImageComponent.componentName = "image";
30788     return ImageComponent;
30789 }(Component_1.Component));
30790 exports.ImageComponent = ImageComponent;
30791 Component_1.ComponentService.register(ImageComponent);
30792 exports.default = ImageComponent;
30793
30794
30795 },{"../Component":291,"../Utils":301,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],314:[function(require,module,exports){
30796 "use strict";
30797 var __extends = (this && this.__extends) || (function () {
30798     var extendStatics = function (d, b) {
30799         extendStatics = Object.setPrototypeOf ||
30800             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30801             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30802         return extendStatics(d, b);
30803     }
30804     return function (d, b) {
30805         extendStatics(d, b);
30806         function __() { this.constructor = d; }
30807         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30808     };
30809 })();
30810 Object.defineProperty(exports, "__esModule", { value: true });
30811 var rxjs_1 = require("rxjs");
30812 var operators_1 = require("rxjs/operators");
30813 var vd = require("virtual-dom");
30814 var Component_1 = require("../Component");
30815 var LoadingComponent = /** @class */ (function (_super) {
30816     __extends(LoadingComponent, _super);
30817     function LoadingComponent(name, container, navigator) {
30818         return _super.call(this, name, container, navigator) || this;
30819     }
30820     LoadingComponent.prototype._activate = function () {
30821         var _this = this;
30822         this._loadingSubscription = this._navigator.loadingService.loading$.pipe(operators_1.switchMap(function (loading) {
30823             return loading ?
30824                 _this._navigator.imageLoadingService.loadstatus$ :
30825                 rxjs_1.of({});
30826         }), operators_1.map(function (loadStatus) {
30827             var total = 0;
30828             var loaded = 0;
30829             for (var key in loadStatus) {
30830                 if (!loadStatus.hasOwnProperty(key)) {
30831                     continue;
30832                 }
30833                 var status_1 = loadStatus[key];
30834                 if (status_1.loaded !== status_1.total) {
30835                     loaded += status_1.loaded;
30836                     total += status_1.total;
30837                 }
30838             }
30839             var percentage = 100;
30840             if (total !== 0) {
30841                 percentage = (loaded / total) * 100;
30842             }
30843             return { name: _this._name, vnode: _this._getBarVNode(percentage) };
30844         }))
30845             .subscribe(this._container.domRenderer.render$);
30846     };
30847     LoadingComponent.prototype._deactivate = function () {
30848         this._loadingSubscription.unsubscribe();
30849     };
30850     LoadingComponent.prototype._getDefaultConfiguration = function () {
30851         return {};
30852     };
30853     LoadingComponent.prototype._getBarVNode = function (percentage) {
30854         var loadingBarStyle = {};
30855         var loadingContainerStyle = {};
30856         if (percentage !== 100) {
30857             loadingBarStyle.width = percentage.toFixed(0) + "%";
30858             loadingBarStyle.opacity = "1";
30859         }
30860         else {
30861             loadingBarStyle.width = "100%";
30862             loadingBarStyle.opacity = "0";
30863         }
30864         return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
30865     };
30866     LoadingComponent.componentName = "loading";
30867     return LoadingComponent;
30868 }(Component_1.Component));
30869 exports.LoadingComponent = LoadingComponent;
30870 Component_1.ComponentService.register(LoadingComponent);
30871 exports.default = LoadingComponent;
30872
30873 },{"../Component":291,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],315:[function(require,module,exports){
30874 "use strict";
30875 var __extends = (this && this.__extends) || (function () {
30876     var extendStatics = function (d, b) {
30877         extendStatics = Object.setPrototypeOf ||
30878             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30879             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30880         return extendStatics(d, b);
30881     }
30882     return function (d, b) {
30883         extendStatics(d, b);
30884         function __() { this.constructor = d; }
30885         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30886     };
30887 })();
30888 Object.defineProperty(exports, "__esModule", { value: true });
30889 var rxjs_1 = require("rxjs");
30890 var operators_1 = require("rxjs/operators");
30891 var vd = require("virtual-dom");
30892 var Edge_1 = require("../Edge");
30893 var Error_1 = require("../Error");
30894 var Component_1 = require("../Component");
30895 /**
30896  * @class NavigationComponent
30897  *
30898  * @classdesc Fallback navigation component for environments without WebGL support.
30899  *
30900  * Replaces the functionality in the Direction and Sequence components.
30901  */
30902 var NavigationComponent = /** @class */ (function (_super) {
30903     __extends(NavigationComponent, _super);
30904     /** @ignore */
30905     function NavigationComponent(name, container, navigator) {
30906         var _this = _super.call(this, name, container, navigator) || this;
30907         _this._seqNames = {};
30908         _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Prev]] = "Prev";
30909         _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Next]] = "Next";
30910         _this._spaTopNames = {};
30911         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnLeft]] = "Turnleft";
30912         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepLeft]] = "Left";
30913         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepForward]] = "Forward";
30914         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepRight]] = "Right";
30915         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnRight]] = "Turnright";
30916         _this._spaBottomNames = {};
30917         _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnU]] = "Turnaround";
30918         _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepBackward]] = "Backward";
30919         return _this;
30920     }
30921     NavigationComponent.prototype._activate = function () {
30922         var _this = this;
30923         this._renderSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$, this._configuration$).pipe(operators_1.switchMap(function (_a) {
30924             var node = _a[0], configuration = _a[1];
30925             var sequenceEdges$ = configuration.sequence ?
30926                 node.sequenceEdges$.pipe(operators_1.map(function (status) {
30927                     return status.edges
30928                         .map(function (edge) {
30929                         return edge.data.direction;
30930                     });
30931                 })) :
30932                 rxjs_1.of([]);
30933             var spatialEdges$ = !node.pano && configuration.spatial ?
30934                 node.spatialEdges$.pipe(operators_1.map(function (status) {
30935                     return status.edges
30936                         .map(function (edge) {
30937                         return edge.data.direction;
30938                     });
30939                 })) :
30940                 rxjs_1.of([]);
30941             return rxjs_1.combineLatest(sequenceEdges$, spatialEdges$).pipe(operators_1.map(function (_a) {
30942                 var seq = _a[0], spa = _a[1];
30943                 return seq.concat(spa);
30944             }));
30945         }), operators_1.map(function (edgeDirections) {
30946             var seqs = _this._createArrowRow(_this._seqNames, edgeDirections);
30947             var spaTops = _this._createArrowRow(_this._spaTopNames, edgeDirections);
30948             var spaBottoms = _this._createArrowRow(_this._spaBottomNames, edgeDirections);
30949             var seqContainer = vd.h("div.NavigationSequence", seqs);
30950             var spaTopContainer = vd.h("div.NavigationSpatialTop", spaTops);
30951             var spaBottomContainer = vd.h("div.NavigationSpatialBottom", spaBottoms);
30952             var spaContainer = vd.h("div.NavigationSpatial", [spaTopContainer, spaBottomContainer]);
30953             return { name: _this._name, vnode: vd.h("div.NavigationContainer", [seqContainer, spaContainer]) };
30954         }))
30955             .subscribe(this._container.domRenderer.render$);
30956     };
30957     NavigationComponent.prototype._deactivate = function () {
30958         this._renderSubscription.unsubscribe();
30959     };
30960     NavigationComponent.prototype._getDefaultConfiguration = function () {
30961         return { sequence: true, spatial: true };
30962     };
30963     NavigationComponent.prototype._createArrowRow = function (arrowNames, edgeDirections) {
30964         var arrows = [];
30965         for (var arrowName in arrowNames) {
30966             if (!(arrowNames.hasOwnProperty(arrowName))) {
30967                 continue;
30968             }
30969             var direction = Edge_1.EdgeDirection[arrowName];
30970             if (edgeDirections.indexOf(direction) !== -1) {
30971                 arrows.push(this._createVNode(direction, arrowNames[arrowName], "visible"));
30972             }
30973             else {
30974                 arrows.push(this._createVNode(direction, arrowNames[arrowName], "hidden"));
30975             }
30976         }
30977         return arrows;
30978     };
30979     NavigationComponent.prototype._createVNode = function (direction, name, visibility) {
30980         var _this = this;
30981         return vd.h("span.Direction.Direction" + name, {
30982             onclick: function (ev) {
30983                 _this._navigator.moveDir$(direction)
30984                     .subscribe(undefined, function (error) {
30985                     if (!(error instanceof Error_1.AbortMapillaryError)) {
30986                         console.error(error);
30987                     }
30988                 });
30989             },
30990             style: {
30991                 visibility: visibility,
30992             },
30993         }, []);
30994     };
30995     NavigationComponent.componentName = "navigation";
30996     return NavigationComponent;
30997 }(Component_1.Component));
30998 exports.NavigationComponent = NavigationComponent;
30999 Component_1.ComponentService.register(NavigationComponent);
31000 exports.default = NavigationComponent;
31001
31002 },{"../Component":291,"../Edge":292,"../Error":293,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],316:[function(require,module,exports){
31003 "use strict";
31004 var __extends = (this && this.__extends) || (function () {
31005     var extendStatics = function (d, b) {
31006         extendStatics = Object.setPrototypeOf ||
31007             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31008             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31009         return extendStatics(d, b);
31010     }
31011     return function (d, b) {
31012         extendStatics(d, b);
31013         function __() { this.constructor = d; }
31014         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31015     };
31016 })();
31017 Object.defineProperty(exports, "__esModule", { value: true });
31018 var rxjs_1 = require("rxjs");
31019 var operators_1 = require("rxjs/operators");
31020 var vd = require("virtual-dom");
31021 var Component_1 = require("../Component");
31022 var DescriptionState = /** @class */ (function () {
31023     function DescriptionState() {
31024     }
31025     return DescriptionState;
31026 }());
31027 var RouteState = /** @class */ (function () {
31028     function RouteState() {
31029     }
31030     return RouteState;
31031 }());
31032 var RouteTrack = /** @class */ (function () {
31033     function RouteTrack() {
31034         this.nodeInstructions = [];
31035         this.nodeInstructionsOrdered = [];
31036     }
31037     return RouteTrack;
31038 }());
31039 var RouteComponent = /** @class */ (function (_super) {
31040     __extends(RouteComponent, _super);
31041     function RouteComponent(name, container, navigator) {
31042         return _super.call(this, name, container, navigator) || this;
31043     }
31044     RouteComponent.prototype._activate = function () {
31045         var _this = this;
31046         var slowedStream$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
31047             return (frame.id % 2) === 0;
31048         }), operators_1.filter(function (frame) {
31049             return frame.state.nodesAhead < 15;
31050         }), operators_1.distinctUntilChanged(undefined, function (frame) {
31051             return frame.state.lastNode.key;
31052         }));
31053         var routeTrack$ = rxjs_1.combineLatest(this.configuration$.pipe(operators_1.mergeMap(function (conf) {
31054             return rxjs_1.from(conf.paths);
31055         }), operators_1.distinct(function (p) {
31056             return p.sequenceKey;
31057         }), operators_1.mergeMap(function (path) {
31058             return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey]).pipe(operators_1.map(function (sequenceByKey) {
31059                 return sequenceByKey[path.sequenceKey];
31060             }));
31061         })), this.configuration$).pipe(operators_1.map(function (_a) {
31062             var sequence = _a[0], conf = _a[1];
31063             var i = 0;
31064             var instructionPlaces = [];
31065             for (var _i = 0, _b = conf.paths; _i < _b.length; _i++) {
31066                 var path = _b[_i];
31067                 if (path.sequenceKey === sequence.key) {
31068                     var nodeInstructions = [];
31069                     var saveKey = false;
31070                     for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
31071                         var key = _d[_c];
31072                         if (path.startKey === key) {
31073                             saveKey = true;
31074                         }
31075                         if (saveKey) {
31076                             var description = null;
31077                             for (var _e = 0, _f = path.infoKeys; _e < _f.length; _e++) {
31078                                 var infoKey = _f[_e];
31079                                 if (infoKey.key === key) {
31080                                     description = infoKey.description;
31081                                 }
31082                             }
31083                             nodeInstructions.push({ description: description, key: key });
31084                         }
31085                         if (path.stopKey === key) {
31086                             saveKey = false;
31087                         }
31088                     }
31089                     instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
31090                 }
31091                 i++;
31092             }
31093             return instructionPlaces;
31094         }), operators_1.scan(function (routeTrack, instructionPlaces) {
31095             for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
31096                 var instructionPlace = instructionPlaces_1[_i];
31097                 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
31098             }
31099             for (var place in routeTrack.nodeInstructionsOrdered) {
31100                 if (!routeTrack.nodeInstructionsOrdered.hasOwnProperty(place)) {
31101                     continue;
31102                 }
31103                 var instructionGroup = routeTrack.nodeInstructionsOrdered[place];
31104                 for (var _a = 0, instructionGroup_1 = instructionGroup; _a < instructionGroup_1.length; _a++) {
31105                     var instruction = instructionGroup_1[_a];
31106                     routeTrack.nodeInstructions.push(instruction);
31107                 }
31108             }
31109             return routeTrack;
31110         }, new RouteTrack()));
31111         var cacheNode$ = rxjs_1.combineLatest(slowedStream$, routeTrack$, this.configuration$).pipe(operators_1.map(function (_a) {
31112             var frame = _a[0], routeTrack = _a[1], conf = _a[2];
31113             return { conf: conf, frame: frame, routeTrack: routeTrack };
31114         }), operators_1.scan(function (routeState, rtAndFrame) {
31115             if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
31116                 routeState.routeTrack = rtAndFrame.routeTrack;
31117                 routeState.currentNode = rtAndFrame.frame.state.currentNode;
31118                 routeState.lastNode = rtAndFrame.frame.state.lastNode;
31119                 routeState.playing = true;
31120             }
31121             else {
31122                 _this._navigator.stateService.cutNodes();
31123                 routeState.playing = false;
31124             }
31125             return routeState;
31126         }, new RouteState()), operators_1.filter(function (routeState) {
31127             return routeState.playing;
31128         }), operators_1.filter(function (routeState) {
31129             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
31130                 var nodeInstruction = _a[_i];
31131                 if (!nodeInstruction) {
31132                     continue;
31133                 }
31134                 if (nodeInstruction.key === routeState.lastNode.key) {
31135                     return true;
31136                 }
31137             }
31138             return false;
31139         }), operators_1.distinctUntilChanged(undefined, function (routeState) {
31140             return routeState.lastNode.key;
31141         }), operators_1.mergeMap(function (routeState) {
31142             var i = 0;
31143             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
31144                 var nodeInstruction = _a[_i];
31145                 if (nodeInstruction.key === routeState.lastNode.key) {
31146                     break;
31147                 }
31148                 i++;
31149             }
31150             var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
31151             if (!nextInstruction) {
31152                 return rxjs_1.of(null);
31153             }
31154             return _this._navigator.graphService.cacheNode$(nextInstruction.key);
31155         }));
31156         this._disposable = rxjs_1.combineLatest(cacheNode$, this.configuration$).pipe(operators_1.map(function (_a) {
31157             var node = _a[0], conf = _a[1];
31158             return { conf: conf, node: node };
31159         }), operators_1.filter(function (cAN) {
31160             return cAN.node !== null && cAN.conf.playing;
31161         }), operators_1.pluck("node"))
31162             .subscribe(this._navigator.stateService.appendNode$);
31163         this._disposableDescription = rxjs_1.combineLatest(this._navigator.stateService.currentNode$, routeTrack$, this.configuration$).pipe(operators_1.map(function (_a) {
31164             var node = _a[0], routeTrack = _a[1], conf = _a[2];
31165             if (conf.playing !== undefined && !conf.playing) {
31166                 return "quit";
31167             }
31168             var description = null;
31169             for (var _i = 0, _b = routeTrack.nodeInstructions; _i < _b.length; _i++) {
31170                 var nodeInstruction = _b[_i];
31171                 if (nodeInstruction.key === node.key) {
31172                     description = nodeInstruction.description;
31173                     break;
31174                 }
31175             }
31176             return description;
31177         }), operators_1.scan(function (descriptionState, description) {
31178             if (description !== descriptionState.description && description !== null) {
31179                 descriptionState.description = description;
31180                 descriptionState.showsLeft = 6;
31181             }
31182             else {
31183                 descriptionState.showsLeft--;
31184             }
31185             if (description === "quit") {
31186                 descriptionState.description = null;
31187             }
31188             return descriptionState;
31189         }, new DescriptionState()), operators_1.map(function (descriptionState) {
31190             if (descriptionState.showsLeft > 0 && descriptionState.description) {
31191                 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
31192             }
31193             else {
31194                 return { name: _this._name, vnode: vd.h("div", []) };
31195             }
31196         }))
31197             .subscribe(this._container.domRenderer.render$);
31198     };
31199     RouteComponent.prototype._deactivate = function () {
31200         this._disposable.unsubscribe();
31201         this._disposableDescription.unsubscribe();
31202     };
31203     RouteComponent.prototype._getDefaultConfiguration = function () {
31204         return {};
31205     };
31206     RouteComponent.prototype.play = function () {
31207         this.configure({ playing: true });
31208     };
31209     RouteComponent.prototype.stop = function () {
31210         this.configure({ playing: false });
31211     };
31212     RouteComponent.prototype._getRouteAnnotationNode = function (description) {
31213         return vd.h("div.RouteFrame", {}, [
31214             vd.h("p", { textContent: description }, []),
31215         ]);
31216     };
31217     RouteComponent.componentName = "route";
31218     return RouteComponent;
31219 }(Component_1.Component));
31220 exports.RouteComponent = RouteComponent;
31221 Component_1.ComponentService.register(RouteComponent);
31222 exports.default = RouteComponent;
31223
31224 },{"../Component":291,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],317:[function(require,module,exports){
31225 "use strict";
31226 var __extends = (this && this.__extends) || (function () {
31227     var extendStatics = function (d, b) {
31228         extendStatics = Object.setPrototypeOf ||
31229             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31230             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31231         return extendStatics(d, b);
31232     }
31233     return function (d, b) {
31234         extendStatics(d, b);
31235         function __() { this.constructor = d; }
31236         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31237     };
31238 })();
31239 Object.defineProperty(exports, "__esModule", { value: true });
31240 var rxjs_1 = require("rxjs");
31241 var operators_1 = require("rxjs/operators");
31242 var Component_1 = require("../Component");
31243 var StatsComponent = /** @class */ (function (_super) {
31244     __extends(StatsComponent, _super);
31245     function StatsComponent(name, container, navigator, scheduler) {
31246         var _this = _super.call(this, name, container, navigator) || this;
31247         _this._scheduler = scheduler;
31248         return _this;
31249     }
31250     StatsComponent.prototype._activate = function () {
31251         var _this = this;
31252         this._sequenceSubscription = this._navigator.stateService.currentNode$.pipe(operators_1.scan(function (keys, node) {
31253             var sKey = node.sequenceKey;
31254             keys.report = [];
31255             if (!(sKey in keys.reported)) {
31256                 keys.report = [sKey];
31257                 keys.reported[sKey] = true;
31258             }
31259             return keys;
31260         }, { report: [], reported: {} }), operators_1.filter(function (keys) {
31261             return keys.report.length > 0;
31262         }), operators_1.mergeMap(function (keys) {
31263             return _this._navigator.apiV3.sequenceViewAdd$(keys.report).pipe(operators_1.catchError(function (error, caught) {
31264                 console.error("Failed to report sequence stats (" + keys.report + ")", error);
31265                 return rxjs_1.empty();
31266             }));
31267         }))
31268             .subscribe(function () { });
31269         this._imageSubscription = this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) {
31270             return node.key;
31271         })).pipe(operators_1.buffer(this._navigator.stateService.currentNode$.pipe(operators_1.debounceTime(5000, this._scheduler))), operators_1.scan(function (keys, newKeys) {
31272             keys.report = [];
31273             for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
31274                 var key = newKeys_1[_i];
31275                 if (!(key in keys.reported)) {
31276                     keys.report.push(key);
31277                     keys.reported[key] = true;
31278                 }
31279             }
31280             return keys;
31281         }, { report: [], reported: {} }), operators_1.filter(function (keys) {
31282             return keys.report.length > 0;
31283         }), operators_1.mergeMap(function (keys) {
31284             return _this._navigator.apiV3.imageViewAdd$(keys.report).pipe(operators_1.catchError(function (error, caught) {
31285                 console.error("Failed to report image stats (" + keys.report + ")", error);
31286                 return rxjs_1.empty();
31287             }));
31288         }))
31289             .subscribe(function () { });
31290     };
31291     StatsComponent.prototype._deactivate = function () {
31292         this._sequenceSubscription.unsubscribe();
31293         this._imageSubscription.unsubscribe();
31294     };
31295     StatsComponent.prototype._getDefaultConfiguration = function () {
31296         return {};
31297     };
31298     StatsComponent.componentName = "stats";
31299     return StatsComponent;
31300 }(Component_1.Component));
31301 exports.StatsComponent = StatsComponent;
31302 Component_1.ComponentService.register(StatsComponent);
31303 exports.default = StatsComponent;
31304
31305 },{"../Component":291,"rxjs":43,"rxjs/operators":241}],318:[function(require,module,exports){
31306 "use strict";
31307 var __extends = (this && this.__extends) || (function () {
31308     var extendStatics = function (d, b) {
31309         extendStatics = Object.setPrototypeOf ||
31310             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
31311             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31312         return extendStatics(d, b);
31313     }
31314     return function (d, b) {
31315         extendStatics(d, b);
31316         function __() { this.constructor = d; }
31317         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31318     };
31319 })();
31320 Object.defineProperty(exports, "__esModule", { value: true });
31321 var vd = require("virtual-dom");
31322 var rxjs_1 = require("rxjs");
31323 var operators_1 = require("rxjs/operators");
31324 var Component_1 = require("../../Component");
31325 /**
31326  * @class DirectionComponent
31327  * @classdesc Component showing navigation arrows for steps and turns.
31328  */
31329 var DirectionComponent = /** @class */ (function (_super) {
31330     __extends(DirectionComponent, _super);
31331     function DirectionComponent(name, container, navigator, directionDOMRenderer) {
31332         var _this = _super.call(this, name, container, navigator) || this;
31333         _this._renderer = !!directionDOMRenderer ?
31334             directionDOMRenderer :
31335             new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, { height: container.element.offsetHeight, width: container.element.offsetWidth });
31336         _this._hoveredKeySubject$ = new rxjs_1.Subject();
31337         _this._hoveredKey$ = _this._hoveredKeySubject$.pipe(operators_1.share());
31338         return _this;
31339     }
31340     Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
31341         /**
31342          * Get hovered key observable.
31343          *
31344          * @description An observable emitting the key of the node for the direction
31345          * arrow that is being hovered. When the mouse leaves a direction arrow null
31346          * is emitted.
31347          *
31348          * @returns {Observable<string>}
31349          */
31350         get: function () {
31351             return this._hoveredKey$;
31352         },
31353         enumerable: true,
31354         configurable: true
31355     });
31356     /**
31357      * Set highlight key.
31358      *
31359      * @description The arrow pointing towards the node corresponding to the
31360      * highlight key will be highlighted.
31361      *
31362      * @param {string} highlightKey Key of node to be highlighted if existing
31363      * among arrows.
31364      */
31365     DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
31366         this.configure({ highlightKey: highlightKey });
31367     };
31368     /**
31369      * Set min width of container element.
31370      *
31371      * @description  Set min width of the non transformed container element holding
31372      * the navigation arrows. If the min width is larger than the max width the
31373      * min width value will be used.
31374      *
31375      * The container element is automatically resized when the resize
31376      * method on the Viewer class is called.
31377      *
31378      * @param {number} minWidth
31379      */
31380     DirectionComponent.prototype.setMinWidth = function (minWidth) {
31381         this.configure({ minWidth: minWidth });
31382     };
31383     /**
31384      * Set max width of container element.
31385      *
31386      * @description Set max width of the non transformed container element holding
31387      * the navigation arrows. If the min width is larger than the max width the
31388      * min width value will be used.
31389      *
31390      * The container element is automatically resized when the resize
31391      * method on the Viewer class is called.
31392      *
31393      * @param {number} minWidth
31394      */
31395     DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
31396         this.configure({ maxWidth: maxWidth });
31397     };
31398     DirectionComponent.prototype._activate = function () {
31399         var _this = this;
31400         this._configurationSubscription = this._configuration$
31401             .subscribe(function (configuration) {
31402             _this._renderer.setConfiguration(configuration);
31403         });
31404         this._resizeSubscription = this._container.renderService.size$
31405             .subscribe(function (size) {
31406             _this._renderer.resize(size);
31407         });
31408         this._nodeSubscription = this._navigator.stateService.currentNode$.pipe(operators_1.tap(function (node) {
31409             _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
31410             _this._renderer.setNode(node);
31411         }), operators_1.withLatestFrom(this._configuration$), operators_1.switchMap(function (_a) {
31412             var node = _a[0], configuration = _a[1];
31413             return rxjs_1.combineLatest(node.spatialEdges$, configuration.distinguishSequence ?
31414                 _this._navigator.graphService
31415                     .cacheSequence$(node.sequenceKey).pipe(operators_1.catchError(function (error, caught) {
31416                     console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
31417                     return rxjs_1.of(null);
31418                 })) :
31419                 rxjs_1.of(null));
31420         }))
31421             .subscribe(function (_a) {
31422             var edgeStatus = _a[0], sequence = _a[1];
31423             _this._renderer.setEdges(edgeStatus, sequence);
31424         });
31425         this._renderCameraSubscription = this._container.renderService.renderCameraFrame$.pipe(operators_1.tap(function (renderCamera) {
31426             _this._renderer.setRenderCamera(renderCamera);
31427         }), operators_1.map(function () {
31428             return _this._renderer;
31429         }), operators_1.filter(function (renderer) {
31430             return renderer.needsRender;
31431         }), operators_1.map(function (renderer) {
31432             return { name: _this._name, vnode: renderer.render(_this._navigator) };
31433         }))
31434             .subscribe(this._container.domRenderer.render$);
31435         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) {
31436             var element = _a[0];
31437             var elements = element.getElementsByClassName("DirectionsPerspective");
31438             for (var i = 0; i < elements.length; i++) {
31439                 var hovered = elements.item(i).querySelector(":hover");
31440                 if (hovered != null && hovered.hasAttribute("data-key")) {
31441                     return hovered.getAttribute("data-key");
31442                 }
31443             }
31444             return null;
31445         }), operators_1.distinctUntilChanged())
31446             .subscribe(this._hoveredKeySubject$);
31447         this._emitHoveredKeySubscription = this._hoveredKey$
31448             .subscribe(function (key) {
31449             _this.fire(DirectionComponent.hoveredkeychanged, key);
31450         });
31451     };
31452     DirectionComponent.prototype._deactivate = function () {
31453         this._configurationSubscription.unsubscribe();
31454         this._emitHoveredKeySubscription.unsubscribe();
31455         this._hoveredKeySubscription.unsubscribe();
31456         this._nodeSubscription.unsubscribe();
31457         this._renderCameraSubscription.unsubscribe();
31458     };
31459     DirectionComponent.prototype._getDefaultConfiguration = function () {
31460         return {
31461             distinguishSequence: false,
31462             maxWidth: 460,
31463             minWidth: 260,
31464         };
31465     };
31466     /** @inheritdoc */
31467     DirectionComponent.componentName = "direction";
31468     /**
31469      * Event fired when the hovered key changes.
31470      *
31471      * @description Emits the key of the node for the direction
31472      * arrow that is being hovered. When the mouse leaves a
31473      * direction arrow null is emitted.
31474      *
31475      * @event DirectionComponent#hoveredkeychanged
31476      * @type {string} The hovered key, null if no key is hovered.
31477      */
31478     DirectionComponent.hoveredkeychanged = "hoveredkeychanged";
31479     return DirectionComponent;
31480 }(Component_1.Component));
31481 exports.DirectionComponent = DirectionComponent;
31482 Component_1.ComponentService.register(DirectionComponent);
31483 exports.default = DirectionComponent;
31484
31485
31486 },{"../../Component":291,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],319:[function(require,module,exports){
31487 "use strict";
31488 Object.defineProperty(exports, "__esModule", { value: true });
31489 var Geo_1 = require("../../Geo");
31490 /**
31491  * @class DirectionDOMCalculator
31492  * @classdesc Helper class for calculating DOM CSS properties.
31493  */
31494 var DirectionDOMCalculator = /** @class */ (function () {
31495     function DirectionDOMCalculator(configuration, size) {
31496         this._spatial = new Geo_1.Spatial();
31497         this._minThresholdWidth = 320;
31498         this._maxThresholdWidth = 1480;
31499         this._minThresholdHeight = 240;
31500         this._maxThresholdHeight = 820;
31501         this._configure(configuration);
31502         this._resize(size);
31503         this._reset();
31504     }
31505     Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
31506         get: function () {
31507             return this._minWidth;
31508         },
31509         enumerable: true,
31510         configurable: true
31511     });
31512     Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
31513         get: function () {
31514             return this._maxWidth;
31515         },
31516         enumerable: true,
31517         configurable: true
31518     });
31519     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
31520         get: function () {
31521             return this._containerWidth;
31522         },
31523         enumerable: true,
31524         configurable: true
31525     });
31526     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
31527         get: function () {
31528             return this._containerWidthCss;
31529         },
31530         enumerable: true,
31531         configurable: true
31532     });
31533     Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
31534         get: function () {
31535             return this._containerMarginCss;
31536         },
31537         enumerable: true,
31538         configurable: true
31539     });
31540     Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
31541         get: function () {
31542             return this._containerLeftCss;
31543         },
31544         enumerable: true,
31545         configurable: true
31546     });
31547     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
31548         get: function () {
31549             return this._containerHeight;
31550         },
31551         enumerable: true,
31552         configurable: true
31553     });
31554     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
31555         get: function () {
31556             return this._containerHeightCss;
31557         },
31558         enumerable: true,
31559         configurable: true
31560     });
31561     Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
31562         get: function () {
31563             return this._containerBottomCss;
31564         },
31565         enumerable: true,
31566         configurable: true
31567     });
31568     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
31569         get: function () {
31570             return this._stepCircleSize;
31571         },
31572         enumerable: true,
31573         configurable: true
31574     });
31575     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
31576         get: function () {
31577             return this._stepCircleSizeCss;
31578         },
31579         enumerable: true,
31580         configurable: true
31581     });
31582     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
31583         get: function () {
31584             return this._stepCircleMarginCss;
31585         },
31586         enumerable: true,
31587         configurable: true
31588     });
31589     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
31590         get: function () {
31591             return this._turnCircleSize;
31592         },
31593         enumerable: true,
31594         configurable: true
31595     });
31596     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
31597         get: function () {
31598             return this._turnCircleSizeCss;
31599         },
31600         enumerable: true,
31601         configurable: true
31602     });
31603     Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
31604         get: function () {
31605             return this._outerRadius;
31606         },
31607         enumerable: true,
31608         configurable: true
31609     });
31610     Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
31611         get: function () {
31612             return this._innerRadius;
31613         },
31614         enumerable: true,
31615         configurable: true
31616     });
31617     Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
31618         get: function () {
31619             return this._shadowOffset;
31620         },
31621         enumerable: true,
31622         configurable: true
31623     });
31624     /**
31625      * Configures the min and max width values.
31626      *
31627      * @param {IDirectionConfiguration} configuration Configuration
31628      * with min and max width values.
31629      */
31630     DirectionDOMCalculator.prototype.configure = function (configuration) {
31631         this._configure(configuration);
31632         this._reset();
31633     };
31634     /**
31635      * Resizes all properties according to the width and height
31636      * of the size object.
31637      *
31638      * @param {ISize} size The size of the container element.
31639      */
31640     DirectionDOMCalculator.prototype.resize = function (size) {
31641         this._resize(size);
31642         this._reset();
31643     };
31644     /**
31645      * Calculates the coordinates on the unit circle for an angle.
31646      *
31647      * @param {number} angle Angle in radians.
31648      * @returns {Array<number>} The x and y coordinates on the unit circle.
31649      */
31650     DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
31651         return [Math.cos(angle), Math.sin(angle)];
31652     };
31653     /**
31654      * Calculates the coordinates on the unit circle for the
31655      * relative angle between the first and second angle.
31656      *
31657      * @param {number} first Angle in radians.
31658      * @param {number} second Angle in radians.
31659      * @returns {Array<number>} The x and y coordinates on the unit circle
31660      * for the relative angle between the first and second angle.
31661      */
31662     DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
31663         var relativeAngle = this._spatial.wrapAngle(first - second);
31664         return this.angleToCoordinates(relativeAngle);
31665     };
31666     DirectionDOMCalculator.prototype._configure = function (configuration) {
31667         this._minWidth = configuration.minWidth;
31668         this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
31669     };
31670     DirectionDOMCalculator.prototype._resize = function (size) {
31671         this._elementWidth = size.width;
31672         this._elementHeight = size.height;
31673     };
31674     DirectionDOMCalculator.prototype._reset = function () {
31675         this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
31676         this._containerHeight = this._getContainerHeight(this.containerWidth);
31677         this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
31678         this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
31679         this._outerRadius = this._getOuterRadius(this._containerHeight);
31680         this._innerRadius = this._getInnerRadius(this._containerHeight);
31681         this._shadowOffset = 3;
31682         this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
31683         this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
31684         this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
31685         this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
31686         this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
31687         this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
31688         this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
31689         this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
31690     };
31691     DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
31692         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
31693         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
31694         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
31695         coeff = 0.04 * Math.round(25 * coeff);
31696         return this._minWidth + coeff * (this._maxWidth - this._minWidth);
31697     };
31698     DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
31699         return 0.77 * containerWidth;
31700     };
31701     DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
31702         return 0.34 * containerHeight;
31703     };
31704     DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
31705         return 0.3 * containerHeight;
31706     };
31707     DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
31708         return 0.31 * containerHeight;
31709     };
31710     DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
31711         return 0.125 * containerHeight;
31712     };
31713     DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
31714         return value + "px";
31715     };
31716     DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
31717         return value > minWidth ? value : minWidth;
31718     };
31719     return DirectionDOMCalculator;
31720 }());
31721 exports.DirectionDOMCalculator = DirectionDOMCalculator;
31722 exports.default = DirectionDOMCalculator;
31723
31724
31725 },{"../../Geo":294}],320:[function(require,module,exports){
31726 "use strict";
31727 Object.defineProperty(exports, "__esModule", { value: true });
31728 var vd = require("virtual-dom");
31729 var Component_1 = require("../../Component");
31730 var Edge_1 = require("../../Edge");
31731 var Error_1 = require("../../Error");
31732 var Geo_1 = require("../../Geo");
31733 /**
31734  * @class DirectionDOMRenderer
31735  * @classdesc DOM renderer for direction arrows.
31736  */
31737 var DirectionDOMRenderer = /** @class */ (function () {
31738     function DirectionDOMRenderer(configuration, size) {
31739         this._isEdge = false;
31740         this._spatial = new Geo_1.Spatial();
31741         this._calculator = new Component_1.DirectionDOMCalculator(configuration, size);
31742         this._node = null;
31743         this._rotation = { phi: 0, theta: 0 };
31744         this._epsilon = 0.5 * Math.PI / 180;
31745         this._highlightKey = null;
31746         this._distinguishSequence = false;
31747         this._needsRender = false;
31748         this._stepEdges = [];
31749         this._turnEdges = [];
31750         this._panoEdges = [];
31751         this._sequenceEdgeKeys = [];
31752         this._stepDirections = [
31753             Edge_1.EdgeDirection.StepForward,
31754             Edge_1.EdgeDirection.StepBackward,
31755             Edge_1.EdgeDirection.StepLeft,
31756             Edge_1.EdgeDirection.StepRight,
31757         ];
31758         this._turnDirections = [
31759             Edge_1.EdgeDirection.TurnLeft,
31760             Edge_1.EdgeDirection.TurnRight,
31761             Edge_1.EdgeDirection.TurnU,
31762         ];
31763         this._turnNames = {};
31764         this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
31765         this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
31766         this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
31767         // detects IE 8-11, then Edge 20+.
31768         var isIE = !!document.documentMode;
31769         this._isEdge = !isIE && !!window.StyleMedia;
31770     }
31771     Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
31772         /**
31773          * Get needs render.
31774          *
31775          * @returns {boolean} Value indicating whether render should be called.
31776          */
31777         get: function () {
31778             return this._needsRender;
31779         },
31780         enumerable: true,
31781         configurable: true
31782     });
31783     /**
31784      * Renders virtual DOM elements.
31785      *
31786      * @description Calling render resets the needs render property.
31787      */
31788     DirectionDOMRenderer.prototype.render = function (navigator) {
31789         this._needsRender = false;
31790         var rotation = this._rotation;
31791         var steps = [];
31792         var turns = [];
31793         if (this._node.pano) {
31794             steps = steps.concat(this._createPanoArrows(navigator, rotation));
31795         }
31796         else {
31797             steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
31798             steps = steps.concat(this._createStepArrows(navigator, rotation));
31799             turns = turns.concat(this._createTurnArrows(navigator));
31800         }
31801         return this._getContainer(steps, turns, rotation);
31802     };
31803     DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
31804         this._setEdges(edgeStatus, sequence);
31805         this._setNeedsRender();
31806     };
31807     /**
31808      * Set node for which to show edges.
31809      *
31810      * @param {Node} node
31811      */
31812     DirectionDOMRenderer.prototype.setNode = function (node) {
31813         this._node = node;
31814         this._clearEdges();
31815         this._setNeedsRender();
31816     };
31817     /**
31818      * Set the render camera to use for calculating rotations.
31819      *
31820      * @param {RenderCamera} renderCamera
31821      */
31822     DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
31823         var rotation = renderCamera.rotation;
31824         if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
31825             return;
31826         }
31827         this._rotation = rotation;
31828         this._setNeedsRender();
31829     };
31830     /**
31831      * Set configuration values.
31832      *
31833      * @param {IDirectionConfiguration} configuration
31834      */
31835     DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
31836         var needsRender = false;
31837         if (this._highlightKey !== configuration.highlightKey ||
31838             this._distinguishSequence !== configuration.distinguishSequence) {
31839             this._highlightKey = configuration.highlightKey;
31840             this._distinguishSequence = configuration.distinguishSequence;
31841             needsRender = true;
31842         }
31843         if (this._calculator.minWidth !== configuration.minWidth ||
31844             this._calculator.maxWidth !== configuration.maxWidth) {
31845             this._calculator.configure(configuration);
31846             needsRender = true;
31847         }
31848         if (needsRender) {
31849             this._setNeedsRender();
31850         }
31851     };
31852     /**
31853      * Detect the element's width and height and resize
31854      * elements accordingly.
31855      *
31856      * @param {ISize} size Size of vßiewer container element.
31857      */
31858     DirectionDOMRenderer.prototype.resize = function (size) {
31859         this._calculator.resize(size);
31860         this._setNeedsRender();
31861     };
31862     DirectionDOMRenderer.prototype._setNeedsRender = function () {
31863         if (this._node != null) {
31864             this._needsRender = true;
31865         }
31866     };
31867     DirectionDOMRenderer.prototype._clearEdges = function () {
31868         this._stepEdges = [];
31869         this._turnEdges = [];
31870         this._panoEdges = [];
31871         this._sequenceEdgeKeys = [];
31872     };
31873     DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
31874         this._stepEdges = [];
31875         this._turnEdges = [];
31876         this._panoEdges = [];
31877         this._sequenceEdgeKeys = [];
31878         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
31879             var edge = _a[_i];
31880             var direction = edge.data.direction;
31881             if (this._stepDirections.indexOf(direction) > -1) {
31882                 this._stepEdges.push(edge);
31883                 continue;
31884             }
31885             if (this._turnDirections.indexOf(direction) > -1) {
31886                 this._turnEdges.push(edge);
31887                 continue;
31888             }
31889             if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
31890                 this._panoEdges.push(edge);
31891             }
31892         }
31893         if (this._distinguishSequence && sequence != null) {
31894             var edges = this._panoEdges
31895                 .concat(this._stepEdges)
31896                 .concat(this._turnEdges);
31897             for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
31898                 var edge = edges_1[_b];
31899                 var edgeKey = edge.to;
31900                 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
31901                     var sequenceKey = _d[_c];
31902                     if (sequenceKey === edgeKey) {
31903                         this._sequenceEdgeKeys.push(edgeKey);
31904                         break;
31905                     }
31906                 }
31907             }
31908         }
31909     };
31910     DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
31911         var arrows = [];
31912         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
31913             var panoEdge = _a[_i];
31914             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
31915         }
31916         for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
31917             var stepEdge = _c[_b];
31918             arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
31919         }
31920         return arrows;
31921     };
31922     DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
31923         var threshold = Math.PI / 8;
31924         var relativePhi = rotation.phi;
31925         switch (direction) {
31926             case Edge_1.EdgeDirection.StepBackward:
31927                 relativePhi = rotation.phi - Math.PI;
31928                 break;
31929             case Edge_1.EdgeDirection.StepLeft:
31930                 relativePhi = rotation.phi + Math.PI / 2;
31931                 break;
31932             case Edge_1.EdgeDirection.StepRight:
31933                 relativePhi = rotation.phi - Math.PI / 2;
31934                 break;
31935             default:
31936                 break;
31937         }
31938         if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
31939             return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
31940         }
31941         return this._createVNodeDisabled(key, azimuth, rotation);
31942     };
31943     DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
31944         var arrows = [];
31945         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
31946             var panoEdge = _a[_i];
31947             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
31948         }
31949         return arrows;
31950     };
31951     DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
31952         var arrows = [];
31953         for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
31954             var stepEdge = _a[_i];
31955             arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
31956         }
31957         return arrows;
31958     };
31959     DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
31960         var turns = [];
31961         for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
31962             var turnEdge = _a[_i];
31963             var direction = turnEdge.data.direction;
31964             var name_1 = this._turnNames[direction];
31965             turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
31966         }
31967         return turns;
31968     };
31969     DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
31970         var onClick = function (e) {
31971             navigator.moveToKey$(key)
31972                 .subscribe(undefined, function (error) {
31973                 if (!(error instanceof Error_1.AbortMapillaryError)) {
31974                     console.error(error);
31975                 }
31976             });
31977         };
31978         return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
31979     };
31980     DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
31981         var onClick = function (e) {
31982             navigator.moveDir$(direction)
31983                 .subscribe(undefined, function (error) {
31984                 if (!(error instanceof Error_1.AbortMapillaryError)) {
31985                     console.error(error);
31986                 }
31987             });
31988         };
31989         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
31990     };
31991     DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
31992         var onClick = function (e) {
31993             navigator.moveDir$(direction)
31994                 .subscribe(undefined, function (error) {
31995                 if (!(error instanceof Error_1.AbortMapillaryError)) {
31996                     console.error(error);
31997                 }
31998             });
31999         };
32000         var style = {
32001             height: this._calculator.turnCircleSizeCss,
32002             transform: "rotate(0)",
32003             width: this._calculator.turnCircleSizeCss,
32004         };
32005         switch (direction) {
32006             case Edge_1.EdgeDirection.TurnLeft:
32007                 style.left = "5px";
32008                 style.top = "5px";
32009                 break;
32010             case Edge_1.EdgeDirection.TurnRight:
32011                 style.right = "5px";
32012                 style.top = "5px";
32013                 break;
32014             case Edge_1.EdgeDirection.TurnU:
32015                 style.left = "5px";
32016                 style.bottom = "5px";
32017                 break;
32018             default:
32019                 break;
32020         }
32021         var circleProperties = {
32022             attributes: {
32023                 "data-key": key,
32024             },
32025             onclick: onClick,
32026             style: style,
32027         };
32028         var circleClassName = "TurnCircle";
32029         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
32030             circleClassName += "Sequence";
32031         }
32032         if (this._highlightKey === key) {
32033             circleClassName += "Highlight";
32034         }
32035         var turn = vd.h("div." + className, {}, []);
32036         return vd.h("div." + circleClassName, circleProperties, [turn]);
32037     };
32038     DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
32039         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
32040     };
32041     DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
32042         var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
32043         // rotate 90 degrees clockwise and flip over X-axis
32044         var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
32045         var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
32046         var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
32047         var shadowOffset = this._calculator.shadowOffset;
32048         var shadowTranslationX = -shadowOffset * shadowTranslation[1];
32049         var shadowTranslationY = shadowOffset * shadowTranslation[0];
32050         var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
32051         var properties = {
32052             style: {
32053                 "-webkit-filter": filter,
32054                 filter: filter,
32055             },
32056         };
32057         var chevron = vd.h("div." + className, properties, []);
32058         var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
32059         var circleTransform = shiftVertically ?
32060             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
32061             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
32062         var circleProperties = {
32063             attributes: { "data-key": key },
32064             onclick: onClick,
32065             style: {
32066                 height: this._calculator.stepCircleSizeCss,
32067                 marginLeft: this._calculator.stepCircleMarginCss,
32068                 marginTop: this._calculator.stepCircleMarginCss,
32069                 transform: circleTransform,
32070                 width: this._calculator.stepCircleSizeCss,
32071             },
32072         };
32073         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
32074             circleClassName += "Sequence";
32075         }
32076         if (this._highlightKey === key) {
32077             circleClassName += "Highlight";
32078         }
32079         return vd.h("div." + circleClassName, circleProperties, [chevron]);
32080     };
32081     DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
32082         // edge does not handle hover on perspective transforms.
32083         var transform = this._isEdge ?
32084             "rotateX(60deg)" :
32085             "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
32086         var properties = {
32087             oncontextmenu: function (event) { event.preventDefault(); },
32088             style: {
32089                 bottom: this._calculator.containerBottomCss,
32090                 height: this._calculator.containerHeightCss,
32091                 left: this._calculator.containerLeftCss,
32092                 marginLeft: this._calculator.containerMarginCss,
32093                 transform: transform,
32094                 width: this._calculator.containerWidthCss,
32095             },
32096         };
32097         return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
32098     };
32099     return DirectionDOMRenderer;
32100 }());
32101 exports.DirectionDOMRenderer = DirectionDOMRenderer;
32102 exports.default = DirectionDOMRenderer;
32103
32104
32105 },{"../../Component":291,"../../Edge":292,"../../Error":293,"../../Geo":294,"virtual-dom":247}],321:[function(require,module,exports){
32106 "use strict";
32107 var __extends = (this && this.__extends) || (function () {
32108     var extendStatics = function (d, b) {
32109         extendStatics = Object.setPrototypeOf ||
32110             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32111             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32112         return extendStatics(d, b);
32113     }
32114     return function (d, b) {
32115         extendStatics(d, b);
32116         function __() { this.constructor = d; }
32117         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32118     };
32119 })();
32120 Object.defineProperty(exports, "__esModule", { value: true });
32121 var rxjs_1 = require("rxjs");
32122 var operators_1 = require("rxjs/operators");
32123 var Component_1 = require("../../Component");
32124 var Viewer_1 = require("../../Viewer");
32125 var Render_1 = require("../../Render");
32126 var Tiles_1 = require("../../Tiles");
32127 var Utils_1 = require("../../Utils");
32128 var ViewportCoords_1 = require("../../geo/ViewportCoords");
32129 var Spatial_1 = require("../../geo/Spatial");
32130 var ImagePlaneComponent = /** @class */ (function (_super) {
32131     __extends(ImagePlaneComponent, _super);
32132     function ImagePlaneComponent(name, container, navigator) {
32133         var _this = _super.call(this, name, container, navigator) || this;
32134         _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
32135         _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
32136         _this._rendererOperation$ = new rxjs_1.Subject();
32137         _this._rendererCreator$ = new rxjs_1.Subject();
32138         _this._rendererDisposer$ = new rxjs_1.Subject();
32139         _this._renderer$ = _this._rendererOperation$.pipe(operators_1.scan(function (renderer, operation) {
32140             return operation(renderer);
32141         }, null), operators_1.filter(function (renderer) {
32142             return renderer != null;
32143         }), operators_1.distinctUntilChanged(undefined, function (renderer) {
32144             return renderer.frameId;
32145         }));
32146         _this._rendererCreator$.pipe(operators_1.map(function () {
32147             return function (renderer) {
32148                 if (renderer != null) {
32149                     throw new Error("Multiple image plane states can not be created at the same time");
32150                 }
32151                 return new Component_1.ImagePlaneGLRenderer();
32152             };
32153         }))
32154             .subscribe(_this._rendererOperation$);
32155         _this._rendererDisposer$.pipe(operators_1.map(function () {
32156             return function (renderer) {
32157                 renderer.dispose();
32158                 return null;
32159             };
32160         }))
32161             .subscribe(_this._rendererOperation$);
32162         return _this;
32163     }
32164     ImagePlaneComponent.prototype._activate = function () {
32165         var _this = this;
32166         this._rendererSubscription = this._renderer$.pipe(operators_1.map(function (renderer) {
32167             var renderHash = {
32168                 name: _this._name,
32169                 render: {
32170                     frameId: renderer.frameId,
32171                     needsRender: renderer.needsRender,
32172                     render: renderer.render.bind(renderer),
32173                     stage: Render_1.GLRenderStage.Background,
32174                 },
32175             };
32176             renderer.clearNeedsRender();
32177             return renderHash;
32178         }))
32179             .subscribe(this._container.glRenderer.render$);
32180         this._rendererCreator$.next(null);
32181         this._stateSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
32182             return function (renderer) {
32183                 renderer.updateFrame(frame);
32184                 return renderer;
32185             };
32186         }))
32187             .subscribe(this._rendererOperation$);
32188         var textureProvider$ = this._navigator.stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
32189             return frame.state.currentNode.key;
32190         }), operators_1.withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), operators_1.map(function (_a) {
32191             var frame = _a[0], renderer = _a[1], size = _a[2];
32192             var state = frame.state;
32193             var viewportSize = Math.max(size.width, size.height);
32194             var currentNode = state.currentNode;
32195             var currentTransform = state.currentTransform;
32196             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
32197             return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
32198         }), operators_1.publishReplay(1), operators_1.refCount());
32199         this._textureProviderSubscription = textureProvider$.subscribe(function () { });
32200         this._setTextureProviderSubscription = textureProvider$.pipe(operators_1.map(function (provider) {
32201             return function (renderer) {
32202                 renderer.setTextureProvider(provider.key, provider);
32203                 return renderer;
32204             };
32205         }))
32206             .subscribe(this._rendererOperation$);
32207         this._setTileSizeSubscription = this._container.renderService.size$.pipe(operators_1.switchMap(function (size) {
32208             return rxjs_1.combineLatest(textureProvider$, rxjs_1.of(size)).pipe(operators_1.first());
32209         }))
32210             .subscribe(function (_a) {
32211             var provider = _a[0], size = _a[1];
32212             var viewportSize = Math.max(size.width, size.height);
32213             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
32214             provider.setTileSize(tileSize);
32215         });
32216         this._abortTextureProviderSubscription = textureProvider$.pipe(operators_1.pairwise())
32217             .subscribe(function (pair) {
32218             var previous = pair[0];
32219             previous.abort();
32220         });
32221         var roiTrigger$ = rxjs_1.combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(operators_1.debounceTime(250))).pipe(operators_1.map(function (_a) {
32222             var camera = _a[0], size = _a[1];
32223             return [
32224                 camera.camera.position.clone(),
32225                 camera.camera.lookat.clone(),
32226                 camera.zoom.valueOf(),
32227                 size.height.valueOf(),
32228                 size.width.valueOf()
32229             ];
32230         }), operators_1.pairwise(), operators_1.skipWhile(function (pls) {
32231             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
32232         }), operators_1.map(function (pls) {
32233             var samePosition = pls[0][0].equals(pls[1][0]);
32234             var sameLookat = pls[0][1].equals(pls[1][1]);
32235             var sameZoom = pls[0][2] === pls[1][2];
32236             var sameHeight = pls[0][3] === pls[1][3];
32237             var sameWidth = pls[0][4] === pls[1][4];
32238             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
32239         }), operators_1.distinctUntilChanged(), operators_1.filter(function (stalled) {
32240             return stalled;
32241         }), operators_1.switchMap(function (stalled) {
32242             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.first());
32243         }), operators_1.withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$));
32244         this._setRegionOfInterestSubscription = textureProvider$.pipe(operators_1.switchMap(function (provider) {
32245             return roiTrigger$.pipe(operators_1.map(function (_a) {
32246                 var camera = _a[0], size = _a[1], transform = _a[2];
32247                 var basic = new ViewportCoords_1.default().viewportToBasic(0, 0, transform, camera.perspective);
32248                 if (basic[0] < 0 || basic[1] < 0 || basic[0] > 1 || basic[1] > 1) {
32249                     return undefined;
32250                 }
32251                 return [
32252                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
32253                     provider,
32254                 ];
32255             }), operators_1.filter(function (args) {
32256                 return !!args;
32257             }));
32258         }), operators_1.filter(function (args) {
32259             return !args[1].disposed;
32260         }))
32261             .subscribe(function (args) {
32262             var roi = args[0];
32263             var provider = args[1];
32264             provider.setRegionOfInterest(roi);
32265         });
32266         var hasTexture$ = textureProvider$.pipe(operators_1.switchMap(function (provider) {
32267             return provider.hasTexture$;
32268         }), operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
32269         this._hasTextureSubscription = hasTexture$.subscribe(function () { });
32270         var nodeImage$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
32271             return frame.state.nodesAhead === 0;
32272         }), operators_1.map(function (frame) {
32273             return frame.state.currentNode;
32274         }), operators_1.distinctUntilChanged(undefined, function (node) {
32275             return node.key;
32276         }), operators_1.debounceTime(1000), operators_1.withLatestFrom(hasTexture$), operators_1.filter(function (args) {
32277             return !args[1];
32278         }), operators_1.map(function (args) {
32279             return args[0];
32280         }), operators_1.filter(function (node) {
32281             return node.pano ?
32282                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
32283                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
32284         }), operators_1.switchMap(function (node) {
32285             var baseImageSize = node.pano ?
32286                 Utils_1.Settings.basePanoramaSize :
32287                 Utils_1.Settings.baseImageSize;
32288             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
32289                 return rxjs_1.empty();
32290             }
32291             var image$ = node
32292                 .cacheImage$(Utils_1.Settings.maxImageSize).pipe(operators_1.map(function (n) {
32293                 return [n.image, n];
32294             }));
32295             return image$.pipe(operators_1.takeUntil(hasTexture$.pipe(operators_1.filter(function (hasTexture) {
32296                 return hasTexture;
32297             }))), operators_1.catchError(function (error, caught) {
32298                 console.error("Failed to fetch high res image (" + node.key + ")", error);
32299                 return rxjs_1.empty();
32300             }));
32301         })).pipe(operators_1.publish(), operators_1.refCount());
32302         this._updateBackgroundSubscription = nodeImage$.pipe(operators_1.withLatestFrom(textureProvider$))
32303             .subscribe(function (args) {
32304             if (args[0][1].key !== args[1].key ||
32305                 args[1].disposed) {
32306                 return;
32307             }
32308             args[1].updateBackground(args[0][0]);
32309         });
32310         this._updateTextureImageSubscription = nodeImage$.pipe(operators_1.map(function (imn) {
32311             return function (renderer) {
32312                 renderer.updateTextureImage(imn[0], imn[1]);
32313                 return renderer;
32314             };
32315         }))
32316             .subscribe(this._rendererOperation$);
32317         this._clearPeripheryPlaneSubscription = this._navigator.panService.panNodes$.pipe(operators_1.filter(function (panNodes) {
32318             return panNodes.length === 0;
32319         }), operators_1.map(function () {
32320             return function (renderer) {
32321                 renderer.clearPeripheryPlanes();
32322                 return renderer;
32323             };
32324         }))
32325             .subscribe(this._rendererOperation$);
32326         var cachedPanNodes$ = this._navigator.panService.panNodes$.pipe(operators_1.switchMap(function (nts) {
32327             return rxjs_1.from(nts).pipe(operators_1.mergeMap(function (_a) {
32328                 var n = _a[0], t = _a[1];
32329                 return rxjs_1.combineLatest(_this._navigator.graphService.cacheNode$(n.key).pipe(operators_1.catchError(function (error) {
32330                     console.error("Failed to cache periphery node (" + n.key + ")", error);
32331                     return rxjs_1.empty();
32332                 })), rxjs_1.of(t));
32333             }));
32334         }), operators_1.share());
32335         this._addPeripheryPlaneSubscription = cachedPanNodes$.pipe(operators_1.map(function (_a) {
32336             var n = _a[0], t = _a[1];
32337             return function (renderer) {
32338                 renderer.addPeripheryPlane(n, t);
32339                 return renderer;
32340             };
32341         }))
32342             .subscribe(this._rendererOperation$);
32343         this._updatePeripheryPlaneTextureSubscription = cachedPanNodes$.pipe(operators_1.mergeMap(function (_a) {
32344             var n = _a[0];
32345             return Viewer_1.ImageSize.Size2048 > Math.max(n.image.width, n.image.height) ?
32346                 n.cacheImage$(Viewer_1.ImageSize.Size2048).pipe(operators_1.catchError(function () {
32347                     return rxjs_1.empty();
32348                 })) :
32349                 rxjs_1.empty();
32350         }), operators_1.map(function (n) {
32351             return function (renderer) {
32352                 renderer.updateTextureImage(n.image, n);
32353                 return renderer;
32354             };
32355         }))
32356             .subscribe(this._rendererOperation$);
32357         var inTransition$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
32358             return frame.state.alpha < 1;
32359         }), operators_1.distinctUntilChanged());
32360         var panTrigger$ = rxjs_1.combineLatest(this._container.mouseService.active$, this._container.touchService.active$, this._navigator.stateService.inMotion$, inTransition$).pipe(operators_1.map(function (_a) {
32361             var mouseActive = _a[0], touchActive = _a[1], inMotion = _a[2], inTransition = _a[3];
32362             return !(mouseActive || touchActive || inMotion || inTransition);
32363         }), operators_1.filter(function (trigger) {
32364             return trigger;
32365         }));
32366         this._moveToPeripheryNodeSubscription = this._navigator.panService.panNodes$.pipe(operators_1.switchMap(function (nts) {
32367             return panTrigger$.pipe(operators_1.withLatestFrom(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentNode$, _this._navigator.stateService.currentTransform$), operators_1.mergeMap(function (_a) {
32368                 var renderCamera = _a[1], currentNode = _a[2], currentTransform = _a[3];
32369                 return rxjs_1.of([
32370                     renderCamera,
32371                     currentNode,
32372                     currentTransform,
32373                     nts,
32374                 ]);
32375             }));
32376         }), operators_1.switchMap(function (_a) {
32377             var camera = _a[0], cn = _a[1], ct = _a[2], nts = _a[3];
32378             var direction = camera.camera.lookat.clone().sub(camera.camera.position);
32379             var cd = new Spatial_1.default().viewingDirection(cn.rotation);
32380             var ca = cd.angleTo(direction);
32381             var closest = [ca, undefined];
32382             var basic = new ViewportCoords_1.default().viewportToBasic(0, 0, ct, camera.perspective);
32383             if (basic[0] >= 0 && basic[0] <= 1 && basic[1] >= 0 && basic[1] <= 1) {
32384                 closest[0] = Number.NEGATIVE_INFINITY;
32385             }
32386             for (var _i = 0, nts_1 = nts; _i < nts_1.length; _i++) {
32387                 var n = nts_1[_i][0];
32388                 var d = new Spatial_1.default().viewingDirection(n.rotation);
32389                 var a = d.angleTo(direction);
32390                 if (a < closest[0]) {
32391                     closest[0] = a;
32392                     closest[1] = n.key;
32393                 }
32394             }
32395             if (!closest[1]) {
32396                 return rxjs_1.empty();
32397             }
32398             return _this._navigator.moveToKey$(closest[1]).pipe(operators_1.catchError(function () {
32399                 return rxjs_1.empty();
32400             }));
32401         }))
32402             .subscribe();
32403     };
32404     ImagePlaneComponent.prototype._deactivate = function () {
32405         this._rendererDisposer$.next(null);
32406         this._abortTextureProviderSubscription.unsubscribe();
32407         this._hasTextureSubscription.unsubscribe();
32408         this._rendererSubscription.unsubscribe();
32409         this._setRegionOfInterestSubscription.unsubscribe();
32410         this._setTextureProviderSubscription.unsubscribe();
32411         this._setTileSizeSubscription.unsubscribe();
32412         this._stateSubscription.unsubscribe();
32413         this._textureProviderSubscription.unsubscribe();
32414         this._updateBackgroundSubscription.unsubscribe();
32415         this._updateTextureImageSubscription.unsubscribe();
32416         this._clearPeripheryPlaneSubscription.unsubscribe();
32417         this._addPeripheryPlaneSubscription.unsubscribe();
32418         this._updatePeripheryPlaneTextureSubscription.unsubscribe();
32419         this._moveToPeripheryNodeSubscription.unsubscribe();
32420     };
32421     ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
32422         return {};
32423     };
32424     ImagePlaneComponent.componentName = "imagePlane";
32425     return ImagePlaneComponent;
32426 }(Component_1.Component));
32427 exports.ImagePlaneComponent = ImagePlaneComponent;
32428 Component_1.ComponentService.register(ImagePlaneComponent);
32429 exports.default = ImagePlaneComponent;
32430
32431 },{"../../Component":291,"../../Render":297,"../../Tiles":300,"../../Utils":301,"../../Viewer":302,"../../geo/Spatial":412,"../../geo/ViewportCoords":414,"rxjs":43,"rxjs/operators":241}],322:[function(require,module,exports){
32432 "use strict";
32433 Object.defineProperty(exports, "__esModule", { value: true });
32434 var Component_1 = require("../../Component");
32435 var ImagePlaneGLRenderer = /** @class */ (function () {
32436     function ImagePlaneGLRenderer() {
32437         this._factory = new Component_1.MeshFactory();
32438         this._scene = new Component_1.MeshScene();
32439         this._alpha = 0;
32440         this._alphaOld = 0;
32441         this._fadeOutSpeed = 0.05;
32442         this._currentKey = null;
32443         this._previousKey = null;
32444         this._providerDisposers = {};
32445         this._frameId = 0;
32446         this._needsRender = false;
32447     }
32448     Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
32449         get: function () {
32450             return this._frameId;
32451         },
32452         enumerable: true,
32453         configurable: true
32454     });
32455     Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
32456         get: function () {
32457             return this._needsRender;
32458         },
32459         enumerable: true,
32460         configurable: true
32461     });
32462     ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
32463         this._needsRender = true;
32464     };
32465     ImagePlaneGLRenderer.prototype.addPeripheryPlane = function (node, transform) {
32466         var mesh = this._factory.createMesh(node, transform);
32467         var planes = {};
32468         planes[node.key] = mesh;
32469         this._scene.addPeripheryPlanes(planes);
32470         this._needsRender = true;
32471     };
32472     ImagePlaneGLRenderer.prototype.clearPeripheryPlanes = function () {
32473         this._scene.setPeripheryPlanes({});
32474         this._needsRender = true;
32475     };
32476     ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
32477         this._updateFrameId(frame.id);
32478         this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
32479         this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
32480         this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
32481     };
32482     ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
32483         var _this = this;
32484         if (key !== this._currentKey) {
32485             return;
32486         }
32487         var createdSubscription = provider.textureCreated$
32488             .subscribe(function (texture) {
32489             _this._updateTexture(texture);
32490         });
32491         var updatedSubscription = provider.textureUpdated$
32492             .subscribe(function (updated) {
32493             _this._needsRender = true;
32494         });
32495         var dispose = function () {
32496             createdSubscription.unsubscribe();
32497             updatedSubscription.unsubscribe();
32498             provider.dispose();
32499         };
32500         if (key in this._providerDisposers) {
32501             var disposeProvider = this._providerDisposers[key];
32502             disposeProvider();
32503             delete this._providerDisposers[key];
32504         }
32505         this._providerDisposers[key] = dispose;
32506     };
32507     ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
32508         this._needsRender = true;
32509         var planes = this._extend({}, this._scene.planes, this._scene.planesOld, this._scene.planesPeriphery);
32510         for (var key in planes) {
32511             if (!planes.hasOwnProperty(key)) {
32512                 continue;
32513             }
32514             if (key !== node.key) {
32515                 continue;
32516             }
32517             var plane = planes[key];
32518             var material = plane.material;
32519             var texture = material.uniforms.projectorTex.value;
32520             texture.image = image;
32521             texture.needsUpdate = true;
32522         }
32523     };
32524     ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
32525         var planes = this._scene.planes;
32526         var planesOld = this._scene.planesOld;
32527         var planesPeriphery = this._scene.planesPeriphery;
32528         var planeAlpha = Object.keys(planesOld).length ? 1 : this._alpha;
32529         var peripheryAlpha = Object.keys(planesOld).length ? 1 : Math.floor(this._alpha);
32530         for (var key in planes) {
32531             if (!planes.hasOwnProperty(key)) {
32532                 continue;
32533             }
32534             var plane = planes[key];
32535             plane.material.uniforms.opacity.value = planeAlpha;
32536         }
32537         for (var key in planesOld) {
32538             if (!planesOld.hasOwnProperty(key)) {
32539                 continue;
32540             }
32541             var plane = planesOld[key];
32542             plane.material.uniforms.opacity.value = this._alphaOld;
32543         }
32544         for (var key in planesPeriphery) {
32545             if (!planesPeriphery.hasOwnProperty(key)) {
32546                 continue;
32547             }
32548             var plane = planesPeriphery[key];
32549             plane.material.uniforms.opacity.value = peripheryAlpha;
32550         }
32551         renderer.render(this._scene.scenePeriphery, perspectiveCamera);
32552         renderer.render(this._scene.scene, perspectiveCamera);
32553         renderer.render(this._scene.sceneOld, perspectiveCamera);
32554         for (var key in planes) {
32555             if (!planes.hasOwnProperty(key)) {
32556                 continue;
32557             }
32558             var plane = planes[key];
32559             plane.material.uniforms.opacity.value = this._alpha;
32560         }
32561         renderer.render(this._scene.scene, perspectiveCamera);
32562     };
32563     ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
32564         this._needsRender = false;
32565     };
32566     ImagePlaneGLRenderer.prototype.dispose = function () {
32567         this._scene.clear();
32568     };
32569     ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
32570         this._frameId = frameId;
32571     };
32572     ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
32573         if (alpha === this._alpha) {
32574             return false;
32575         }
32576         this._alpha = alpha;
32577         return true;
32578     };
32579     ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
32580         if (alpha < 1 || this._alphaOld === 0) {
32581             return false;
32582         }
32583         this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
32584         return true;
32585     };
32586     ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
32587         if (state.currentNode == null || state.currentNode.key === this._currentKey) {
32588             return false;
32589         }
32590         var previousKey = state.previousNode != null ? state.previousNode.key : null;
32591         var currentKey = state.currentNode.key;
32592         if (this._previousKey !== previousKey &&
32593             this._previousKey !== currentKey &&
32594             this._previousKey in this._providerDisposers) {
32595             var disposeProvider = this._providerDisposers[this._previousKey];
32596             disposeProvider();
32597             delete this._providerDisposers[this._previousKey];
32598         }
32599         if (previousKey != null) {
32600             if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
32601                 var previousMesh = this._factory.createMesh(state.previousNode, state.previousTransform);
32602                 var previousPlanes = {};
32603                 previousPlanes[previousKey] = previousMesh;
32604                 this._scene.updateImagePlanes(previousPlanes);
32605             }
32606             this._previousKey = previousKey;
32607         }
32608         this._currentKey = currentKey;
32609         var currentMesh = this._factory.createMesh(state.currentNode, state.currentTransform);
32610         var planes = {};
32611         planes[currentKey] = currentMesh;
32612         this._scene.updateImagePlanes(planes);
32613         this._alphaOld = 1;
32614         return true;
32615     };
32616     ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
32617         this._needsRender = true;
32618         var planes = this._scene.planes;
32619         for (var key in planes) {
32620             if (!planes.hasOwnProperty(key)) {
32621                 continue;
32622             }
32623             var plane = planes[key];
32624             var material = plane.material;
32625             var oldTexture = material.uniforms.projectorTex.value;
32626             material.uniforms.projectorTex.value = null;
32627             oldTexture.dispose();
32628             material.uniforms.projectorTex.value = texture;
32629         }
32630     };
32631     ImagePlaneGLRenderer.prototype._extend = function (dest) {
32632         var sources = [];
32633         for (var _i = 1; _i < arguments.length; _i++) {
32634             sources[_i - 1] = arguments[_i];
32635         }
32636         for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
32637             var src = sources_1[_a];
32638             for (var k in src) {
32639                 if (!src.hasOwnProperty(k)) {
32640                     continue;
32641                 }
32642                 dest[k] = src[k];
32643             }
32644         }
32645         return dest;
32646     };
32647     return ImagePlaneGLRenderer;
32648 }());
32649 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
32650 exports.default = ImagePlaneGLRenderer;
32651
32652 },{"../../Component":291}],323:[function(require,module,exports){
32653 "use strict";
32654 Object.defineProperty(exports, "__esModule", { value: true });
32655 var CoverState;
32656 (function (CoverState) {
32657     CoverState[CoverState["Hidden"] = 0] = "Hidden";
32658     CoverState[CoverState["Loading"] = 1] = "Loading";
32659     CoverState[CoverState["Visible"] = 2] = "Visible";
32660 })(CoverState = exports.CoverState || (exports.CoverState = {}));
32661
32662 },{}],324:[function(require,module,exports){
32663 "use strict";
32664 Object.defineProperty(exports, "__esModule", { value: true });
32665 /**
32666  * Enumeration for slider mode.
32667  *
32668  * @enum {number}
32669  * @readonly
32670  *
32671  * @description Modes for specifying how transitions
32672  * between nodes are performed in slider mode. Only
32673  * applicable when the slider component determines
32674  * that transitions with motion is possilble. When it
32675  * is not, the stationary mode will be applied.
32676  */
32677 var SliderMode;
32678 (function (SliderMode) {
32679     /**
32680      * Transitions with motion.
32681      *
32682      * @description The slider component moves the
32683      * camera between the node origins.
32684      *
32685      * In this mode it is not possible to zoom or pan.
32686      *
32687      * The slider component falls back to stationary
32688      * mode when it determines that the pair of nodes
32689      * does not have a strong enough relation.
32690      */
32691     SliderMode[SliderMode["Motion"] = 0] = "Motion";
32692     /**
32693      * Stationary transitions.
32694      *
32695      * @description The camera is stationary.
32696      *
32697      * In this mode it is possible to zoom and pan.
32698      */
32699     SliderMode[SliderMode["Stationary"] = 1] = "Stationary";
32700 })(SliderMode = exports.SliderMode || (exports.SliderMode = {}));
32701
32702 },{}],325:[function(require,module,exports){
32703 "use strict";
32704 Object.defineProperty(exports, "__esModule", { value: true });
32705 var ICoverConfiguration_1 = require("./ICoverConfiguration");
32706 exports.CoverState = ICoverConfiguration_1.CoverState;
32707 var ISliderConfiguration_1 = require("./ISliderConfiguration");
32708 exports.SliderMode = ISliderConfiguration_1.SliderMode;
32709
32710 },{"./ICoverConfiguration":323,"./ISliderConfiguration":324}],326:[function(require,module,exports){
32711 "use strict";
32712 var __extends = (this && this.__extends) || (function () {
32713     var extendStatics = function (d, b) {
32714         extendStatics = Object.setPrototypeOf ||
32715             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32716             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32717         return extendStatics(d, b);
32718     }
32719     return function (d, b) {
32720         extendStatics(d, b);
32721         function __() { this.constructor = d; }
32722         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32723     };
32724 })();
32725 Object.defineProperty(exports, "__esModule", { value: true });
32726 var operators_1 = require("rxjs/operators");
32727 var Component_1 = require("../../Component");
32728 var Edge_1 = require("../../Edge");
32729 /**
32730  * The `KeyPlayHandler` allows the user to control the play behavior
32731  * using the following key commands:
32732  *
32733  * `Spacebar`: Start or stop playing.
32734  * `SHIFT` + `D`: Switch direction.
32735  * `<`: Decrease speed.
32736  * `>`: Increase speed.
32737  *
32738  * @example
32739  * ```
32740  * var keyboardComponent = viewer.getComponent("keyboard");
32741  *
32742  * keyboardComponent.keyPlay.disable();
32743  * keyboardComponent.keyPlay.enable();
32744  *
32745  * var isEnabled = keyboardComponent.keyPlay.isEnabled;
32746  * ```
32747  */
32748 var KeyPlayHandler = /** @class */ (function (_super) {
32749     __extends(KeyPlayHandler, _super);
32750     function KeyPlayHandler() {
32751         return _super !== null && _super.apply(this, arguments) || this;
32752     }
32753     KeyPlayHandler.prototype._enable = function () {
32754         var _this = this;
32755         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) {
32756             return node.sequenceEdges$;
32757         }))))
32758             .subscribe(function (_a) {
32759             var event = _a[0], playing = _a[1], direction = _a[2], speed = _a[3], status = _a[4];
32760             if (event.altKey || event.ctrlKey || event.metaKey) {
32761                 return;
32762             }
32763             switch (event.key) {
32764                 case "D":
32765                     if (!event.shiftKey) {
32766                         return;
32767                     }
32768                     var newDirection = playing ?
32769                         null : direction === Edge_1.EdgeDirection.Next ?
32770                         Edge_1.EdgeDirection.Prev : direction === Edge_1.EdgeDirection.Prev ?
32771                         Edge_1.EdgeDirection.Next : null;
32772                     if (newDirection != null) {
32773                         _this._navigator.playService.setDirection(newDirection);
32774                     }
32775                     break;
32776                 case " ":
32777                     if (event.shiftKey) {
32778                         return;
32779                     }
32780                     if (playing) {
32781                         _this._navigator.playService.stop();
32782                     }
32783                     else {
32784                         for (var _i = 0, _b = status.edges; _i < _b.length; _i++) {
32785                             var edge = _b[_i];
32786                             if (edge.data.direction === direction) {
32787                                 _this._navigator.playService.play();
32788                             }
32789                         }
32790                     }
32791                     break;
32792                 case "<":
32793                     _this._navigator.playService.setSpeed(speed - 0.05);
32794                     break;
32795                 case ">":
32796                     _this._navigator.playService.setSpeed(speed + 0.05);
32797                     break;
32798                 default:
32799                     return;
32800             }
32801             event.preventDefault();
32802         });
32803     };
32804     KeyPlayHandler.prototype._disable = function () {
32805         this._keyDownSubscription.unsubscribe();
32806     };
32807     KeyPlayHandler.prototype._getConfiguration = function (enable) {
32808         return { keyZoom: enable };
32809     };
32810     return KeyPlayHandler;
32811 }(Component_1.HandlerBase));
32812 exports.KeyPlayHandler = KeyPlayHandler;
32813 exports.default = KeyPlayHandler;
32814
32815 },{"../../Component":291,"../../Edge":292,"rxjs/operators":241}],327:[function(require,module,exports){
32816 "use strict";
32817 var __extends = (this && this.__extends) || (function () {
32818     var extendStatics = function (d, b) {
32819         extendStatics = Object.setPrototypeOf ||
32820             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32821             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32822         return extendStatics(d, b);
32823     }
32824     return function (d, b) {
32825         extendStatics(d, b);
32826         function __() { this.constructor = d; }
32827         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32828     };
32829 })();
32830 Object.defineProperty(exports, "__esModule", { value: true });
32831 var operators_1 = require("rxjs/operators");
32832 var Component_1 = require("../../Component");
32833 var Edge_1 = require("../../Edge");
32834 var Error_1 = require("../../Error");
32835 /**
32836  * The `KeySequenceNavigationHandler` allows the user to navigate through a sequence using the
32837  * following key commands:
32838  *
32839  * `ALT` + `Up Arrow`: Navigate to next image in the sequence.
32840  * `ALT` + `Down Arrow`: Navigate to previous image in sequence.
32841  *
32842  * @example
32843  * ```
32844  * var keyboardComponent = viewer.getComponent("keyboard");
32845  *
32846  * keyboardComponent.keySequenceNavigation.disable();
32847  * keyboardComponent.keySequenceNavigation.enable();
32848  *
32849  * var isEnabled = keyboardComponent.keySequenceNavigation.isEnabled;
32850  * ```
32851  */
32852 var KeySequenceNavigationHandler = /** @class */ (function (_super) {
32853     __extends(KeySequenceNavigationHandler, _super);
32854     function KeySequenceNavigationHandler() {
32855         return _super !== null && _super.apply(this, arguments) || this;
32856     }
32857     KeySequenceNavigationHandler.prototype._enable = function () {
32858         var _this = this;
32859         var sequenceEdges$ = this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
32860             return node.sequenceEdges$;
32861         }));
32862         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(sequenceEdges$))
32863             .subscribe(function (_a) {
32864             var event = _a[0], edgeStatus = _a[1];
32865             var direction = null;
32866             switch (event.keyCode) {
32867                 case 38: // up
32868                     direction = Edge_1.EdgeDirection.Next;
32869                     break;
32870                 case 40: // down
32871                     direction = Edge_1.EdgeDirection.Prev;
32872                     break;
32873                 default:
32874                     return;
32875             }
32876             event.preventDefault();
32877             if (!event.altKey || event.shiftKey || !edgeStatus.cached) {
32878                 return;
32879             }
32880             for (var _i = 0, _b = edgeStatus.edges; _i < _b.length; _i++) {
32881                 var edge = _b[_i];
32882                 if (edge.data.direction === direction) {
32883                     _this._navigator.moveToKey$(edge.to)
32884                         .subscribe(undefined, function (error) {
32885                         if (!(error instanceof Error_1.AbortMapillaryError)) {
32886                             console.error(error);
32887                         }
32888                     });
32889                     return;
32890                 }
32891             }
32892         });
32893     };
32894     KeySequenceNavigationHandler.prototype._disable = function () {
32895         this._keyDownSubscription.unsubscribe();
32896     };
32897     KeySequenceNavigationHandler.prototype._getConfiguration = function (enable) {
32898         return { keySequenceNavigation: enable };
32899     };
32900     return KeySequenceNavigationHandler;
32901 }(Component_1.HandlerBase));
32902 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler;
32903 exports.default = KeySequenceNavigationHandler;
32904
32905 },{"../../Component":291,"../../Edge":292,"../../Error":293,"rxjs/operators":241}],328:[function(require,module,exports){
32906 "use strict";
32907 var __extends = (this && this.__extends) || (function () {
32908     var extendStatics = function (d, b) {
32909         extendStatics = Object.setPrototypeOf ||
32910             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32911             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32912         return extendStatics(d, b);
32913     }
32914     return function (d, b) {
32915         extendStatics(d, b);
32916         function __() { this.constructor = d; }
32917         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32918     };
32919 })();
32920 Object.defineProperty(exports, "__esModule", { value: true });
32921 var operators_1 = require("rxjs/operators");
32922 var Component_1 = require("../../Component");
32923 var Edge_1 = require("../../Edge");
32924 var Error_1 = require("../../Error");
32925 /**
32926  * The `KeySpatialNavigationHandler` allows the user to navigate through a sequence using the
32927  * following key commands:
32928  *
32929  * `Up Arrow`: Step forward.
32930  * `Down Arrow`: Step backward.
32931  * `Left Arrow`: Step to the left.
32932  * `Rigth Arrow`: Step to the right.
32933  * `SHIFT` + `Down Arrow`: Turn around.
32934  * `SHIFT` + `Left Arrow`: Turn to the left.
32935  * `SHIFT` + `Rigth Arrow`: Turn to the right.
32936  *
32937  * @example
32938  * ```
32939  * var keyboardComponent = viewer.getComponent("keyboard");
32940  *
32941  * keyboardComponent.keySpatialNavigation.disable();
32942  * keyboardComponent.keySpatialNavigation.enable();
32943  *
32944  * var isEnabled = keyboardComponent.keySpatialNavigation.isEnabled;
32945  * ```
32946  */
32947 var KeySpatialNavigationHandler = /** @class */ (function (_super) {
32948     __extends(KeySpatialNavigationHandler, _super);
32949     /** @ignore */
32950     function KeySpatialNavigationHandler(component, container, navigator, spatial) {
32951         var _this = _super.call(this, component, container, navigator) || this;
32952         _this._spatial = spatial;
32953         return _this;
32954     }
32955     KeySpatialNavigationHandler.prototype._enable = function () {
32956         var _this = this;
32957         var spatialEdges$ = this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
32958             return node.spatialEdges$;
32959         }));
32960         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(spatialEdges$, this._navigator.stateService.currentState$))
32961             .subscribe(function (_a) {
32962             var event = _a[0], edgeStatus = _a[1], frame = _a[2];
32963             var pano = frame.state.currentNode.pano;
32964             var direction = null;
32965             switch (event.keyCode) {
32966                 case 37: // left
32967                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
32968                     break;
32969                 case 38: // up
32970                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
32971                     break;
32972                 case 39: // right
32973                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
32974                     break;
32975                 case 40: // down
32976                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
32977                     break;
32978                 default:
32979                     return;
32980             }
32981             event.preventDefault();
32982             if (event.altKey || !edgeStatus.cached ||
32983                 (event.shiftKey && pano)) {
32984                 return;
32985             }
32986             if (!pano) {
32987                 _this._moveDir(direction, edgeStatus);
32988             }
32989             else {
32990                 var shifts = {};
32991                 shifts[Edge_1.EdgeDirection.StepBackward] = Math.PI;
32992                 shifts[Edge_1.EdgeDirection.StepForward] = 0;
32993                 shifts[Edge_1.EdgeDirection.StepLeft] = Math.PI / 2;
32994                 shifts[Edge_1.EdgeDirection.StepRight] = -Math.PI / 2;
32995                 var phi = _this._rotationFromCamera(frame.state.camera).phi;
32996                 var navigationAngle = _this._spatial.wrapAngle(phi + shifts[direction]);
32997                 var threshold = Math.PI / 4;
32998                 var edges = edgeStatus.edges.filter(function (e) {
32999                     return e.data.direction === Edge_1.EdgeDirection.Pano || e.data.direction === direction;
33000                 });
33001                 var smallestAngle = Number.MAX_VALUE;
33002                 var toKey = null;
33003                 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
33004                     var edge = edges_1[_i];
33005                     var angle = Math.abs(_this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
33006                     if (angle < Math.min(smallestAngle, threshold)) {
33007                         smallestAngle = angle;
33008                         toKey = edge.to;
33009                     }
33010                 }
33011                 if (toKey == null) {
33012                     return;
33013                 }
33014                 _this._moveToKey(toKey);
33015             }
33016         });
33017     };
33018     KeySpatialNavigationHandler.prototype._disable = function () {
33019         this._keyDownSubscription.unsubscribe();
33020     };
33021     KeySpatialNavigationHandler.prototype._getConfiguration = function (enable) {
33022         return { keySpatialNavigation: enable };
33023     };
33024     KeySpatialNavigationHandler.prototype._moveDir = function (direction, edgeStatus) {
33025         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
33026             var edge = _a[_i];
33027             if (edge.data.direction === direction) {
33028                 this._moveToKey(edge.to);
33029                 return;
33030             }
33031         }
33032     };
33033     KeySpatialNavigationHandler.prototype._moveToKey = function (key) {
33034         this._navigator.moveToKey$(key)
33035             .subscribe(undefined, function (error) {
33036             if (!(error instanceof Error_1.AbortMapillaryError)) {
33037                 console.error(error);
33038             }
33039         });
33040     };
33041     KeySpatialNavigationHandler.prototype._rotationFromCamera = function (camera) {
33042         var direction = camera.lookat.clone().sub(camera.position);
33043         var upProjection = direction.clone().dot(camera.up);
33044         var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
33045         var phi = Math.atan2(planeProjection.y, planeProjection.x);
33046         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
33047         return { phi: phi, theta: theta };
33048     };
33049     return KeySpatialNavigationHandler;
33050 }(Component_1.HandlerBase));
33051 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler;
33052 exports.default = KeySpatialNavigationHandler;
33053
33054 },{"../../Component":291,"../../Edge":292,"../../Error":293,"rxjs/operators":241}],329:[function(require,module,exports){
33055 "use strict";
33056 var __extends = (this && this.__extends) || (function () {
33057     var extendStatics = function (d, b) {
33058         extendStatics = Object.setPrototypeOf ||
33059             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33060             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33061         return extendStatics(d, b);
33062     }
33063     return function (d, b) {
33064         extendStatics(d, b);
33065         function __() { this.constructor = d; }
33066         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33067     };
33068 })();
33069 Object.defineProperty(exports, "__esModule", { value: true });
33070 var operators_1 = require("rxjs/operators");
33071 var Component_1 = require("../../Component");
33072 /**
33073  * The `KeyZoomHandler` allows the user to zoom in and out using the
33074  * following key commands:
33075  *
33076  * `+`: Zoom in.
33077  * `-`: Zoom out.
33078  *
33079  * @example
33080  * ```
33081  * var keyboardComponent = viewer.getComponent("keyboard");
33082  *
33083  * keyboardComponent.keyZoom.disable();
33084  * keyboardComponent.keyZoom.enable();
33085  *
33086  * var isEnabled = keyboardComponent.keyZoom.isEnabled;
33087  * ```
33088  */
33089 var KeyZoomHandler = /** @class */ (function (_super) {
33090     __extends(KeyZoomHandler, _super);
33091     /** @ignore */
33092     function KeyZoomHandler(component, container, navigator, viewportCoords) {
33093         var _this = _super.call(this, component, container, navigator) || this;
33094         _this._viewportCoords = viewportCoords;
33095         return _this;
33096     }
33097     KeyZoomHandler.prototype._enable = function () {
33098         var _this = this;
33099         this._keyDownSubscription = this._container.keyboardService.keyDown$.pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
33100             .subscribe(function (_a) {
33101             var event = _a[0], render = _a[1], transform = _a[2];
33102             if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
33103                 return;
33104             }
33105             var delta = 0;
33106             switch (event.key) {
33107                 case "+":
33108                     delta = 1;
33109                     break;
33110                 case "-":
33111                     delta = -1;
33112                     break;
33113                 default:
33114                     return;
33115             }
33116             event.preventDefault();
33117             var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
33118             var reference = transform.projectBasic(unprojected.toArray());
33119             _this._navigator.stateService.zoomIn(delta, reference);
33120         });
33121     };
33122     KeyZoomHandler.prototype._disable = function () {
33123         this._keyDownSubscription.unsubscribe();
33124     };
33125     KeyZoomHandler.prototype._getConfiguration = function (enable) {
33126         return { keyZoom: enable };
33127     };
33128     return KeyZoomHandler;
33129 }(Component_1.HandlerBase));
33130 exports.KeyZoomHandler = KeyZoomHandler;
33131 exports.default = KeyZoomHandler;
33132
33133 },{"../../Component":291,"rxjs/operators":241}],330:[function(require,module,exports){
33134 "use strict";
33135 var __extends = (this && this.__extends) || (function () {
33136     var extendStatics = function (d, b) {
33137         extendStatics = Object.setPrototypeOf ||
33138             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33139             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33140         return extendStatics(d, b);
33141     }
33142     return function (d, b) {
33143         extendStatics(d, b);
33144         function __() { this.constructor = d; }
33145         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33146     };
33147 })();
33148 Object.defineProperty(exports, "__esModule", { value: true });
33149 var Component_1 = require("../../Component");
33150 var Geo_1 = require("../../Geo");
33151 /**
33152  * @class KeyboardComponent
33153  *
33154  * @classdesc Component for keyboard event handling.
33155  *
33156  * To retrive and use the keyboard component
33157  *
33158  * @example
33159  * ```
33160  * var viewer = new Mapillary.Viewer(
33161  *     "<element-id>",
33162  *     "<client-id>",
33163  *     "<my key>");
33164  *
33165  * var keyboardComponent = viewer.getComponent("keyboard");
33166  * ```
33167  */
33168 var KeyboardComponent = /** @class */ (function (_super) {
33169     __extends(KeyboardComponent, _super);
33170     /** @ignore */
33171     function KeyboardComponent(name, container, navigator) {
33172         var _this = _super.call(this, name, container, navigator) || this;
33173         _this._keyPlayHandler = new Component_1.KeyPlayHandler(_this, container, navigator);
33174         _this._keySequenceNavigationHandler = new Component_1.KeySequenceNavigationHandler(_this, container, navigator);
33175         _this._keySpatialNavigationHandler = new Component_1.KeySpatialNavigationHandler(_this, container, navigator, new Geo_1.Spatial());
33176         _this._keyZoomHandler = new Component_1.KeyZoomHandler(_this, container, navigator, new Geo_1.ViewportCoords());
33177         return _this;
33178     }
33179     Object.defineProperty(KeyboardComponent.prototype, "keyPlay", {
33180         /**
33181          * Get key play.
33182          *
33183          * @returns {KeyPlayHandler} The key play handler.
33184          */
33185         get: function () {
33186             return this._keyPlayHandler;
33187         },
33188         enumerable: true,
33189         configurable: true
33190     });
33191     Object.defineProperty(KeyboardComponent.prototype, "keySequenceNavigation", {
33192         /**
33193          * Get key sequence navigation.
33194          *
33195          * @returns {KeySequenceNavigationHandler} The key sequence navigation handler.
33196          */
33197         get: function () {
33198             return this._keySequenceNavigationHandler;
33199         },
33200         enumerable: true,
33201         configurable: true
33202     });
33203     Object.defineProperty(KeyboardComponent.prototype, "keySpatialNavigation", {
33204         /**
33205          * Get spatial.
33206          *
33207          * @returns {KeySpatialNavigationHandler} The spatial handler.
33208          */
33209         get: function () {
33210             return this._keySpatialNavigationHandler;
33211         },
33212         enumerable: true,
33213         configurable: true
33214     });
33215     Object.defineProperty(KeyboardComponent.prototype, "keyZoom", {
33216         /**
33217          * Get key zoom.
33218          *
33219          * @returns {KeyZoomHandler} The key zoom handler.
33220          */
33221         get: function () {
33222             return this._keyZoomHandler;
33223         },
33224         enumerable: true,
33225         configurable: true
33226     });
33227     KeyboardComponent.prototype._activate = function () {
33228         var _this = this;
33229         this._configurationSubscription = this._configuration$
33230             .subscribe(function (configuration) {
33231             if (configuration.keyPlay) {
33232                 _this._keyPlayHandler.enable();
33233             }
33234             else {
33235                 _this._keyPlayHandler.disable();
33236             }
33237             if (configuration.keySequenceNavigation) {
33238                 _this._keySequenceNavigationHandler.enable();
33239             }
33240             else {
33241                 _this._keySequenceNavigationHandler.disable();
33242             }
33243             if (configuration.keySpatialNavigation) {
33244                 _this._keySpatialNavigationHandler.enable();
33245             }
33246             else {
33247                 _this._keySpatialNavigationHandler.disable();
33248             }
33249             if (configuration.keyZoom) {
33250                 _this._keyZoomHandler.enable();
33251             }
33252             else {
33253                 _this._keyZoomHandler.disable();
33254             }
33255         });
33256     };
33257     KeyboardComponent.prototype._deactivate = function () {
33258         this._configurationSubscription.unsubscribe();
33259         this._keyPlayHandler.disable();
33260         this._keySequenceNavigationHandler.disable();
33261         this._keySpatialNavigationHandler.disable();
33262         this._keyZoomHandler.disable();
33263     };
33264     KeyboardComponent.prototype._getDefaultConfiguration = function () {
33265         return { keyPlay: true, keySequenceNavigation: true, keySpatialNavigation: true, keyZoom: true };
33266     };
33267     KeyboardComponent.componentName = "keyboard";
33268     return KeyboardComponent;
33269 }(Component_1.Component));
33270 exports.KeyboardComponent = KeyboardComponent;
33271 Component_1.ComponentService.register(KeyboardComponent);
33272 exports.default = KeyboardComponent;
33273
33274 },{"../../Component":291,"../../Geo":294}],331:[function(require,module,exports){
33275 "use strict";
33276 Object.defineProperty(exports, "__esModule", { value: true });
33277 var MarkerComponent_1 = require("./MarkerComponent");
33278 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
33279 var SimpleMarker_1 = require("./marker/SimpleMarker");
33280 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
33281 var CircleMarker_1 = require("./marker/CircleMarker");
33282 exports.CircleMarker = CircleMarker_1.CircleMarker;
33283
33284 },{"./MarkerComponent":332,"./marker/CircleMarker":335,"./marker/SimpleMarker":337}],332:[function(require,module,exports){
33285 "use strict";
33286 var __extends = (this && this.__extends) || (function () {
33287     var extendStatics = function (d, b) {
33288         extendStatics = Object.setPrototypeOf ||
33289             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33290             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33291         return extendStatics(d, b);
33292     }
33293     return function (d, b) {
33294         extendStatics(d, b);
33295         function __() { this.constructor = d; }
33296         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33297     };
33298 })();
33299 Object.defineProperty(exports, "__esModule", { value: true });
33300 var rxjs_1 = require("rxjs");
33301 var operators_1 = require("rxjs/operators");
33302 var THREE = require("three");
33303 var when = require("when");
33304 var Component_1 = require("../../Component");
33305 var Render_1 = require("../../Render");
33306 var Graph_1 = require("../../Graph");
33307 var Geo_1 = require("../../Geo");
33308 /**
33309  * @class MarkerComponent
33310  *
33311  * @classdesc Component for showing and editing 3D marker objects.
33312  *
33313  * The `add` method is used for adding new markers or replacing
33314  * markers already in the set.
33315  *
33316  * If a marker already in the set has the same
33317  * id as one of the markers added, the old marker will be removed and
33318  * the added marker will take its place.
33319  *
33320  * It is not possible to update markers in the set by updating any properties
33321  * directly on the marker object. Markers need to be replaced by
33322  * re-adding them for updates to geographic position or configuration
33323  * to be reflected.
33324  *
33325  * Markers added to the marker component can be either interactive
33326  * or non-interactive. Different marker types define their behavior.
33327  * Markers with interaction support can be configured with options
33328  * to respond to dragging inside the viewer and be detected when
33329  * retrieving markers from pixel points with the `getMarkerIdAt` method.
33330  *
33331  * To retrive and use the marker component
33332  *
33333  * @example
33334  * ```
33335  * var viewer = new Mapillary.Viewer(
33336  *     "<element-id>",
33337  *     "<client-id>",
33338  *     "<my key>",
33339  *     { component: { marker: true } });
33340  *
33341  * var markerComponent = viewer.getComponent("marker");
33342  * ```
33343  */
33344 var MarkerComponent = /** @class */ (function (_super) {
33345     __extends(MarkerComponent, _super);
33346     /** @ignore */
33347     function MarkerComponent(name, container, navigator) {
33348         var _this = _super.call(this, name, container, navigator) || this;
33349         _this._relativeGroundAltitude = -2;
33350         _this._geoCoords = new Geo_1.GeoCoords();
33351         _this._graphCalculator = new Graph_1.GraphCalculator();
33352         _this._markerScene = new Component_1.MarkerScene();
33353         _this._markerSet = new Component_1.MarkerSet();
33354         _this._viewportCoords = new Geo_1.ViewportCoords();
33355         return _this;
33356     }
33357     /**
33358      * Add markers to the marker set or replace markers in the marker set.
33359      *
33360      * @description If a marker already in the set has the same
33361      * id as one of the markers added, the old marker will be removed
33362      * the added marker will take its place.
33363      *
33364      * Any marker inside the visible bounding bbox
33365      * will be initialized and placed in the viewer.
33366      *
33367      * @param {Array<Marker>} markers - Markers to add.
33368      *
33369      * @example ```markerComponent.add([marker1, marker2]);```
33370      */
33371     MarkerComponent.prototype.add = function (markers) {
33372         this._markerSet.add(markers);
33373     };
33374     /**
33375      * Returns the marker in the marker set with the specified id, or
33376      * undefined if the id matches no marker.
33377      *
33378      * @param {string} markerId - Id of the marker.
33379      *
33380      * @example ```var marker = markerComponent.get("markerId");```
33381      *
33382      */
33383     MarkerComponent.prototype.get = function (markerId) {
33384         return this._markerSet.get(markerId);
33385     };
33386     /**
33387      * Returns an array of all markers.
33388      *
33389      * @example ```var markers = markerComponent.getAll();```
33390      */
33391     MarkerComponent.prototype.getAll = function () {
33392         return this._markerSet.getAll();
33393     };
33394     /**
33395      * Returns the id of the interactive marker closest to the current camera
33396      * position at the specified point.
33397      *
33398      * @description Notice that the pixelPoint argument requires x, y
33399      * coordinates from pixel space.
33400      *
33401      * With this function, you can use the coordinates provided by mouse
33402      * events to get information out of the marker component.
33403      *
33404      * If no interactive geometry of an interactive marker exist at the pixel
33405      * point, `null` will be returned.
33406      *
33407      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
33408      * @returns {string} Id of the interactive marker closest to the camera. If no
33409      * interactive marker exist at the pixel point, `null` will be returned.
33410      *
33411      * @example
33412      * ```
33413      * markerComponent.getMarkerIdAt([100, 100])
33414      *     .then((markerId) => { console.log(markerId); });
33415      * ```
33416      */
33417     MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
33418         var _this = this;
33419         return when.promise(function (resolve, reject) {
33420             _this._container.renderService.renderCamera$.pipe(operators_1.first(), operators_1.map(function (render) {
33421                 var viewport = _this._viewportCoords
33422                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
33423                 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
33424                 return id;
33425             }))
33426                 .subscribe(function (id) {
33427                 resolve(id);
33428             }, function (error) {
33429                 reject(error);
33430             });
33431         });
33432     };
33433     /**
33434      * Check if a marker exist in the marker set.
33435      *
33436      * @param {string} markerId - Id of the marker.
33437      *
33438      * @example ```var markerExists = markerComponent.has("markerId");```
33439      */
33440     MarkerComponent.prototype.has = function (markerId) {
33441         return this._markerSet.has(markerId);
33442     };
33443     /**
33444      * Remove markers with the specified ids from the marker set.
33445      *
33446      * @param {Array<string>} markerIds - Ids for markers to remove.
33447      *
33448      * @example ```markerComponent.remove(["id-1", "id-2"]);```
33449      */
33450     MarkerComponent.prototype.remove = function (markerIds) {
33451         this._markerSet.remove(markerIds);
33452     };
33453     /**
33454      * Remove all markers from the marker set.
33455      *
33456      * @example ```markerComponent.removeAll();```
33457      */
33458     MarkerComponent.prototype.removeAll = function () {
33459         this._markerSet.removeAll();
33460     };
33461     MarkerComponent.prototype._activate = function () {
33462         var _this = this;
33463         var groundAltitude$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
33464             return frame.state.camera.position.z + _this._relativeGroundAltitude;
33465         }), operators_1.distinctUntilChanged(function (a1, a2) {
33466             return Math.abs(a1 - a2) < 0.01;
33467         }), operators_1.publishReplay(1), operators_1.refCount());
33468         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());
33469         var clampedConfiguration$ = this._configuration$.pipe(operators_1.map(function (configuration) {
33470             return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
33471         }));
33472         var currentlatLon$ = this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) { return node.latLon; }), operators_1.publishReplay(1), operators_1.refCount());
33473         var visibleBBox$ = rxjs_1.combineLatest(clampedConfiguration$, currentlatLon$).pipe(operators_1.map(function (_a) {
33474             var configuration = _a[0], latLon = _a[1];
33475             return _this._graphCalculator
33476                 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
33477         }), operators_1.publishReplay(1), operators_1.refCount());
33478         var visibleMarkers$ = rxjs_1.combineLatest(rxjs_1.concat(rxjs_1.of(this._markerSet), this._markerSet.changed$), visibleBBox$).pipe(operators_1.map(function (_a) {
33479             var set = _a[0], bbox = _a[1];
33480             return set.search(bbox);
33481         }));
33482         this._setChangedSubscription = geoInitiated$.pipe(operators_1.switchMap(function () {
33483             return visibleMarkers$.pipe(operators_1.withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$));
33484         }))
33485             .subscribe(function (_a) {
33486             var markers = _a[0], reference = _a[1], alt = _a[2];
33487             var geoCoords = _this._geoCoords;
33488             var markerScene = _this._markerScene;
33489             var sceneMarkers = markerScene.markers;
33490             var markersToRemove = Object.assign({}, sceneMarkers);
33491             for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
33492                 var marker = markers_1[_i];
33493                 if (marker.id in sceneMarkers) {
33494                     delete markersToRemove[marker.id];
33495                 }
33496                 else {
33497                     var point3d = geoCoords
33498                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
33499                     markerScene.add(marker, point3d);
33500                 }
33501             }
33502             for (var id in markersToRemove) {
33503                 if (!markersToRemove.hasOwnProperty(id)) {
33504                     continue;
33505                 }
33506                 markerScene.remove(id);
33507             }
33508         });
33509         this._markersUpdatedSubscription = geoInitiated$.pipe(operators_1.switchMap(function () {
33510             return _this._markerSet.updated$.pipe(operators_1.withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$));
33511         }))
33512             .subscribe(function (_a) {
33513             var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
33514             var geoCoords = _this._geoCoords;
33515             var markerScene = _this._markerScene;
33516             for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
33517                 var marker = markers_2[_i];
33518                 var exists = markerScene.has(marker.id);
33519                 var visible = marker.latLon.lat > sw.lat &&
33520                     marker.latLon.lat < ne.lat &&
33521                     marker.latLon.lon > sw.lon &&
33522                     marker.latLon.lon < ne.lon;
33523                 if (visible) {
33524                     var point3d = geoCoords
33525                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
33526                     markerScene.add(marker, point3d);
33527                 }
33528                 else if (!visible && exists) {
33529                     markerScene.remove(marker.id);
33530                 }
33531             }
33532         });
33533         this._referenceSubscription = this._navigator.stateService.reference$.pipe(operators_1.skip(1), operators_1.withLatestFrom(groundAltitude$))
33534             .subscribe(function (_a) {
33535             var reference = _a[0], alt = _a[1];
33536             var geoCoords = _this._geoCoords;
33537             var markerScene = _this._markerScene;
33538             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
33539                 var marker = _b[_i];
33540                 var point3d = geoCoords
33541                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
33542                 markerScene.update(marker.id, point3d);
33543             }
33544         });
33545         this._adjustHeightSubscription = groundAltitude$.pipe(operators_1.skip(1), operators_1.withLatestFrom(this._navigator.stateService.reference$, currentlatLon$))
33546             .subscribe(function (_a) {
33547             var alt = _a[0], reference = _a[1], latLon = _a[2];
33548             var geoCoords = _this._geoCoords;
33549             var markerScene = _this._markerScene;
33550             var position = geoCoords
33551                 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
33552             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
33553                 var marker = _b[_i];
33554                 var point3d = geoCoords
33555                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
33556                 var distanceX = point3d[0] - position[0];
33557                 var distanceY = point3d[1] - position[1];
33558                 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
33559                 if (groundDistance > 50) {
33560                     continue;
33561                 }
33562                 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
33563             }
33564         });
33565         this._renderSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
33566             var scene = _this._markerScene;
33567             return {
33568                 name: _this._name,
33569                 render: {
33570                     frameId: frame.id,
33571                     needsRender: scene.needsRender,
33572                     render: scene.render.bind(scene),
33573                     stage: Render_1.GLRenderStage.Foreground,
33574                 },
33575             };
33576         }))
33577             .subscribe(this._container.glRenderer.render$);
33578         var hoveredMarkerId$ = rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$).pipe(operators_1.map(function (_a) {
33579             var render = _a[0], event = _a[1];
33580             var element = _this._container.element;
33581             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
33582             var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
33583             var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
33584             return markerId;
33585         }), operators_1.publishReplay(1), operators_1.refCount());
33586         var draggingStarted$ = this._container.mouseService
33587             .filtered$(this._name, this._container.mouseService.mouseDragStart$).pipe(operators_1.map(function (event) {
33588             return true;
33589         }));
33590         var draggingStopped$ = this._container.mouseService
33591             .filtered$(this._name, this._container.mouseService.mouseDragEnd$).pipe(operators_1.map(function (event) {
33592             return false;
33593         }));
33594         var filteredDragging$ = rxjs_1.merge(draggingStarted$, draggingStopped$).pipe(operators_1.startWith(false));
33595         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())
33596             .subscribe(function (_a) {
33597             var previous = _a[0], current = _a[1];
33598             var dragging = current[0];
33599             var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
33600             var id = dragging ? current[1] : previous[1];
33601             var marker = _this._markerScene.get(id);
33602             var markerEvent = { marker: marker, target: _this, type: eventType };
33603             _this.fire(eventType, markerEvent);
33604         });
33605         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));
33606         this._mouseClaimSubscription = rxjs_1.combineLatest(this._container.mouseService.active$, hoveredMarkerId$.pipe(operators_1.distinctUntilChanged()), mouseDown$, filteredDragging$).pipe(operators_1.map(function (_a) {
33607             var active = _a[0], markerId = _a[1], mouseDown = _a[2], filteredDragging = _a[3];
33608             return (!active && markerId != null && mouseDown) || filteredDragging;
33609         }), operators_1.distinctUntilChanged())
33610             .subscribe(function (claim) {
33611             if (claim) {
33612                 _this._container.mouseService.claimMouse(_this._name, 1);
33613                 _this._container.mouseService.claimWheel(_this._name, 1);
33614             }
33615             else {
33616                 _this._container.mouseService.unclaimMouse(_this._name);
33617                 _this._container.mouseService.unclaimWheel(_this._name);
33618             }
33619         });
33620         var offset$ = this._container.mouseService
33621             .filtered$(this._name, this._container.mouseService.mouseDragStart$).pipe(operators_1.withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$), operators_1.map(function (_a) {
33622             var e = _a[0], id = _a[1], r = _a[2];
33623             var marker = _this._markerScene.get(id);
33624             var element = _this._container.element;
33625             var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
33626             var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
33627             var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
33628             return [marker, offset, r];
33629         }), operators_1.publishReplay(1), operators_1.refCount());
33630         this._updateMarkerSubscription = this._container.mouseService
33631             .filtered$(this._name, this._container.mouseService.mouseDrag$).pipe(operators_1.withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$))
33632             .subscribe(function (_a) {
33633             var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
33634             if (!_this._markerScene.has(marker.id)) {
33635                 return;
33636             }
33637             var element = _this._container.element;
33638             var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
33639             var groundX = canvasX - offset[0];
33640             var groundY = canvasY - offset[1];
33641             var _d = _this._viewportCoords
33642                 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
33643             var direction = new THREE.Vector3(viewportX, viewportY, 1)
33644                 .unproject(render.perspective)
33645                 .sub(render.perspective.position)
33646                 .normalize();
33647             var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
33648             if (distance < 0) {
33649                 return;
33650             }
33651             var intersection = direction
33652                 .clone()
33653                 .multiplyScalar(distance)
33654                 .add(render.perspective.position);
33655             intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
33656             var _e = _this._geoCoords
33657                 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
33658             _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
33659             _this._markerSet.update(marker);
33660             var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
33661             _this.fire(MarkerComponent.changed, markerEvent);
33662         });
33663     };
33664     MarkerComponent.prototype._deactivate = function () {
33665         this._adjustHeightSubscription.unsubscribe();
33666         this._dragEventSubscription.unsubscribe();
33667         this._markersUpdatedSubscription.unsubscribe();
33668         this._mouseClaimSubscription.unsubscribe();
33669         this._referenceSubscription.unsubscribe();
33670         this._renderSubscription.unsubscribe();
33671         this._setChangedSubscription.unsubscribe();
33672         this._updateMarkerSubscription.unsubscribe();
33673         this._markerScene.clear();
33674     };
33675     MarkerComponent.prototype._getDefaultConfiguration = function () {
33676         return { visibleBBoxSize: 100 };
33677     };
33678     MarkerComponent.componentName = "marker";
33679     /**
33680      * Fired when the position of a marker is changed.
33681      * @event
33682      * @type {IMarkerEvent} markerEvent - Marker event data.
33683      * @example
33684      * ```
33685      * markerComponent.on("changed", function(e) {
33686      *     console.log(e.marker.id, e.marker.latLon);
33687      * });
33688      * ```
33689      */
33690     MarkerComponent.changed = "changed";
33691     /**
33692      * Fired when a marker drag interaction starts.
33693      * @event
33694      * @type {IMarkerEvent} markerEvent - Marker event data.
33695      * @example
33696      * ```
33697      * markerComponent.on("dragstart", function(e) {
33698      *     console.log(e.marker.id, e.marker.latLon);
33699      * });
33700      * ```
33701      */
33702     MarkerComponent.dragstart = "dragstart";
33703     /**
33704      * Fired when a marker drag interaction ends.
33705      * @event
33706      * @type {IMarkerEvent} markerEvent - Marker event data.
33707      * @example
33708      * ```
33709      * markerComponent.on("dragend", function(e) {
33710      *     console.log(e.marker.id, e.marker.latLon);
33711      * });
33712      * ```
33713      */
33714     MarkerComponent.dragend = "dragend";
33715     return MarkerComponent;
33716 }(Component_1.Component));
33717 exports.MarkerComponent = MarkerComponent;
33718 Component_1.ComponentService.register(MarkerComponent);
33719 exports.default = MarkerComponent;
33720
33721
33722 },{"../../Component":291,"../../Geo":294,"../../Graph":295,"../../Render":297,"rxjs":43,"rxjs/operators":241,"three":242,"when":288}],333:[function(require,module,exports){
33723 "use strict";
33724 Object.defineProperty(exports, "__esModule", { value: true });
33725 var THREE = require("three");
33726 var MarkerScene = /** @class */ (function () {
33727     function MarkerScene(scene, raycaster) {
33728         this._needsRender = false;
33729         this._interactiveObjects = [];
33730         this._markers = {};
33731         this._objectMarkers = {};
33732         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
33733         this._scene = !!scene ? scene : new THREE.Scene();
33734     }
33735     Object.defineProperty(MarkerScene.prototype, "markers", {
33736         get: function () {
33737             return this._markers;
33738         },
33739         enumerable: true,
33740         configurable: true
33741     });
33742     Object.defineProperty(MarkerScene.prototype, "needsRender", {
33743         get: function () {
33744             return this._needsRender;
33745         },
33746         enumerable: true,
33747         configurable: true
33748     });
33749     MarkerScene.prototype.add = function (marker, position) {
33750         if (marker.id in this._markers) {
33751             this._dispose(marker.id);
33752         }
33753         marker.createGeometry(position);
33754         this._scene.add(marker.geometry);
33755         this._markers[marker.id] = marker;
33756         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
33757             var interactiveObject = _a[_i];
33758             this._interactiveObjects.push(interactiveObject);
33759             this._objectMarkers[interactiveObject.uuid] = marker.id;
33760         }
33761         this._needsRender = true;
33762     };
33763     MarkerScene.prototype.clear = function () {
33764         for (var id in this._markers) {
33765             if (!this._markers.hasOwnProperty) {
33766                 continue;
33767             }
33768             this._dispose(id);
33769         }
33770         this._needsRender = true;
33771     };
33772     MarkerScene.prototype.get = function (id) {
33773         return this._markers[id];
33774     };
33775     MarkerScene.prototype.getAll = function () {
33776         var _this = this;
33777         return Object
33778             .keys(this._markers)
33779             .map(function (id) { return _this._markers[id]; });
33780     };
33781     MarkerScene.prototype.has = function (id) {
33782         return id in this._markers;
33783     };
33784     MarkerScene.prototype.intersectObjects = function (_a, camera) {
33785         var viewportX = _a[0], viewportY = _a[1];
33786         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
33787         var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
33788         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
33789             var intersect = intersects_1[_i];
33790             if (intersect.object.uuid in this._objectMarkers) {
33791                 return this._objectMarkers[intersect.object.uuid];
33792             }
33793         }
33794         return null;
33795     };
33796     MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
33797         if (!(id in this._markers)) {
33798             return;
33799         }
33800         this._markers[id].lerpAltitude(alt, alpha);
33801         this._needsRender = true;
33802     };
33803     MarkerScene.prototype.remove = function (id) {
33804         if (!(id in this._markers)) {
33805             return;
33806         }
33807         this._dispose(id);
33808         this._needsRender = true;
33809     };
33810     MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
33811         renderer.render(this._scene, perspectiveCamera);
33812         this._needsRender = false;
33813     };
33814     MarkerScene.prototype.update = function (id, position, latLon) {
33815         if (!(id in this._markers)) {
33816             return;
33817         }
33818         var marker = this._markers[id];
33819         marker.updatePosition(position, latLon);
33820         this._needsRender = true;
33821     };
33822     MarkerScene.prototype._dispose = function (id) {
33823         var marker = this._markers[id];
33824         this._scene.remove(marker.geometry);
33825         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
33826             var interactiveObject = _a[_i];
33827             var index = this._interactiveObjects.indexOf(interactiveObject);
33828             if (index !== -1) {
33829                 this._interactiveObjects.splice(index, 1);
33830             }
33831             else {
33832                 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
33833             }
33834             delete this._objectMarkers[interactiveObject.uuid];
33835         }
33836         marker.disposeGeometry();
33837         delete this._markers[id];
33838     };
33839     return MarkerScene;
33840 }());
33841 exports.MarkerScene = MarkerScene;
33842 exports.default = MarkerScene;
33843
33844 },{"three":242}],334:[function(require,module,exports){
33845 "use strict";
33846 Object.defineProperty(exports, "__esModule", { value: true });
33847 var rbush = require("rbush");
33848 var rxjs_1 = require("rxjs");
33849 var MarkerSet = /** @class */ (function () {
33850     function MarkerSet() {
33851         this._hash = {};
33852         this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
33853         this._indexChanged$ = new rxjs_1.Subject();
33854         this._updated$ = new rxjs_1.Subject();
33855     }
33856     Object.defineProperty(MarkerSet.prototype, "changed$", {
33857         get: function () {
33858             return this._indexChanged$;
33859         },
33860         enumerable: true,
33861         configurable: true
33862     });
33863     Object.defineProperty(MarkerSet.prototype, "updated$", {
33864         get: function () {
33865             return this._updated$;
33866         },
33867         enumerable: true,
33868         configurable: true
33869     });
33870     MarkerSet.prototype.add = function (markers) {
33871         var updated = [];
33872         var hash = this._hash;
33873         var index = this._index;
33874         for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
33875             var marker = markers_1[_i];
33876             var id = marker.id;
33877             if (id in hash) {
33878                 index.remove(hash[id]);
33879                 updated.push(marker);
33880             }
33881             var item = {
33882                 lat: marker.latLon.lat,
33883                 lon: marker.latLon.lon,
33884                 marker: marker,
33885             };
33886             hash[id] = item;
33887             index.insert(item);
33888         }
33889         if (updated.length > 0) {
33890             this._updated$.next(updated);
33891         }
33892         if (markers.length > updated.length) {
33893             this._indexChanged$.next(this);
33894         }
33895     };
33896     MarkerSet.prototype.has = function (id) {
33897         return id in this._hash;
33898     };
33899     MarkerSet.prototype.get = function (id) {
33900         return this.has(id) ? this._hash[id].marker : undefined;
33901     };
33902     MarkerSet.prototype.getAll = function () {
33903         return this._index
33904             .all()
33905             .map(function (indexItem) {
33906             return indexItem.marker;
33907         });
33908     };
33909     MarkerSet.prototype.remove = function (ids) {
33910         var hash = this._hash;
33911         var index = this._index;
33912         var changed = false;
33913         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
33914             var id = ids_1[_i];
33915             if (!(id in hash)) {
33916                 continue;
33917             }
33918             var item = hash[id];
33919             index.remove(item);
33920             delete hash[id];
33921             changed = true;
33922         }
33923         if (changed) {
33924             this._indexChanged$.next(this);
33925         }
33926     };
33927     MarkerSet.prototype.removeAll = function () {
33928         this._hash = {};
33929         this._index.clear();
33930         this._indexChanged$.next(this);
33931     };
33932     MarkerSet.prototype.search = function (_a) {
33933         var sw = _a[0], ne = _a[1];
33934         return this._index
33935             .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
33936             .map(function (indexItem) {
33937             return indexItem.marker;
33938         });
33939     };
33940     MarkerSet.prototype.update = function (marker) {
33941         var hash = this._hash;
33942         var index = this._index;
33943         var id = marker.id;
33944         if (!(id in hash)) {
33945             return;
33946         }
33947         index.remove(hash[id]);
33948         var item = {
33949             lat: marker.latLon.lat,
33950             lon: marker.latLon.lon,
33951             marker: marker,
33952         };
33953         hash[id] = item;
33954         index.insert(item);
33955     };
33956     return MarkerSet;
33957 }());
33958 exports.MarkerSet = MarkerSet;
33959 exports.default = MarkerSet;
33960
33961 },{"rbush":42,"rxjs":43}],335:[function(require,module,exports){
33962 "use strict";
33963 var __extends = (this && this.__extends) || (function () {
33964     var extendStatics = function (d, b) {
33965         extendStatics = Object.setPrototypeOf ||
33966             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33967             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33968         return extendStatics(d, b);
33969     }
33970     return function (d, b) {
33971         extendStatics(d, b);
33972         function __() { this.constructor = d; }
33973         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33974     };
33975 })();
33976 Object.defineProperty(exports, "__esModule", { value: true });
33977 var THREE = require("three");
33978 var Component_1 = require("../../../Component");
33979 /**
33980  * @class CircleMarker
33981  *
33982  * @classdesc Non-interactive marker with a flat circle shape. The circle
33983  * marker can not be configured to be interactive.
33984  *
33985  * Circle marker properties can not be updated after creation.
33986  *
33987  * To create and add one `CircleMarker` with default configuration
33988  * and one with configuration use
33989  *
33990  * @example
33991  * ```
33992  * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
33993  *     "id-1",
33994  *     { lat: 0, lon: 0, });
33995  *
33996  * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
33997  *     "id-2",
33998  *     { lat: 0, lon: 0, },
33999  *     {
34000  *         color: "#0Ff",
34001  *         opacity: 0.3,
34002  *         radius: 0.7,
34003  *     });
34004  *
34005  * markerComponent.add([defaultMarker, configuredMarker]);
34006  * ```
34007  */
34008 var CircleMarker = /** @class */ (function (_super) {
34009     __extends(CircleMarker, _super);
34010     function CircleMarker(id, latLon, options) {
34011         var _this = _super.call(this, id, latLon) || this;
34012         options = !!options ? options : {};
34013         _this._color = options.color != null ? options.color : 0xffffff;
34014         _this._opacity = options.opacity != null ? options.opacity : 0.4;
34015         _this._radius = options.radius != null ? options.radius : 1;
34016         return _this;
34017     }
34018     CircleMarker.prototype._createGeometry = function (position) {
34019         var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
34020             color: this._color,
34021             opacity: this._opacity,
34022             transparent: true,
34023         }));
34024         circle.up.fromArray([0, 0, 1]);
34025         circle.renderOrder = -1;
34026         var group = new THREE.Object3D();
34027         group.add(circle);
34028         group.position.fromArray(position);
34029         this._geometry = group;
34030     };
34031     CircleMarker.prototype._disposeGeometry = function () {
34032         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
34033             var mesh = _a[_i];
34034             mesh.geometry.dispose();
34035             mesh.material.dispose();
34036         }
34037     };
34038     CircleMarker.prototype._getInteractiveObjects = function () {
34039         return [];
34040     };
34041     return CircleMarker;
34042 }(Component_1.Marker));
34043 exports.CircleMarker = CircleMarker;
34044 exports.default = CircleMarker;
34045
34046 },{"../../../Component":291,"three":242}],336:[function(require,module,exports){
34047 "use strict";
34048 Object.defineProperty(exports, "__esModule", { value: true });
34049 /**
34050  * @class Marker
34051  *
34052  * @classdesc Represents an abstract marker class that should be extended
34053  * by marker implementations used in the marker component.
34054  */
34055 var Marker = /** @class */ (function () {
34056     function Marker(id, latLon) {
34057         this._id = id;
34058         this._latLon = latLon;
34059     }
34060     Object.defineProperty(Marker.prototype, "id", {
34061         /**
34062          * Get id.
34063          * @returns {string} The id of the marker.
34064          */
34065         get: function () {
34066             return this._id;
34067         },
34068         enumerable: true,
34069         configurable: true
34070     });
34071     Object.defineProperty(Marker.prototype, "geometry", {
34072         /**
34073          * Get geometry.
34074          *
34075          * @ignore
34076          */
34077         get: function () {
34078             return this._geometry;
34079         },
34080         enumerable: true,
34081         configurable: true
34082     });
34083     Object.defineProperty(Marker.prototype, "latLon", {
34084         /**
34085          * Get lat lon.
34086          * @returns {ILatLon} The geographic coordinates of the marker.
34087          */
34088         get: function () {
34089             return this._latLon;
34090         },
34091         enumerable: true,
34092         configurable: true
34093     });
34094     /** @ignore */
34095     Marker.prototype.createGeometry = function (position) {
34096         if (!!this._geometry) {
34097             return;
34098         }
34099         this._createGeometry(position);
34100         // update matrix world if raycasting occurs before first render
34101         this._geometry.updateMatrixWorld(true);
34102     };
34103     /** @ignore */
34104     Marker.prototype.disposeGeometry = function () {
34105         if (!this._geometry) {
34106             return;
34107         }
34108         this._disposeGeometry();
34109         this._geometry = undefined;
34110     };
34111     /** @ignore */
34112     Marker.prototype.getInteractiveObjects = function () {
34113         if (!this._geometry) {
34114             return [];
34115         }
34116         return this._getInteractiveObjects();
34117     };
34118     /** @ignore */
34119     Marker.prototype.lerpAltitude = function (alt, alpha) {
34120         if (!this._geometry) {
34121             return;
34122         }
34123         this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
34124     };
34125     /** @ignore */
34126     Marker.prototype.updatePosition = function (position, latLon) {
34127         if (!!latLon) {
34128             this._latLon.lat = latLon.lat;
34129             this._latLon.lon = latLon.lon;
34130         }
34131         if (!this._geometry) {
34132             return;
34133         }
34134         this._geometry.position.fromArray(position);
34135         this._geometry.updateMatrixWorld(true);
34136     };
34137     return Marker;
34138 }());
34139 exports.Marker = Marker;
34140 exports.default = Marker;
34141
34142 },{}],337:[function(require,module,exports){
34143 "use strict";
34144 var __extends = (this && this.__extends) || (function () {
34145     var extendStatics = function (d, b) {
34146         extendStatics = Object.setPrototypeOf ||
34147             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34148             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34149         return extendStatics(d, b);
34150     }
34151     return function (d, b) {
34152         extendStatics(d, b);
34153         function __() { this.constructor = d; }
34154         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34155     };
34156 })();
34157 Object.defineProperty(exports, "__esModule", { value: true });
34158 var THREE = require("three");
34159 var Component_1 = require("../../../Component");
34160 /**
34161  * @class SimpleMarker
34162  *
34163  * @classdesc Interactive marker with ice cream shape. The sphere
34164  * inside the ice cream can be configured to be interactive.
34165  *
34166  * Simple marker properties can not be updated after creation.
34167  *
34168  * To create and add one `SimpleMarker` with default configuration
34169  * (non-interactive) and one interactive with configuration use
34170  *
34171  * @example
34172  * ```
34173  * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
34174  *     "id-1",
34175  *     { lat: 0, lon: 0, });
34176  *
34177  * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
34178  *     "id-2",
34179  *     { lat: 0, lon: 0, },
34180  *     {
34181  *         ballColor: "#00f",
34182  *         ballOpacity: 0.5,
34183  *         color: "#00f",
34184  *         interactive: true,
34185  *         opacity: 0.3,
34186  *         radius: 0.7,
34187  *     });
34188  *
34189  * markerComponent.add([defaultMarker, interactiveMarker]);
34190  * ```
34191  */
34192 var SimpleMarker = /** @class */ (function (_super) {
34193     __extends(SimpleMarker, _super);
34194     function SimpleMarker(id, latLon, options) {
34195         var _this = _super.call(this, id, latLon) || this;
34196         options = !!options ? options : {};
34197         _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
34198         _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
34199         _this._circleToRayAngle = 2;
34200         _this._color = options.color != null ? options.color : 0xff0000;
34201         _this._interactive = !!options.interactive;
34202         _this._opacity = options.opacity != null ? options.opacity : 0.4;
34203         _this._radius = options.radius != null ? options.radius : 1;
34204         return _this;
34205     }
34206     SimpleMarker.prototype._createGeometry = function (position) {
34207         var radius = this._radius;
34208         var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
34209             color: this._color,
34210             opacity: this._opacity,
34211             transparent: true,
34212         }));
34213         cone.renderOrder = 1;
34214         var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
34215             color: this._ballColor,
34216             opacity: this._ballOpacity,
34217             transparent: true,
34218         }));
34219         ball.position.z = this._markerHeight(radius);
34220         var group = new THREE.Object3D();
34221         group.add(ball);
34222         group.add(cone);
34223         group.position.fromArray(position);
34224         this._geometry = group;
34225     };
34226     SimpleMarker.prototype._disposeGeometry = function () {
34227         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
34228             var mesh = _a[_i];
34229             mesh.geometry.dispose();
34230             mesh.material.dispose();
34231         }
34232     };
34233     SimpleMarker.prototype._getInteractiveObjects = function () {
34234         return this._interactive ? [this._geometry.children[0]] : [];
34235     };
34236     SimpleMarker.prototype._markerHeight = function (radius) {
34237         var t = Math.tan(Math.PI - this._circleToRayAngle);
34238         return radius * Math.sqrt(1 + t * t);
34239     };
34240     SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
34241         var geometry = new THREE.Geometry();
34242         widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
34243         heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
34244         var height = this._markerHeight(radius);
34245         var vertices = [];
34246         for (var y = 0; y <= heightSegments; ++y) {
34247             var verticesRow = [];
34248             for (var x = 0; x <= widthSegments; ++x) {
34249                 var u = x / widthSegments * Math.PI * 2;
34250                 var v = y / heightSegments * Math.PI;
34251                 var r = void 0;
34252                 if (v < this._circleToRayAngle) {
34253                     r = radius;
34254                 }
34255                 else {
34256                     var t = Math.tan(v - this._circleToRayAngle);
34257                     r = radius * Math.sqrt(1 + t * t);
34258                 }
34259                 var vertex = new THREE.Vector3();
34260                 vertex.x = r * Math.cos(u) * Math.sin(v);
34261                 vertex.y = r * Math.sin(u) * Math.sin(v);
34262                 vertex.z = r * Math.cos(v) + height;
34263                 geometry.vertices.push(vertex);
34264                 verticesRow.push(geometry.vertices.length - 1);
34265             }
34266             vertices.push(verticesRow);
34267         }
34268         for (var y = 0; y < heightSegments; ++y) {
34269             for (var x = 0; x < widthSegments; ++x) {
34270                 var v1 = vertices[y][x + 1];
34271                 var v2 = vertices[y][x];
34272                 var v3 = vertices[y + 1][x];
34273                 var v4 = vertices[y + 1][x + 1];
34274                 var n1 = geometry.vertices[v1].clone().normalize();
34275                 var n2 = geometry.vertices[v2].clone().normalize();
34276                 var n3 = geometry.vertices[v3].clone().normalize();
34277                 var n4 = geometry.vertices[v4].clone().normalize();
34278                 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
34279                 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
34280             }
34281         }
34282         geometry.computeFaceNormals();
34283         geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
34284         return geometry;
34285     };
34286     return SimpleMarker;
34287 }(Component_1.Marker));
34288 exports.SimpleMarker = SimpleMarker;
34289 exports.default = SimpleMarker;
34290
34291 },{"../../../Component":291,"three":242}],338:[function(require,module,exports){
34292 "use strict";
34293 var __extends = (this && this.__extends) || (function () {
34294     var extendStatics = function (d, b) {
34295         extendStatics = Object.setPrototypeOf ||
34296             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34297             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34298         return extendStatics(d, b);
34299     }
34300     return function (d, b) {
34301         extendStatics(d, b);
34302         function __() { this.constructor = d; }
34303         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34304     };
34305 })();
34306 Object.defineProperty(exports, "__esModule", { value: true });
34307 var rxjs_1 = require("rxjs");
34308 var operators_1 = require("rxjs/operators");
34309 var Component_1 = require("../../Component");
34310 /**
34311  * The `BounceHandler` ensures that the viewer bounces back to the image
34312  * when drag panning outside of the image edge.
34313  */
34314 var BounceHandler = /** @class */ (function (_super) {
34315     __extends(BounceHandler, _super);
34316     function BounceHandler(component, container, navigator, viewportCoords, spatial) {
34317         var _this = _super.call(this, component, container, navigator) || this;
34318         _this._spatial = spatial;
34319         _this._viewportCoords = viewportCoords;
34320         return _this;
34321     }
34322     BounceHandler.prototype._enable = function () {
34323         var _this = this;
34324         var inTransition$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
34325             return frame.state.alpha < 1;
34326         }), operators_1.distinctUntilChanged());
34327         this._bounceSubscription = rxjs_1.combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$).pipe(operators_1.map(function (noForce) {
34328             return noForce[0] || noForce[1] || noForce[2] || noForce[3];
34329         }), operators_1.distinctUntilChanged(), operators_1.switchMap(function (noForce) {
34330             return noForce ?
34331                 rxjs_1.empty() :
34332                 rxjs_1.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.pipe(operators_1.first()));
34333         }), operators_1.withLatestFrom(this._navigator.panService.panNodes$))
34334             .subscribe(function (_a) {
34335             var _b = _a[0], render = _b[0], transform = _b[1], nts = _a[1];
34336             if (!transform.hasValidScale && render.camera.focal < 0.1) {
34337                 return;
34338             }
34339             if (render.perspective.aspect === 0 || render.perspective.aspect === Number.POSITIVE_INFINITY) {
34340                 return;
34341             }
34342             var distances = Component_1.ImageBoundary.viewportDistances(transform, render.perspective, _this._viewportCoords);
34343             var basic = _this._viewportCoords.viewportToBasic(0, 0, transform, render.perspective);
34344             if ((basic[0] < 0 || basic[0] > 1) && nts.length > 0) {
34345                 distances[0] = distances[2] = 0;
34346             }
34347             for (var _i = 0, nts_1 = nts; _i < nts_1.length; _i++) {
34348                 var _c = nts_1[_i], t = _c[1];
34349                 var d = Component_1.ImageBoundary.viewportDistances(t, render.perspective, _this._viewportCoords);
34350                 for (var i = 1; i < distances.length; i += 2) {
34351                     if (d[i] < distances[i]) {
34352                         distances[i] = d[i];
34353                     }
34354                 }
34355             }
34356             if (Math.max.apply(Math, distances) < 0.01) {
34357                 return;
34358             }
34359             var horizontalDistance = distances[1] - distances[3];
34360             var verticalDistance = distances[0] - distances[2];
34361             var currentDirection = _this._viewportCoords
34362                 .unprojectFromViewport(0, 0, render.perspective)
34363                 .sub(render.perspective.position);
34364             var directionPhi = _this._viewportCoords
34365                 .unprojectFromViewport(horizontalDistance, 0, render.perspective)
34366                 .sub(render.perspective.position);
34367             var directionTheta = _this._viewportCoords
34368                 .unprojectFromViewport(0, verticalDistance, render.perspective)
34369                 .sub(render.perspective.position);
34370             var phi = (horizontalDistance > 0 ? 1 : -1) * directionPhi.angleTo(currentDirection);
34371             var theta = (verticalDistance > 0 ? 1 : -1) * directionTheta.angleTo(currentDirection);
34372             var threshold = Math.PI / 60;
34373             var coeff = 1e-1;
34374             phi = _this._spatial.clamp(coeff * phi, -threshold, threshold);
34375             theta = _this._spatial.clamp(coeff * theta, -threshold, threshold);
34376             _this._navigator.stateService.rotateUnbounded({ phi: phi, theta: theta });
34377         });
34378     };
34379     BounceHandler.prototype._disable = function () {
34380         this._bounceSubscription.unsubscribe();
34381     };
34382     BounceHandler.prototype._getConfiguration = function () {
34383         return {};
34384     };
34385     return BounceHandler;
34386 }(Component_1.HandlerBase));
34387 exports.BounceHandler = BounceHandler;
34388 exports.default = BounceHandler;
34389
34390 },{"../../Component":291,"rxjs":43,"rxjs/operators":241}],339:[function(require,module,exports){
34391 "use strict";
34392 var __extends = (this && this.__extends) || (function () {
34393     var extendStatics = function (d, b) {
34394         extendStatics = Object.setPrototypeOf ||
34395             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34396             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34397         return extendStatics(d, b);
34398     }
34399     return function (d, b) {
34400         extendStatics(d, b);
34401         function __() { this.constructor = d; }
34402         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34403     };
34404 })();
34405 Object.defineProperty(exports, "__esModule", { value: true });
34406 var rxjs_1 = require("rxjs");
34407 var operators_1 = require("rxjs/operators");
34408 var Component_1 = require("../../Component");
34409 /**
34410  * The `DoubleClickZoomHandler` allows the user to zoom the viewer image at a point by double clicking.
34411  *
34412  * @example
34413  * ```
34414  * var mouseComponent = viewer.getComponent("mouse");
34415  *
34416  * mouseComponent.doubleClickZoom.disable();
34417  * mouseComponent.doubleClickZoom.enable();
34418  *
34419  * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
34420  * ```
34421  */
34422 var DoubleClickZoomHandler = /** @class */ (function (_super) {
34423     __extends(DoubleClickZoomHandler, _super);
34424     /** @ignore */
34425     function DoubleClickZoomHandler(component, container, navigator, viewportCoords) {
34426         var _this = _super.call(this, component, container, navigator) || this;
34427         _this._viewportCoords = viewportCoords;
34428         return _this;
34429     }
34430     DoubleClickZoomHandler.prototype._enable = function () {
34431         var _this = this;
34432         this._zoomSubscription = rxjs_1.merge(this._container.mouseService
34433             .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$.pipe(operators_1.map(function (e) {
34434             var touch = e.touches[0];
34435             return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
34436         }))).pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
34437             .subscribe(function (_a) {
34438             var event = _a[0], render = _a[1], transform = _a[2];
34439             var element = _this._container.element;
34440             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
34441             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
34442             var reference = transform.projectBasic(unprojected.toArray());
34443             var delta = !!event.shiftKey ? -1 : 1;
34444             _this._navigator.stateService.zoomIn(delta, reference);
34445         });
34446     };
34447     DoubleClickZoomHandler.prototype._disable = function () {
34448         this._zoomSubscription.unsubscribe();
34449     };
34450     DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
34451         return { doubleClickZoom: enable };
34452     };
34453     return DoubleClickZoomHandler;
34454 }(Component_1.HandlerBase));
34455 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
34456 exports.default = DoubleClickZoomHandler;
34457
34458 },{"../../Component":291,"rxjs":43,"rxjs/operators":241}],340:[function(require,module,exports){
34459 "use strict";
34460 var __extends = (this && this.__extends) || (function () {
34461     var extendStatics = function (d, b) {
34462         extendStatics = Object.setPrototypeOf ||
34463             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34464             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34465         return extendStatics(d, b);
34466     }
34467     return function (d, b) {
34468         extendStatics(d, b);
34469         function __() { this.constructor = d; }
34470         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34471     };
34472 })();
34473 Object.defineProperty(exports, "__esModule", { value: true });
34474 var rxjs_1 = require("rxjs");
34475 var operators_1 = require("rxjs/operators");
34476 var Component_1 = require("../../Component");
34477 /**
34478  * The `DragPanHandler` allows the user to pan the viewer image by clicking and dragging the cursor.
34479  *
34480  * @example
34481  * ```
34482  * var mouseComponent = viewer.getComponent("mouse");
34483  *
34484  * mouseComponent.dragPan.disable();
34485  * mouseComponent.dragPan.enable();
34486  *
34487  * var isEnabled = mouseComponent.dragPan.isEnabled;
34488  * ```
34489  */
34490 var DragPanHandler = /** @class */ (function (_super) {
34491     __extends(DragPanHandler, _super);
34492     /** @ignore */
34493     function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
34494         var _this = _super.call(this, component, container, navigator) || this;
34495         _this._spatial = spatial;
34496         _this._viewportCoords = viewportCoords;
34497         return _this;
34498     }
34499     DragPanHandler.prototype._enable = function () {
34500         var _this = this;
34501         var draggingStarted$ = this._container.mouseService
34502             .filtered$(this._component.name, this._container.mouseService.mouseDragStart$).pipe(operators_1.map(function () {
34503             return true;
34504         }), operators_1.share());
34505         var draggingStopped$ = this._container.mouseService
34506             .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$).pipe(operators_1.map(function () {
34507             return false;
34508         }), operators_1.share());
34509         this._activeMouseSubscription = rxjs_1.merge(draggingStarted$, draggingStopped$)
34510             .subscribe(this._container.mouseService.activate$);
34511         var documentMouseMove$ = rxjs_1.merge(draggingStarted$, draggingStopped$).pipe(operators_1.switchMap(function (dragging) {
34512             return dragging ?
34513                 _this._container.mouseService.documentMouseMove$ :
34514                 rxjs_1.empty();
34515         }));
34516         this._preventDefaultSubscription = rxjs_1.merge(documentMouseMove$, this._container.touchService.touchMove$)
34517             .subscribe(function (event) {
34518             event.preventDefault(); // prevent selection of content outside the viewer
34519         });
34520         var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$.pipe(operators_1.map(function () {
34521             return true;
34522         }));
34523         var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$.pipe(operators_1.map(function () {
34524             return false;
34525         }));
34526         this._activeTouchSubscription = rxjs_1.merge(touchMovingStarted$, touchMovingStopped$)
34527             .subscribe(this._container.touchService.activate$);
34528         var rotation$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
34529             return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
34530         }), operators_1.distinctUntilChanged(), operators_1.switchMap(function (enable) {
34531             if (!enable) {
34532                 return rxjs_1.empty();
34533             }
34534             var mouseDrag$ = Component_1.MouseOperator.filteredPairwiseMouseDrag$(_this._component.name, _this._container.mouseService);
34535             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) {
34536                 return event != null && event.touches.length > 0 ?
34537                     event.touches[0] : null;
34538             }), operators_1.pairwise(), operators_1.filter(function (pair) {
34539                 return pair[0] != null && pair[1] != null;
34540             }));
34541             return rxjs_1.merge(mouseDrag$, singleTouchDrag$);
34542         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.panService.panNodes$), operators_1.map(function (_a) {
34543             var events = _a[0], render = _a[1], transform = _a[2], nts = _a[3];
34544             var previousEvent = events[0];
34545             var event = events[1];
34546             var movementX = event.clientX - previousEvent.clientX;
34547             var movementY = event.clientY - previousEvent.clientY;
34548             var element = _this._container.element;
34549             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
34550             var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
34551                 .sub(render.perspective.position);
34552             var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
34553                 .sub(render.perspective.position);
34554             var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
34555                 .sub(render.perspective.position);
34556             var phi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
34557             var theta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
34558             var distances = Component_1.ImageBoundary.viewportDistances(transform, render.perspective, _this._viewportCoords);
34559             for (var _i = 0, nts_1 = nts; _i < nts_1.length; _i++) {
34560                 var _c = nts_1[_i], t = _c[1];
34561                 var d = Component_1.ImageBoundary.viewportDistances(t, render.perspective, _this._viewportCoords);
34562                 for (var i = 0; i < distances.length; i++) {
34563                     if (d[i] < distances[i]) {
34564                         distances[i] = d[i];
34565                     }
34566                 }
34567             }
34568             if (distances[0] > 0 && theta < 0) {
34569                 theta /= Math.max(1, 2e2 * distances[0]);
34570             }
34571             if (distances[2] > 0 && theta > 0) {
34572                 theta /= Math.max(1, 2e2 * distances[2]);
34573             }
34574             if (distances[1] > 0 && phi < 0) {
34575                 phi /= Math.max(1, 2e2 * distances[1]);
34576             }
34577             if (distances[3] > 0 && phi > 0) {
34578                 phi /= Math.max(1, 2e2 * distances[3]);
34579             }
34580             return { phi: phi, theta: theta };
34581         }), operators_1.share());
34582         this._rotateWithoutInertiaSubscription = rotation$
34583             .subscribe(function (rotation) {
34584             _this._navigator.stateService.rotateWithoutInertia(rotation);
34585         });
34586         this._rotateSubscription = rotation$.pipe(operators_1.scan(function (rotationBuffer, rotation) {
34587             _this._drainBuffer(rotationBuffer);
34588             rotationBuffer.push([Date.now(), rotation]);
34589             return rotationBuffer;
34590         }, []), 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) {
34591             var drainedBuffer = _this._drainBuffer(rotationBuffer.slice());
34592             var rotation = { phi: 0, theta: 0 };
34593             for (var _i = 0, drainedBuffer_1 = drainedBuffer; _i < drainedBuffer_1.length; _i++) {
34594                 var bufferedRotation = drainedBuffer_1[_i];
34595                 rotation.phi += bufferedRotation[1].phi;
34596                 rotation.theta += bufferedRotation[1].theta;
34597             }
34598             var count = drainedBuffer.length;
34599             if (count > 0) {
34600                 rotation.phi /= count;
34601                 rotation.theta /= count;
34602             }
34603             var threshold = Math.PI / 18;
34604             rotation.phi = _this._spatial.clamp(rotation.phi, -threshold, threshold);
34605             rotation.theta = _this._spatial.clamp(rotation.theta, -threshold, threshold);
34606             return rotation;
34607         }))
34608             .subscribe(function (rotation) {
34609             _this._navigator.stateService.rotate(rotation);
34610         });
34611     };
34612     DragPanHandler.prototype._disable = function () {
34613         this._activeMouseSubscription.unsubscribe();
34614         this._activeTouchSubscription.unsubscribe();
34615         this._preventDefaultSubscription.unsubscribe();
34616         this._rotateSubscription.unsubscribe();
34617         this._rotateWithoutInertiaSubscription.unsubscribe();
34618         this._activeMouseSubscription = null;
34619         this._activeTouchSubscription = null;
34620         this._preventDefaultSubscription = null;
34621         this._rotateSubscription = null;
34622     };
34623     DragPanHandler.prototype._getConfiguration = function (enable) {
34624         return { dragPan: enable };
34625     };
34626     DragPanHandler.prototype._drainBuffer = function (buffer) {
34627         var cutoff = 50;
34628         var now = Date.now();
34629         while (buffer.length > 0 && now - buffer[0][0] > cutoff) {
34630             buffer.shift();
34631         }
34632         return buffer;
34633     };
34634     return DragPanHandler;
34635 }(Component_1.HandlerBase));
34636 exports.DragPanHandler = DragPanHandler;
34637 exports.default = DragPanHandler;
34638
34639 },{"../../Component":291,"rxjs":43,"rxjs/operators":241}],341:[function(require,module,exports){
34640 "use strict";
34641 var __extends = (this && this.__extends) || (function () {
34642     var extendStatics = function (d, b) {
34643         extendStatics = Object.setPrototypeOf ||
34644             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34645             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34646         return extendStatics(d, b);
34647     }
34648     return function (d, b) {
34649         extendStatics(d, b);
34650         function __() { this.constructor = d; }
34651         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34652     };
34653 })();
34654 Object.defineProperty(exports, "__esModule", { value: true });
34655 var THREE = require("three");
34656 var rxjs_1 = require("rxjs");
34657 var operators_1 = require("rxjs/operators");
34658 var Component_1 = require("../../Component");
34659 var State_1 = require("../../State");
34660 var EarthControlHandler = /** @class */ (function (_super) {
34661     __extends(EarthControlHandler, _super);
34662     function EarthControlHandler(component, container, navigator, viewportCoords, spatial) {
34663         var _this = _super.call(this, component, container, navigator) || this;
34664         _this._spatial = spatial;
34665         _this._viewportCoords = viewportCoords;
34666         return _this;
34667     }
34668     EarthControlHandler.prototype._enable = function () {
34669         var _this = this;
34670         var earth$ = this._navigator.stateService.state$.pipe(operators_1.map(function (state) {
34671             return state === State_1.State.Earth;
34672         }), operators_1.share());
34673         this._preventDefaultSubscription = earth$.pipe(operators_1.switchMap(function (earth) {
34674             return earth ?
34675                 _this._container.mouseService.mouseWheel$ :
34676                 rxjs_1.empty();
34677         }))
34678             .subscribe(function (event) {
34679             event.preventDefault();
34680         });
34681         this._truckSubscription = earth$.pipe(operators_1.switchMap(function (earth) {
34682             if (!earth) {
34683                 return rxjs_1.empty();
34684             }
34685             return Component_1.MouseOperator.filteredPairwiseMouseDrag$(_this._component.name, _this._container.mouseService).pipe(operators_1.filter(function (_a) {
34686                 var e1 = _a[0], e2 = _a[1];
34687                 return !(e1.ctrlKey && e2.ctrlKey);
34688             }));
34689         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
34690             var _b = _a[0], previous = _b[0], current = _b[1], render = _a[1], transform = _a[2];
34691             var planeNormal = [0, 0, 1];
34692             var planePoint = transform.unprojectBasic([0.5, 0.5], 0);
34693             planePoint[2] -= 2;
34694             var currentIntersection = _this._planeIntersection(current, planeNormal, planePoint, render.perspective, _this._container.element);
34695             var previousIntersection = _this._planeIntersection(previous, planeNormal, planePoint, render.perspective, _this._container.element);
34696             if (!currentIntersection || !previousIntersection) {
34697                 return null;
34698             }
34699             var direction = new THREE.Vector3()
34700                 .subVectors(currentIntersection, previousIntersection)
34701                 .multiplyScalar(-1)
34702                 .toArray();
34703             return direction;
34704         }), operators_1.filter(function (direction) {
34705             return !!direction;
34706         }))
34707             .subscribe(function (direction) {
34708             _this._navigator.stateService.truck(direction);
34709         });
34710         this._orbitSubscription = earth$.pipe(operators_1.switchMap(function (earth) {
34711             if (!earth) {
34712                 return rxjs_1.empty();
34713             }
34714             return Component_1.MouseOperator.filteredPairwiseMouseDrag$(_this._component.name, _this._container.mouseService).pipe(operators_1.filter(function (_a) {
34715                 var e1 = _a[0], e2 = _a[1];
34716                 return e1.ctrlKey && e2.ctrlKey;
34717             }));
34718         }), operators_1.map(function (_a) {
34719             var previous = _a[0], current = _a[1];
34720             var _b = _this._eventToViewport(current, _this._container.element), currentX = _b[0], currentY = _b[1];
34721             var _c = _this._eventToViewport(previous, _this._container.element), previousX = _c[0], previousY = _c[1];
34722             var phi = (previousX - currentX) * Math.PI;
34723             var theta = (currentY - previousY) * Math.PI / 2;
34724             return { phi: phi, theta: theta };
34725         }))
34726             .subscribe(function (rotation) {
34727             _this._navigator.stateService.orbit(rotation);
34728         });
34729         this._dollySubscription = earth$.pipe(operators_1.switchMap(function (earth) {
34730             if (!earth) {
34731                 return rxjs_1.empty();
34732             }
34733             return _this._container.mouseService
34734                 .filteredWheel$(_this._component.name, _this._container.mouseService.mouseWheel$);
34735         }), operators_1.map(function (event) {
34736             var delta = event.deltaY;
34737             if (event.deltaMode === 1) {
34738                 delta = 40 * delta;
34739             }
34740             else if (event.deltaMode === 2) {
34741                 delta = 800 * delta;
34742             }
34743             var canvasSize = _this._viewportCoords.containerToCanvas(_this._container.element);
34744             return -delta / canvasSize[1];
34745         }))
34746             .subscribe(function (delta) {
34747             _this._navigator.stateService.dolly(delta);
34748         });
34749     };
34750     EarthControlHandler.prototype._disable = function () {
34751         this._dollySubscription.unsubscribe();
34752         this._orbitSubscription.unsubscribe();
34753         this._preventDefaultSubscription.unsubscribe();
34754         this._truckSubscription.unsubscribe();
34755     };
34756     EarthControlHandler.prototype._getConfiguration = function () {
34757         return {};
34758     };
34759     EarthControlHandler.prototype._eventToViewport = function (event, element) {
34760         var previousCanvas = this._viewportCoords.canvasPosition(event, element);
34761         return this._viewportCoords.canvasToViewport(previousCanvas[0], previousCanvas[1], element);
34762     };
34763     EarthControlHandler.prototype._planeIntersection = function (event, planeNormal, planePoint, camera, element) {
34764         var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
34765         var direction = this._viewportCoords
34766             .unprojectFromCanvas(canvasX, canvasY, element, camera)
34767             .sub(camera.position)
34768             .normalize();
34769         if (Math.abs(this._spatial.angleToPlane(direction.toArray(), planeNormal)) < Math.PI / 90) {
34770             return null;
34771         }
34772         var l0 = camera.position.clone();
34773         var n = new THREE.Vector3().fromArray(planeNormal);
34774         var p0 = new THREE.Vector3().fromArray(planePoint);
34775         var d = new THREE.Vector3().subVectors(p0, l0).dot(n) / direction.clone().dot(n);
34776         var intersection = new THREE.Vector3().addVectors(l0, direction.multiplyScalar(d));
34777         if (this._viewportCoords.worldToCamera(intersection.toArray(), camera)[2] > 0) {
34778             return null;
34779         }
34780         return intersection;
34781     };
34782     return EarthControlHandler;
34783 }(Component_1.HandlerBase));
34784 exports.EarthControlHandler = EarthControlHandler;
34785 exports.default = EarthControlHandler;
34786
34787 },{"../../Component":291,"../../State":298,"rxjs":43,"rxjs/operators":241,"three":242}],342:[function(require,module,exports){
34788 "use strict";
34789 Object.defineProperty(exports, "__esModule", { value: true });
34790 var Geo_1 = require("../../../src/Geo");
34791 function basicBoundaryPoints(pointsPerSide) {
34792     var points = [];
34793     var os = [[0, 0], [1, 0], [1, 1], [0, 1]];
34794     var ds = [[1, 0], [0, 1], [-1, 0], [0, -1]];
34795     for (var side = 0; side < 4; ++side) {
34796         var o = os[side];
34797         var d = ds[side];
34798         for (var i = 0; i < pointsPerSide; ++i) {
34799             points.push([o[0] + d[0] * i / pointsPerSide,
34800                 o[1] + d[1] * i / pointsPerSide]);
34801         }
34802     }
34803     return points;
34804 }
34805 function insideViewport(x, y) {
34806     return x >= -1 && x <= 1 && y >= -1 && y <= 1;
34807 }
34808 function insideBasic(x, y) {
34809     return x >= 0 && x <= 1 && y >= 0 && y <= 1;
34810 }
34811 function viewportDistances(transform, perspective, viewportCoords) {
34812     var boundaryPointsBasic = basicBoundaryPoints(100);
34813     var boundaryPointsViewport = boundaryPointsBasic
34814         .map(function (basic) {
34815         return viewportCoords.basicToViewportSafe(basic[0], basic[1], transform, perspective);
34816     });
34817     var visibleBoundaryPoints = [];
34818     var viewportSides = [
34819         { x: -1, y: 1 },
34820         { x: 1, y: 1 },
34821         { x: 1, y: -1 },
34822         { x: -1, y: -1 }
34823     ];
34824     var intersections = [false, false, false, false];
34825     for (var i = 0; i < boundaryPointsViewport.length; i++) {
34826         var p1 = boundaryPointsViewport[i];
34827         var p2 = boundaryPointsViewport[(i + 1) % boundaryPointsViewport.length];
34828         if (p1 === null) {
34829             continue;
34830         }
34831         if (p2 === null) {
34832             if (insideViewport(p1[0], p1[1])) {
34833                 visibleBoundaryPoints.push(p1);
34834             }
34835             continue;
34836         }
34837         var x1 = p1[0], y1 = p1[1];
34838         var x2 = p2[0], y2 = p2[1];
34839         if (insideViewport(x1, y1)) {
34840             if (insideViewport(x2, y2)) {
34841                 visibleBoundaryPoints.push(p1);
34842             }
34843             else {
34844                 for (var side = 0; side < 4; side++) {
34845                     var s1 = { p1: { x: x1, y: y1 }, p2: { x: x2, y: y2 } };
34846                     var s2 = { p1: viewportSides[side], p2: viewportSides[(side + 1) % 4] };
34847                     var intersecting = Geo_1.Lines.segmentsIntersect(s1, s2);
34848                     if (intersecting) {
34849                         var intersection = Geo_1.Lines.segmentIntersection(s1, s2);
34850                         visibleBoundaryPoints.push(p1, [intersection.x, intersection.y]);
34851                         intersections[side] = true;
34852                     }
34853                 }
34854             }
34855         }
34856     }
34857     var _a = viewportCoords.viewportToBasic(-1, 1, transform, perspective), topLeftBasicX = _a[0], topLeftBasicY = _a[1];
34858     var _b = viewportCoords.viewportToBasic(1, 1, transform, perspective), topRightBasicX = _b[0], topRightBasicY = _b[1];
34859     var _c = viewportCoords.viewportToBasic(1, -1, transform, perspective), bottomRightBasicX = _c[0], bottomRightBasicY = _c[1];
34860     var _d = viewportCoords.viewportToBasic(-1, -1, transform, perspective), bottomLeftBasicX = _d[0], bottomLeftBasicY = _d[1];
34861     if (insideBasic(topLeftBasicX, topLeftBasicY)) {
34862         intersections[3] = intersections[0] = true;
34863     }
34864     if (insideBasic(topRightBasicX, topRightBasicY)) {
34865         intersections[0] = intersections[1] = true;
34866     }
34867     if (insideBasic(bottomRightBasicX, bottomRightBasicY)) {
34868         intersections[1] = intersections[2] = true;
34869     }
34870     if (insideBasic(bottomLeftBasicX, bottomLeftBasicY)) {
34871         intersections[2] = intersections[3] = true;
34872     }
34873     var maximums = [-1, -1, 1, 1];
34874     for (var _i = 0, visibleBoundaryPoints_1 = visibleBoundaryPoints; _i < visibleBoundaryPoints_1.length; _i++) {
34875         var visibleBoundaryPoint = visibleBoundaryPoints_1[_i];
34876         var x = visibleBoundaryPoint[0];
34877         var y = visibleBoundaryPoint[1];
34878         if (x > maximums[1]) {
34879             maximums[1] = x;
34880         }
34881         if (x < maximums[3]) {
34882             maximums[3] = x;
34883         }
34884         if (y > maximums[0]) {
34885             maximums[0] = y;
34886         }
34887         if (y < maximums[2]) {
34888             maximums[2] = y;
34889         }
34890     }
34891     var boundary = [1, 1, -1, -1];
34892     var distances = [];
34893     for (var side = 0; side < 4; side++) {
34894         if (intersections[side]) {
34895             distances.push(0);
34896             continue;
34897         }
34898         distances.push(Math.abs(boundary[side] - maximums[side]));
34899     }
34900     return distances;
34901 }
34902 exports.viewportDistances = viewportDistances;
34903
34904 },{"../../../src/Geo":294}],343:[function(require,module,exports){
34905 "use strict";
34906 var __extends = (this && this.__extends) || (function () {
34907     var extendStatics = function (d, b) {
34908         extendStatics = Object.setPrototypeOf ||
34909             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34910             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34911         return extendStatics(d, b);
34912     }
34913     return function (d, b) {
34914         extendStatics(d, b);
34915         function __() { this.constructor = d; }
34916         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34917     };
34918 })();
34919 Object.defineProperty(exports, "__esModule", { value: true });
34920 var Component_1 = require("../../Component");
34921 var Geo_1 = require("../../Geo");
34922 /**
34923  * @class MouseComponent
34924  *
34925  * @classdesc Component handling mouse and touch events for camera movement.
34926  *
34927  * To retrive and use the mouse component
34928  *
34929  * @example
34930  * ```
34931  * var viewer = new Mapillary.Viewer(
34932  *     "<element-id>",
34933  *     "<client-id>",
34934  *     "<my key>");
34935  *
34936  * var mouseComponent = viewer.getComponent("mouse");
34937  * ```
34938  */
34939 var MouseComponent = /** @class */ (function (_super) {
34940     __extends(MouseComponent, _super);
34941     /** @ignore */
34942     function MouseComponent(name, container, navigator) {
34943         var _this = _super.call(this, name, container, navigator) || this;
34944         var spatial = new Geo_1.Spatial();
34945         var viewportCoords = new Geo_1.ViewportCoords();
34946         _this._bounceHandler = new Component_1.BounceHandler(_this, container, navigator, viewportCoords, spatial);
34947         _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
34948         _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
34949         _this._earthControlHandler = new Component_1.EarthControlHandler(_this, container, navigator, viewportCoords, spatial);
34950         _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
34951         _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
34952         return _this;
34953     }
34954     Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
34955         /**
34956          * Get double click zoom.
34957          *
34958          * @returns {DoubleClickZoomHandler} The double click zoom handler.
34959          */
34960         get: function () {
34961             return this._doubleClickZoomHandler;
34962         },
34963         enumerable: true,
34964         configurable: true
34965     });
34966     Object.defineProperty(MouseComponent.prototype, "dragPan", {
34967         /**
34968          * Get drag pan.
34969          *
34970          * @returns {DragPanHandler} The drag pan handler.
34971          */
34972         get: function () {
34973             return this._dragPanHandler;
34974         },
34975         enumerable: true,
34976         configurable: true
34977     });
34978     Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
34979         /**
34980          * Get scroll zoom.
34981          *
34982          * @returns {ScrollZoomHandler} The scroll zoom handler.
34983          */
34984         get: function () {
34985             return this._scrollZoomHandler;
34986         },
34987         enumerable: true,
34988         configurable: true
34989     });
34990     Object.defineProperty(MouseComponent.prototype, "touchZoom", {
34991         /**
34992          * Get touch zoom.
34993          *
34994          * @returns {TouchZoomHandler} The touch zoom handler.
34995          */
34996         get: function () {
34997             return this._touchZoomHandler;
34998         },
34999         enumerable: true,
35000         configurable: true
35001     });
35002     MouseComponent.prototype._activate = function () {
35003         var _this = this;
35004         this._bounceHandler.enable();
35005         this._earthControlHandler.enable();
35006         this._configurationSubscription = this._configuration$
35007             .subscribe(function (configuration) {
35008             if (configuration.doubleClickZoom) {
35009                 _this._doubleClickZoomHandler.enable();
35010             }
35011             else {
35012                 _this._doubleClickZoomHandler.disable();
35013             }
35014             if (configuration.dragPan) {
35015                 _this._dragPanHandler.enable();
35016             }
35017             else {
35018                 _this._dragPanHandler.disable();
35019             }
35020             if (configuration.scrollZoom) {
35021                 _this._scrollZoomHandler.enable();
35022             }
35023             else {
35024                 _this._scrollZoomHandler.disable();
35025             }
35026             if (configuration.touchZoom) {
35027                 _this._touchZoomHandler.enable();
35028             }
35029             else {
35030                 _this._touchZoomHandler.disable();
35031             }
35032         });
35033         this._container.mouseService.claimMouse(this._name, 0);
35034     };
35035     MouseComponent.prototype._deactivate = function () {
35036         this._container.mouseService.unclaimMouse(this._name);
35037         this._configurationSubscription.unsubscribe();
35038         this._bounceHandler.disable();
35039         this._doubleClickZoomHandler.disable();
35040         this._dragPanHandler.disable();
35041         this._earthControlHandler.disable();
35042         this._scrollZoomHandler.disable();
35043         this._touchZoomHandler.disable();
35044     };
35045     MouseComponent.prototype._getDefaultConfiguration = function () {
35046         return { doubleClickZoom: false, dragPan: true, scrollZoom: true, touchZoom: true };
35047     };
35048     /** @inheritdoc */
35049     MouseComponent.componentName = "mouse";
35050     return MouseComponent;
35051 }(Component_1.Component));
35052 exports.MouseComponent = MouseComponent;
35053 Component_1.ComponentService.register(MouseComponent);
35054 exports.default = MouseComponent;
35055
35056 },{"../../Component":291,"../../Geo":294}],344:[function(require,module,exports){
35057 "use strict";
35058 var __extends = (this && this.__extends) || (function () {
35059     var extendStatics = function (d, b) {
35060         extendStatics = Object.setPrototypeOf ||
35061             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35062             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35063         return extendStatics(d, b);
35064     }
35065     return function (d, b) {
35066         extendStatics(d, b);
35067         function __() { this.constructor = d; }
35068         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35069     };
35070 })();
35071 Object.defineProperty(exports, "__esModule", { value: true });
35072 var operators_1 = require("rxjs/operators");
35073 var Component_1 = require("../../Component");
35074 /**
35075  * The `ScrollZoomHandler` allows the user to zoom the viewer image by scrolling.
35076  *
35077  * @example
35078  * ```
35079  * var mouseComponent = viewer.getComponent("mouse");
35080  *
35081  * mouseComponent.scrollZoom.disable();
35082  * mouseComponent.scrollZoom.enable();
35083  *
35084  * var isEnabled = mouseComponent.scrollZoom.isEnabled;
35085  * ```
35086  */
35087 var ScrollZoomHandler = /** @class */ (function (_super) {
35088     __extends(ScrollZoomHandler, _super);
35089     /** @ignore */
35090     function ScrollZoomHandler(component, container, navigator, viewportCoords) {
35091         var _this = _super.call(this, component, container, navigator) || this;
35092         _this._viewportCoords = viewportCoords;
35093         return _this;
35094     }
35095     ScrollZoomHandler.prototype._enable = function () {
35096         var _this = this;
35097         this._container.mouseService.claimWheel(this._component.name, 0);
35098         this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
35099             .subscribe(function (event) {
35100             event.preventDefault();
35101         });
35102         this._zoomSubscription = this._container.mouseService
35103             .filteredWheel$(this._component.name, this._container.mouseService.mouseWheel$).pipe(operators_1.withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
35104             return [w, f];
35105         }), operators_1.filter(function (args) {
35106             var state = args[1].state;
35107             return state.currentNode.fullPano || state.nodesAhead < 1;
35108         }), operators_1.map(function (args) {
35109             return args[0];
35110         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
35111             return [w, r, t];
35112         }))
35113             .subscribe(function (args) {
35114             var event = args[0];
35115             var render = args[1];
35116             var transform = args[2];
35117             var element = _this._container.element;
35118             var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
35119             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
35120             var reference = transform.projectBasic(unprojected.toArray());
35121             var deltaY = event.deltaY;
35122             if (event.deltaMode === 1) {
35123                 deltaY = 40 * deltaY;
35124             }
35125             else if (event.deltaMode === 2) {
35126                 deltaY = 800 * deltaY;
35127             }
35128             var canvasSize = _this._viewportCoords.containerToCanvas(element);
35129             var zoom = -3 * deltaY / canvasSize[1];
35130             _this._navigator.stateService.zoomIn(zoom, reference);
35131         });
35132     };
35133     ScrollZoomHandler.prototype._disable = function () {
35134         this._container.mouseService.unclaimWheel(this._component.name);
35135         this._preventDefaultSubscription.unsubscribe();
35136         this._zoomSubscription.unsubscribe();
35137         this._preventDefaultSubscription = null;
35138         this._zoomSubscription = null;
35139     };
35140     ScrollZoomHandler.prototype._getConfiguration = function (enable) {
35141         return { scrollZoom: enable };
35142     };
35143     return ScrollZoomHandler;
35144 }(Component_1.HandlerBase));
35145 exports.ScrollZoomHandler = ScrollZoomHandler;
35146 exports.default = ScrollZoomHandler;
35147
35148 },{"../../Component":291,"rxjs/operators":241}],345:[function(require,module,exports){
35149 "use strict";
35150 var __extends = (this && this.__extends) || (function () {
35151     var extendStatics = function (d, b) {
35152         extendStatics = Object.setPrototypeOf ||
35153             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35154             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35155         return extendStatics(d, b);
35156     }
35157     return function (d, b) {
35158         extendStatics(d, b);
35159         function __() { this.constructor = d; }
35160         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35161     };
35162 })();
35163 Object.defineProperty(exports, "__esModule", { value: true });
35164 var rxjs_1 = require("rxjs");
35165 var operators_1 = require("rxjs/operators");
35166 var Component_1 = require("../../Component");
35167 /**
35168  * The `TouchZoomHandler` allows the user to zoom the viewer image by pinching on a touchscreen.
35169  *
35170  * @example
35171  * ```
35172  * var mouseComponent = viewer.getComponent("mouse");
35173  *
35174  * mouseComponent.touchZoom.disable();
35175  * mouseComponent.touchZoom.enable();
35176  *
35177  * var isEnabled = mouseComponent.touchZoom.isEnabled;
35178  * ```
35179  */
35180 var TouchZoomHandler = /** @class */ (function (_super) {
35181     __extends(TouchZoomHandler, _super);
35182     /** @ignore */
35183     function TouchZoomHandler(component, container, navigator, viewportCoords) {
35184         var _this = _super.call(this, component, container, navigator) || this;
35185         _this._viewportCoords = viewportCoords;
35186         return _this;
35187     }
35188     TouchZoomHandler.prototype._enable = function () {
35189         var _this = this;
35190         this._preventDefaultSubscription = this._container.touchService.pinch$
35191             .subscribe(function (pinch) {
35192             pinch.originalEvent.preventDefault();
35193         });
35194         var pinchStarted$ = this._container.touchService.pinchStart$.pipe(operators_1.map(function (event) {
35195             return true;
35196         }));
35197         var pinchStopped$ = this._container.touchService.pinchEnd$.pipe(operators_1.map(function (event) {
35198             return false;
35199         }));
35200         this._activeSubscription = rxjs_1.merge(pinchStarted$, pinchStopped$)
35201             .subscribe(this._container.touchService.activate$);
35202         this._zoomSubscription = this._container.touchService.pinch$.pipe(operators_1.withLatestFrom(this._navigator.stateService.currentState$), operators_1.filter(function (args) {
35203             var state = args[1].state;
35204             return state.currentNode.fullPano || state.nodesAhead < 1;
35205         }), operators_1.map(function (args) {
35206             return args[0];
35207         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
35208             .subscribe(function (_a) {
35209             var pinch = _a[0], render = _a[1], transform = _a[2];
35210             var element = _this._container.element;
35211             var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
35212             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
35213             var reference = transform.projectBasic(unprojected.toArray());
35214             var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
35215             var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
35216             _this._navigator.stateService.zoomIn(zoom, reference);
35217         });
35218     };
35219     TouchZoomHandler.prototype._disable = function () {
35220         this._activeSubscription.unsubscribe();
35221         this._preventDefaultSubscription.unsubscribe();
35222         this._zoomSubscription.unsubscribe();
35223         this._preventDefaultSubscription = null;
35224         this._zoomSubscription = null;
35225     };
35226     TouchZoomHandler.prototype._getConfiguration = function (enable) {
35227         return { touchZoom: enable };
35228     };
35229     return TouchZoomHandler;
35230 }(Component_1.HandlerBase));
35231 exports.TouchZoomHandler = TouchZoomHandler;
35232 exports.default = TouchZoomHandler;
35233
35234 },{"../../Component":291,"rxjs":43,"rxjs/operators":241}],346:[function(require,module,exports){
35235 "use strict";
35236 Object.defineProperty(exports, "__esModule", { value: true });
35237 var Popup_1 = require("./popup/Popup");
35238 exports.Popup = Popup_1.Popup;
35239 var PopupComponent_1 = require("./PopupComponent");
35240 exports.PopupComponent = PopupComponent_1.PopupComponent;
35241
35242 },{"./PopupComponent":347,"./popup/Popup":348}],347:[function(require,module,exports){
35243 "use strict";
35244 var __extends = (this && this.__extends) || (function () {
35245     var extendStatics = function (d, b) {
35246         extendStatics = Object.setPrototypeOf ||
35247             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35248             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35249         return extendStatics(d, b);
35250     }
35251     return function (d, b) {
35252         extendStatics(d, b);
35253         function __() { this.constructor = d; }
35254         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35255     };
35256 })();
35257 Object.defineProperty(exports, "__esModule", { value: true });
35258 var rxjs_1 = require("rxjs");
35259 var operators_1 = require("rxjs/operators");
35260 var Component_1 = require("../../Component");
35261 var Utils_1 = require("../../Utils");
35262 /**
35263  * @class PopupComponent
35264  *
35265  * @classdesc Component for showing HTML popup objects.
35266  *
35267  * The `add` method is used for adding new popups. Popups are removed by reference.
35268  *
35269  * It is not possible to update popups in the set by updating any properties
35270  * directly on the popup object. Popups need to be replaced by
35271  * removing them and creating new ones with relevant changed properties and
35272  * adding those instead.
35273  *
35274  * Popups are only relevant to a single image because they are based on
35275  * 2D basic image coordinates. Popups related to a certain image should
35276  * be removed when the viewer is moved to another node.
35277  *
35278  * To retrive and use the popup component
35279  *
35280  * @example
35281  * ```
35282  * var viewer = new Mapillary.Viewer(
35283  *     "<element-id>",
35284  *     "<client-id>",
35285  *     "<my key>",
35286  *     { component: { popup: true } });
35287  *
35288  * var popupComponent = viewer.getComponent("popup");
35289  * ```
35290  */
35291 var PopupComponent = /** @class */ (function (_super) {
35292     __extends(PopupComponent, _super);
35293     /** @ignore */
35294     function PopupComponent(name, container, navigator, dom) {
35295         var _this = _super.call(this, name, container, navigator) || this;
35296         _this._dom = !!dom ? dom : new Utils_1.DOM();
35297         _this._popups = [];
35298         _this._added$ = new rxjs_1.Subject();
35299         _this._popups$ = new rxjs_1.Subject();
35300         return _this;
35301     }
35302     /**
35303      * Add popups to the popups set.
35304      *
35305      * @description Adding a new popup never replaces an old one
35306      * because they are stored by reference. Adding an already
35307      * existing popup has no effect.
35308      *
35309      * @param {Array<Popup>} popups - Popups to add.
35310      *
35311      * @example ```popupComponent.add([popup1, popup2]);```
35312      */
35313     PopupComponent.prototype.add = function (popups) {
35314         for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) {
35315             var popup = popups_1[_i];
35316             if (this._popups.indexOf(popup) !== -1) {
35317                 continue;
35318             }
35319             this._popups.push(popup);
35320             if (this._activated) {
35321                 popup.setParentContainer(this._popupContainer);
35322             }
35323         }
35324         this._added$.next(popups);
35325         this._popups$.next(this._popups);
35326     };
35327     /**
35328      * Returns an array of all popups.
35329      *
35330      * @example ```var popups = popupComponent.getAll();```
35331      */
35332     PopupComponent.prototype.getAll = function () {
35333         return this._popups.slice();
35334     };
35335     /**
35336      * Remove popups based on reference from the popup set.
35337      *
35338      * @param {Array<Popup>} popups - Popups to remove.
35339      *
35340      * @example ```popupComponent.remove([popup1, popup2]);```
35341      */
35342     PopupComponent.prototype.remove = function (popups) {
35343         for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) {
35344             var popup = popups_2[_i];
35345             this._remove(popup);
35346         }
35347         this._popups$.next(this._popups);
35348     };
35349     /**
35350      * Remove all popups from the popup set.
35351      *
35352      * @example ```popupComponent.removeAll();```
35353      */
35354     PopupComponent.prototype.removeAll = function () {
35355         for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) {
35356             var popup = _a[_i];
35357             this._remove(popup);
35358         }
35359         this._popups$.next(this._popups);
35360     };
35361     PopupComponent.prototype._activate = function () {
35362         var _this = this;
35363         this._popupContainer = this._dom.createElement("div", "mapillary-js-popup-container", this._container.element);
35364         for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
35365             var popup = _a[_i];
35366             popup.setParentContainer(this._popupContainer);
35367         }
35368         this._updateAllSubscription = rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
35369             .subscribe(function (_a) {
35370             var renderCamera = _a[0], size = _a[1], transform = _a[2];
35371             for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) {
35372                 var popup = _b[_i];
35373                 popup.update(renderCamera, size, transform);
35374             }
35375         });
35376         var changed$ = this._popups$.pipe(operators_1.startWith(this._popups), operators_1.switchMap(function (popups) {
35377             return rxjs_1.from(popups).pipe(operators_1.mergeMap(function (popup) {
35378                 return popup.changed$;
35379             }));
35380         }), operators_1.map(function (popup) {
35381             return [popup];
35382         }));
35383         this._updateAddedChangedSubscription = rxjs_1.merge(this._added$, changed$).pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$))
35384             .subscribe(function (_a) {
35385             var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3];
35386             for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) {
35387                 var popup = popups_3[_i];
35388                 popup.update(renderCamera, size, transform);
35389             }
35390         });
35391     };
35392     PopupComponent.prototype._deactivate = function () {
35393         this._updateAllSubscription.unsubscribe();
35394         this._updateAddedChangedSubscription.unsubscribe();
35395         for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
35396             var popup = _a[_i];
35397             popup.remove();
35398         }
35399         this._container.element.removeChild(this._popupContainer);
35400         delete this._popupContainer;
35401     };
35402     PopupComponent.prototype._getDefaultConfiguration = function () {
35403         return {};
35404     };
35405     PopupComponent.prototype._remove = function (popup) {
35406         var index = this._popups.indexOf(popup);
35407         if (index === -1) {
35408             return;
35409         }
35410         var removed = this._popups.splice(index, 1)[0];
35411         if (this._activated) {
35412             removed.remove();
35413         }
35414     };
35415     PopupComponent.componentName = "popup";
35416     return PopupComponent;
35417 }(Component_1.Component));
35418 exports.PopupComponent = PopupComponent;
35419 Component_1.ComponentService.register(PopupComponent);
35420 exports.default = PopupComponent;
35421
35422 },{"../../Component":291,"../../Utils":301,"rxjs":43,"rxjs/operators":241}],348:[function(require,module,exports){
35423 "use strict";
35424 Object.defineProperty(exports, "__esModule", { value: true });
35425 var rxjs_1 = require("rxjs");
35426 var Geo_1 = require("../../../Geo");
35427 var Utils_1 = require("../../../Utils");
35428 var Viewer_1 = require("../../../Viewer");
35429 /**
35430  * @class Popup
35431  *
35432  * @classdesc Popup instance for rendering custom HTML content
35433  * on top of images. Popups are based on 2D basic image coordinates
35434  * (see the {@link Viewer} class documentation for more information about coordinate
35435  * systems) and a certain popup is therefore only relevant to a single image.
35436  * Popups related to a certain image should be removed when moving
35437  * to another image.
35438  *
35439  * A popup must have both its content and its point or rect set to be
35440  * rendered. Popup options can not be updated after creation but the
35441  * basic point or rect as well as its content can be changed by calling
35442  * the appropriate methods.
35443  *
35444  * To create and add one `Popup` with default configuration
35445  * (tooltip visuals and automatic float) and one with specific options
35446  * use
35447  *
35448  * @example
35449  * ```
35450  * var defaultSpan = document.createElement('span');
35451  * defaultSpan.innerHTML = 'hello default';
35452  *
35453  * var defaultPopup = new Mapillary.PopupComponent.Popup();
35454  * defaultPopup.setDOMContent(defaultSpan);
35455  * defaultPopup.setBasicPoint([0.3, 0.3]);
35456  *
35457  * var cleanSpan = document.createElement('span');
35458  * cleanSpan.innerHTML = 'hello clean';
35459  *
35460  * var cleanPopup = new Mapillary.PopupComponent.Popup({
35461  *     clean: true,
35462  *     float: Mapillary.Alignment.Top,
35463  *     offset: 10,
35464  *     opacity: 0.7,
35465  * });
35466  *
35467  * cleanPopup.setDOMContent(cleanSpan);
35468  * cleanPopup.setBasicPoint([0.6, 0.6]);
35469  *
35470  * popupComponent.add([defaultPopup, cleanPopup]);
35471  * ```
35472  *
35473  * @description Implementation of API methods and API documentation inspired
35474  * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js
35475  */
35476 var Popup = /** @class */ (function () {
35477     function Popup(options, viewportCoords, dom) {
35478         this._options = {};
35479         options = !!options ? options : {};
35480         this._options.capturePointer = options.capturePointer === false ?
35481             options.capturePointer : true;
35482         this._options.clean = options.clean;
35483         this._options.float = options.float;
35484         this._options.offset = options.offset;
35485         this._options.opacity = options.opacity;
35486         this._options.position = options.position;
35487         this._dom = !!dom ? dom : new Utils_1.DOM();
35488         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
35489         this._notifyChanged$ = new rxjs_1.Subject();
35490     }
35491     Object.defineProperty(Popup.prototype, "changed$", {
35492         /**
35493          * @description Internal observable used by the component to
35494          * render the popup when its position or content has changed.
35495          * @ignore
35496          */
35497         get: function () {
35498             return this._notifyChanged$;
35499         },
35500         enumerable: true,
35501         configurable: true
35502     });
35503     /**
35504      * @description Internal method used by the component to
35505      * remove all references to the popup.
35506      * @ignore
35507      */
35508     Popup.prototype.remove = function () {
35509         if (this._content && this._content.parentNode) {
35510             this._content.parentNode.removeChild(this._content);
35511         }
35512         if (this._container) {
35513             this._container.parentNode.removeChild(this._container);
35514             delete this._container;
35515         }
35516         if (this._parentContainer) {
35517             delete this._parentContainer;
35518         }
35519     };
35520     /**
35521      * Sets a 2D basic image coordinates point to the popup's anchor, and
35522      * moves the popup to it.
35523      *
35524      * @description Overwrites any previously set point or rect.
35525      *
35526      * @param {Array<number>} basicPoint - Point in 2D basic image coordinates.
35527      *
35528      * @example
35529      * ```
35530      * var popup = new Mapillary.PopupComponent.Popup();
35531      * popup.setText('hello image');
35532      * popup.setBasicPoint([0.3, 0.3]);
35533      *
35534      * popupComponent.add([popup]);
35535      * ```
35536      */
35537     Popup.prototype.setBasicPoint = function (basicPoint) {
35538         this._point = basicPoint.slice();
35539         this._rect = null;
35540         this._notifyChanged$.next(this);
35541     };
35542     /**
35543      * Sets a 2D basic image coordinates rect to the popup's anchor, and
35544      * moves the popup to it.
35545      *
35546      * @description Overwrites any previously set point or rect.
35547      *
35548      * @param {Array<number>} basicRect - Rect in 2D basic image
35549      * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) .
35550      *
35551      * @example
35552      * ```
35553      * var popup = new Mapillary.PopupComponent.Popup();
35554      * popup.setText('hello image');
35555      * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]);
35556      *
35557      * popupComponent.add([popup]);
35558      * ```
35559      */
35560     Popup.prototype.setBasicRect = function (basicRect) {
35561         this._rect = basicRect.slice();
35562         this._point = null;
35563         this._notifyChanged$.next(this);
35564     };
35565     /**
35566      * Sets the popup's content to the element provided as a DOM node.
35567      *
35568      * @param {Node} htmlNode - A DOM node to be used as content for the popup.
35569      *
35570      * @example
35571      * ```
35572      * var div = document.createElement('div');
35573      * div.innerHTML = 'hello image';
35574      *
35575      * var popup = new Mapillary.PopupComponent.Popup();
35576      * popup.setDOMContent(div);
35577      * popup.setBasicPoint([0.3, 0.3]);
35578      *
35579      * popupComponent.add([popup]);
35580      * ```
35581      */
35582     Popup.prototype.setDOMContent = function (htmlNode) {
35583         if (this._content && this._content.parentNode) {
35584             this._content.parentNode.removeChild(this._content);
35585         }
35586         var className = "mapillaryjs-popup-content" +
35587             (this._options.clean === true ? "-clean" : "") +
35588             (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
35589         this._content = this._dom.createElement("div", className, this._container);
35590         this._content.appendChild(htmlNode);
35591         this._notifyChanged$.next(this);
35592     };
35593     /**
35594      * Sets the popup's content to the HTML provided as a string.
35595      *
35596      * @description This method does not perform HTML filtering or sanitization,
35597      * and must be used only with trusted content. Consider Popup#setText if the
35598      * content is an untrusted text string.
35599      *
35600      * @param {string} html - A string representing HTML content for the popup.
35601      *
35602      * @example
35603      * ```
35604      * var popup = new Mapillary.PopupComponent.Popup();
35605      * popup.setHTML('<div>hello image</div>');
35606      * popup.setBasicPoint([0.3, 0.3]);
35607      *
35608      * popupComponent.add([popup]);
35609      * ```
35610      */
35611     Popup.prototype.setHTML = function (html) {
35612         var frag = this._dom.document.createDocumentFragment();
35613         var temp = this._dom.createElement("body");
35614         var child;
35615         temp.innerHTML = html;
35616         while (true) {
35617             child = temp.firstChild;
35618             if (!child) {
35619                 break;
35620             }
35621             frag.appendChild(child);
35622         }
35623         this.setDOMContent(frag);
35624     };
35625     /**
35626      * Sets the popup's content to a string of text.
35627      *
35628      * @description This function creates a Text node in the DOM, so it cannot insert raw HTML.
35629      * Use this method for security against XSS if the popup content is user-provided.
35630      *
35631      * @param {string} text - Textual content for the popup.
35632      *
35633      * @example
35634      * ```
35635      * var popup = new Mapillary.PopupComponent.Popup();
35636      * popup.setText('hello image');
35637      * popup.setBasicPoint([0.3, 0.3]);
35638      *
35639      * popupComponent.add([popup]);
35640      * ```
35641      */
35642     Popup.prototype.setText = function (text) {
35643         this.setDOMContent(this._dom.document.createTextNode(text));
35644     };
35645     /**
35646      * @description Internal method for attaching the popup to
35647      * its parent container so that it is rendered in the DOM tree.
35648      * @ignore
35649      */
35650     Popup.prototype.setParentContainer = function (parentContainer) {
35651         this._parentContainer = parentContainer;
35652     };
35653     /**
35654      * @description Internal method for updating the rendered
35655      * position of the popup called by the popup component.
35656      * @ignore
35657      */
35658     Popup.prototype.update = function (renderCamera, size, transform) {
35659         var _a;
35660         if (!this._parentContainer || !this._content) {
35661             return;
35662         }
35663         if (!this._point && !this._rect) {
35664             return;
35665         }
35666         if (!this._container) {
35667             this._container = this._dom.createElement("div", "mapillaryjs-popup", this._parentContainer);
35668             var showTip = this._options.clean !== true &&
35669                 this._options.float !== Viewer_1.Alignment.Center;
35670             if (showTip) {
35671                 var tipClassName = "mapillaryjs-popup-tip" +
35672                     (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
35673                 this._tip = this._dom.createElement("div", tipClassName, this._container);
35674                 this._dom.createElement("div", "mapillaryjs-popup-tip-inner", this._tip);
35675             }
35676             this._container.appendChild(this._content);
35677             this._parentContainer.appendChild(this._container);
35678             if (this._options.opacity != null) {
35679                 this._container.style.opacity = this._options.opacity.toString();
35680             }
35681         }
35682         var pointPixel = null;
35683         var position = this._alignmentToPopupAligment(this._options.position);
35684         var float = this._alignmentToPopupAligment(this._options.float);
35685         var classList = this._container.classList;
35686         if (this._point != null) {
35687             pointPixel =
35688                 this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
35689         }
35690         else {
35691             var alignments = ["center", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"];
35692             var appliedPosition = null;
35693             for (var _i = 0, alignments_1 = alignments; _i < alignments_1.length; _i++) {
35694                 var alignment = alignments_1[_i];
35695                 if (classList.contains("mapillaryjs-popup-float-" + alignment)) {
35696                     appliedPosition = alignment;
35697                     break;
35698                 }
35699             }
35700             _a = this._rectToPixel(this._rect, position, appliedPosition, renderCamera, size, transform), pointPixel = _a[0], position = _a[1];
35701             if (!float) {
35702                 float = position;
35703             }
35704         }
35705         if (pointPixel == null) {
35706             this._container.style.display = "none";
35707             return;
35708         }
35709         this._container.style.display = "";
35710         if (!float) {
35711             var width = this._container.offsetWidth;
35712             var height = this._container.offsetHeight;
35713             var floats = this._pixelToFloats(pointPixel, size, width, height);
35714             float = floats.length === 0 ? "top" : floats.join("-");
35715         }
35716         var offset = this._normalizeOffset(this._options.offset);
35717         pointPixel = [pointPixel[0] + offset[float][0], pointPixel[1] + offset[float][1]];
35718         pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])];
35719         var floatTranslate = {
35720             "bottom": "translate(-50%,0)",
35721             "bottom-left": "translate(-100%,0)",
35722             "bottom-right": "translate(0,0)",
35723             "center": "translate(-50%,-50%)",
35724             "left": "translate(-100%,-50%)",
35725             "right": "translate(0,-50%)",
35726             "top": "translate(-50%,-100%)",
35727             "top-left": "translate(-100%,-100%)",
35728             "top-right": "translate(0,-100%)",
35729         };
35730         for (var key in floatTranslate) {
35731             if (!floatTranslate.hasOwnProperty(key)) {
35732                 continue;
35733             }
35734             classList.remove("mapillaryjs-popup-float-" + key);
35735         }
35736         classList.add("mapillaryjs-popup-float-" + float);
35737         this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)";
35738     };
35739     Popup.prototype._rectToPixel = function (rect, position, appliedPosition, renderCamera, size, transform) {
35740         if (!position) {
35741             var width = this._container.offsetWidth;
35742             var height = this._container.offsetHeight;
35743             var floatOffsets = {
35744                 "bottom": [0, height / 2],
35745                 "bottom-left": [-width / 2, height / 2],
35746                 "bottom-right": [width / 2, height / 2],
35747                 "left": [-width / 2, 0],
35748                 "right": [width / 2, 0],
35749                 "top": [0, -height / 2],
35750                 "top-left": [-width / 2, -height / 2],
35751                 "top-right": [width / 2, -height / 2],
35752             };
35753             var automaticPositions = ["top", "bottom", "left", "right"];
35754             var largestVisibleArea = [0, null, null];
35755             for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) {
35756                 var automaticPosition = automaticPositions_1[_i];
35757                 var autoPointBasic = this._pointFromRectPosition(rect, automaticPosition);
35758                 var autoPointPixel = this._viewportCoords.basicToCanvasSafe(autoPointBasic[0], autoPointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
35759                 if (autoPointPixel == null) {
35760                     continue;
35761                 }
35762                 var floatOffset = floatOffsets[automaticPosition];
35763                 var offsetedPosition = [autoPointPixel[0] + floatOffset[0], autoPointPixel[1] + floatOffset[1]];
35764                 var staticCoeff = appliedPosition != null && appliedPosition === automaticPosition ? 1 : 0.7;
35765                 var floats = this._pixelToFloats(offsetedPosition, size, width / staticCoeff, height / (2 * staticCoeff));
35766                 if (floats.length === 0 &&
35767                     autoPointPixel[0] > 0 &&
35768                     autoPointPixel[0] < size.width &&
35769                     autoPointPixel[1] > 0 &&
35770                     autoPointPixel[1] < size.height) {
35771                     return [autoPointPixel, automaticPosition];
35772                 }
35773                 var minX = Math.max(offsetedPosition[0] - width / 2, 0);
35774                 var maxX = Math.min(offsetedPosition[0] + width / 2, size.width);
35775                 var minY = Math.max(offsetedPosition[1] - height / 2, 0);
35776                 var maxY = Math.min(offsetedPosition[1] + height / 2, size.height);
35777                 var visibleX = Math.max(0, maxX - minX);
35778                 var visibleY = Math.max(0, maxY - minY);
35779                 var visibleArea = staticCoeff * visibleX * visibleY;
35780                 if (visibleArea > largestVisibleArea[0]) {
35781                     largestVisibleArea[0] = visibleArea;
35782                     largestVisibleArea[1] = autoPointPixel;
35783                     largestVisibleArea[2] = automaticPosition;
35784                 }
35785             }
35786             if (largestVisibleArea[0] > 0) {
35787                 return [largestVisibleArea[1], largestVisibleArea[2]];
35788             }
35789         }
35790         var pointBasic = this._pointFromRectPosition(rect, position);
35791         var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
35792         return [pointPixel, position != null ? position : "top"];
35793     };
35794     Popup.prototype._alignmentToPopupAligment = function (float) {
35795         switch (float) {
35796             case Viewer_1.Alignment.Bottom:
35797                 return "bottom";
35798             case Viewer_1.Alignment.BottomLeft:
35799                 return "bottom-left";
35800             case Viewer_1.Alignment.BottomRight:
35801                 return "bottom-right";
35802             case Viewer_1.Alignment.Center:
35803                 return "center";
35804             case Viewer_1.Alignment.Left:
35805                 return "left";
35806             case Viewer_1.Alignment.Right:
35807                 return "right";
35808             case Viewer_1.Alignment.Top:
35809                 return "top";
35810             case Viewer_1.Alignment.TopLeft:
35811                 return "top-left";
35812             case Viewer_1.Alignment.TopRight:
35813                 return "top-right";
35814             default:
35815                 return null;
35816         }
35817     };
35818     Popup.prototype._normalizeOffset = function (offset) {
35819         if (offset == null) {
35820             return this._normalizeOffset(0);
35821         }
35822         if (typeof offset === "number") {
35823             // input specifies a radius
35824             var sideOffset = offset;
35825             var sign = sideOffset >= 0 ? 1 : -1;
35826             var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(sideOffset, 2)));
35827             return {
35828                 "bottom": [0, sideOffset],
35829                 "bottom-left": [-cornerOffset, cornerOffset],
35830                 "bottom-right": [cornerOffset, cornerOffset],
35831                 "center": [0, 0],
35832                 "left": [-sideOffset, 0],
35833                 "right": [sideOffset, 0],
35834                 "top": [0, -sideOffset],
35835                 "top-left": [-cornerOffset, -cornerOffset],
35836                 "top-right": [cornerOffset, -cornerOffset],
35837             };
35838         }
35839         else {
35840             // input specifes a value for each position
35841             return {
35842                 "bottom": offset.bottom || [0, 0],
35843                 "bottom-left": offset.bottomLeft || [0, 0],
35844                 "bottom-right": offset.bottomRight || [0, 0],
35845                 "center": offset.center || [0, 0],
35846                 "left": offset.left || [0, 0],
35847                 "right": offset.right || [0, 0],
35848                 "top": offset.top || [0, 0],
35849                 "top-left": offset.topLeft || [0, 0],
35850                 "top-right": offset.topRight || [0, 0],
35851             };
35852         }
35853     };
35854     Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) {
35855         var floats = [];
35856         if (pointPixel[1] < height) {
35857             floats.push("bottom");
35858         }
35859         else if (pointPixel[1] > size.height - height) {
35860             floats.push("top");
35861         }
35862         if (pointPixel[0] < width / 2) {
35863             floats.push("right");
35864         }
35865         else if (pointPixel[0] > size.width - width / 2) {
35866             floats.push("left");
35867         }
35868         return floats;
35869     };
35870     Popup.prototype._pointFromRectPosition = function (rect, position) {
35871         var x0 = rect[0];
35872         var x1 = rect[0] < rect[2] ? rect[2] : rect[2] + 1;
35873         var y0 = rect[1];
35874         var y1 = rect[3];
35875         switch (position) {
35876             case "bottom":
35877                 return [(x0 + x1) / 2, y1];
35878             case "bottom-left":
35879                 return [x0, y1];
35880             case "bottom-right":
35881                 return [x1, y1];
35882             case "center":
35883                 return [(x0 + x1) / 2, (y0 + y1) / 2];
35884             case "left":
35885                 return [x0, (y0 + y1) / 2];
35886             case "right":
35887                 return [x1, (y0 + y1) / 2];
35888             case "top":
35889                 return [(x0 + x1) / 2, y0];
35890             case "top-left":
35891                 return [x0, y0];
35892             case "top-right":
35893                 return [x1, y0];
35894             default:
35895                 return [(x0 + x1) / 2, y1];
35896         }
35897     };
35898     return Popup;
35899 }());
35900 exports.Popup = Popup;
35901 exports.default = Popup;
35902
35903
35904 },{"../../../Geo":294,"../../../Utils":301,"../../../Viewer":302,"rxjs":43}],349:[function(require,module,exports){
35905 "use strict";
35906 var __extends = (this && this.__extends) || (function () {
35907     var extendStatics = function (d, b) {
35908         extendStatics = Object.setPrototypeOf ||
35909             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35910             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35911         return extendStatics(d, b);
35912     }
35913     return function (d, b) {
35914         extendStatics(d, b);
35915         function __() { this.constructor = d; }
35916         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35917     };
35918 })();
35919 Object.defineProperty(exports, "__esModule", { value: true });
35920 var rxjs_1 = require("rxjs");
35921 var operators_1 = require("rxjs/operators");
35922 var Component_1 = require("../../Component");
35923 var Edge_1 = require("../../Edge");
35924 var Graph_1 = require("../../Graph");
35925 /**
35926  * @class SequenceComponent
35927  * @classdesc Component showing navigation arrows for sequence directions
35928  * as well as playing button. Exposes an API to start and stop play.
35929  */
35930 var SequenceComponent = /** @class */ (function (_super) {
35931     __extends(SequenceComponent, _super);
35932     function SequenceComponent(name, container, navigator, renderer, scheduler) {
35933         var _this = _super.call(this, name, container, navigator) || this;
35934         _this._sequenceDOMRenderer = !!renderer ? renderer : new Component_1.SequenceDOMRenderer(container);
35935         _this._scheduler = scheduler;
35936         _this._containerWidth$ = new rxjs_1.Subject();
35937         _this._hoveredKeySubject$ = new rxjs_1.Subject();
35938         _this._hoveredKey$ = _this._hoveredKeySubject$.pipe(operators_1.share());
35939         _this._navigator.playService.playing$.pipe(operators_1.skip(1), operators_1.withLatestFrom(_this._configuration$))
35940             .subscribe(function (_a) {
35941             var playing = _a[0], configuration = _a[1];
35942             _this.fire(SequenceComponent.playingchanged, playing);
35943             if (playing === configuration.playing) {
35944                 return;
35945             }
35946             if (playing) {
35947                 _this.play();
35948             }
35949             else {
35950                 _this.stop();
35951             }
35952         });
35953         _this._navigator.playService.direction$.pipe(operators_1.skip(1), operators_1.withLatestFrom(_this._configuration$))
35954             .subscribe(function (_a) {
35955             var direction = _a[0], configuration = _a[1];
35956             if (direction !== configuration.direction) {
35957                 _this.setDirection(direction);
35958             }
35959         });
35960         return _this;
35961     }
35962     Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
35963         /**
35964          * Get hovered key observable.
35965          *
35966          * @description An observable emitting the key of the node for the direction
35967          * arrow that is being hovered. When the mouse leaves a direction arrow null
35968          * is emitted.
35969          *
35970          * @returns {Observable<string>}
35971          */
35972         get: function () {
35973             return this._hoveredKey$;
35974         },
35975         enumerable: true,
35976         configurable: true
35977     });
35978     /**
35979      * Start playing.
35980      *
35981      * @fires PlayerComponent#playingchanged
35982      */
35983     SequenceComponent.prototype.play = function () {
35984         this.configure({ playing: true });
35985     };
35986     /**
35987      * Stop playing.
35988      *
35989      * @fires PlayerComponent#playingchanged
35990      */
35991     SequenceComponent.prototype.stop = function () {
35992         this.configure({ playing: false });
35993     };
35994     /**
35995      * Set the direction to follow when playing.
35996      *
35997      * @param {EdgeDirection} direction - The direction that will be followed when playing.
35998      */
35999     SequenceComponent.prototype.setDirection = function (direction) {
36000         this.configure({ direction: direction });
36001     };
36002     /**
36003      * Set highlight key.
36004      *
36005      * @description The arrow pointing towards the node corresponding to the
36006      * highlight key will be highlighted.
36007      *
36008      * @param {string} highlightKey Key of node to be highlighted if existing.
36009      */
36010     SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
36011         this.configure({ highlightKey: highlightKey });
36012     };
36013     /**
36014      * Set max width of container element.
36015      *
36016      * @description Set max width of the container element holding
36017      * the sequence navigation elements. If the min width is larger than the
36018      * max width the min width value will be used.
36019      *
36020      * The container element is automatically resized when the resize
36021      * method on the Viewer class is called.
36022      *
36023      * @param {number} minWidth
36024      */
36025     SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
36026         this.configure({ maxWidth: maxWidth });
36027     };
36028     /**
36029      * Set min width of container element.
36030      *
36031      * @description Set min width of the container element holding
36032      * the sequence navigation elements. If the min width is larger than the
36033      * max width the min width value will be used.
36034      *
36035      * The container element is automatically resized when the resize
36036      * method on the Viewer class is called.
36037      *
36038      * @param {number} minWidth
36039      */
36040     SequenceComponent.prototype.setMinWidth = function (minWidth) {
36041         this.configure({ minWidth: minWidth });
36042     };
36043     /**
36044      * Set the value indicating whether the sequence UI elements should be visible.
36045      *
36046      * @param {boolean} visible
36047      */
36048     SequenceComponent.prototype.setVisible = function (visible) {
36049         this.configure({ visible: visible });
36050     };
36051     SequenceComponent.prototype._activate = function () {
36052         var _this = this;
36053         this._sequenceDOMRenderer.activate();
36054         var edgeStatus$ = this._navigator.stateService.currentNode$.pipe(operators_1.switchMap(function (node) {
36055             return node.sequenceEdges$;
36056         }), operators_1.publishReplay(1), operators_1.refCount());
36057         var sequence$ = this._navigator.stateService.currentNode$.pipe(operators_1.distinctUntilChanged(undefined, function (node) {
36058             return node.sequenceKey;
36059         }), operators_1.switchMap(function (node) {
36060             return rxjs_1.concat(rxjs_1.of(null), _this._navigator.graphService.cacheSequence$(node.sequenceKey).pipe(operators_1.retry(3), operators_1.catchError(function (e) {
36061                 console.error("Failed to cache sequence", e);
36062                 return rxjs_1.of(null);
36063             })));
36064         }), operators_1.startWith(null), operators_1.publishReplay(1), operators_1.refCount());
36065         this._sequenceSubscription = sequence$.subscribe();
36066         var rendererKey$ = this._sequenceDOMRenderer.index$.pipe(operators_1.withLatestFrom(sequence$), operators_1.map(function (_a) {
36067             var index = _a[0], sequence = _a[1];
36068             return sequence != null ? sequence.keys[index] : null;
36069         }), operators_1.filter(function (key) {
36070             return !!key;
36071         }), operators_1.distinctUntilChanged(), operators_1.publish(), operators_1.refCount());
36072         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) {
36073             return _this._navigator.moveToKey$(key).pipe(operators_1.catchError(function (e) {
36074                 return rxjs_1.empty();
36075             }));
36076         }))
36077             .subscribe();
36078         this._setSequenceGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.filter(function (changing) {
36079             return changing;
36080         }))
36081             .subscribe(function () {
36082             _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Sequence);
36083         });
36084         this._setSpatialGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.filter(function (changing) {
36085             return !changing;
36086         }))
36087             .subscribe(function () {
36088             _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Spatial);
36089         });
36090         this._navigator.graphService.graphMode$.pipe(operators_1.switchMap(function (mode) {
36091             return mode === Graph_1.GraphMode.Spatial ?
36092                 _this._navigator.stateService.currentNode$.pipe(operators_1.take(2)) :
36093                 rxjs_1.empty();
36094         }), operators_1.filter(function (node) {
36095             return !node.spatialEdges.cached;
36096         }), operators_1.switchMap(function (node) {
36097             return _this._navigator.graphService.cacheNode$(node.key).pipe(operators_1.catchError(function (e) {
36098                 return rxjs_1.empty();
36099             }));
36100         }))
36101             .subscribe();
36102         this._stopSubscription = this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.filter(function (changing) {
36103             return changing;
36104         }))
36105             .subscribe(function () {
36106             _this._navigator.playService.stop();
36107         });
36108         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) {
36109             var _b = _a[0], mode = _b[0], changing = _b[1], node = _a[1];
36110             return changing && mode === Graph_1.GraphMode.Sequence ?
36111                 _this._navigator.graphService.cacheSequenceNodes$(node.sequenceKey, node.key).pipe(operators_1.retry(3), operators_1.catchError(function (error) {
36112                     console.error("Failed to cache sequence nodes.", error);
36113                     return rxjs_1.empty();
36114                 })) :
36115                 rxjs_1.empty();
36116         }))
36117             .subscribe();
36118         var position$ = sequence$.pipe(operators_1.switchMap(function (sequence) {
36119             if (!sequence) {
36120                 return rxjs_1.of({ index: null, max: null });
36121             }
36122             var firstCurrentKey = true;
36123             return _this._sequenceDOMRenderer.changingPositionChanged$.pipe(operators_1.startWith(false), operators_1.distinctUntilChanged(), operators_1.switchMap(function (changingPosition) {
36124                 var skipCount = !changingPosition && firstCurrentKey ? 0 : 1;
36125                 firstCurrentKey = false;
36126                 return changingPosition ?
36127                     rendererKey$ :
36128                     _this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) {
36129                         return node.key;
36130                     }), operators_1.distinctUntilChanged(), operators_1.skip(skipCount));
36131             }), operators_1.map(function (key) {
36132                 var index = sequence.keys.indexOf(key);
36133                 if (index === -1) {
36134                     return { index: null, max: null };
36135                 }
36136                 return { index: index, max: sequence.keys.length - 1 };
36137             }));
36138         }));
36139         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) {
36140             var edgeStatus = _a[0], configuration = _a[1], containerWidth = _a[2], renderer = _a[3], speed = _a[4], position = _a[5];
36141             var vNode = _this._sequenceDOMRenderer
36142                 .render(edgeStatus, configuration, containerWidth, speed, position.index, position.max, _this, _this._navigator);
36143             return { name: _this._name, vnode: vNode };
36144         }))
36145             .subscribe(this._container.domRenderer.render$);
36146         this._setSpeedSubscription = this._sequenceDOMRenderer.speed$
36147             .subscribe(function (speed) {
36148             _this._navigator.playService.setSpeed(speed);
36149         });
36150         this._setDirectionSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
36151             return configuration.direction;
36152         }), operators_1.distinctUntilChanged())
36153             .subscribe(function (direction) {
36154             _this._navigator.playService.setDirection(direction);
36155         });
36156         this._containerWidthSubscription = rxjs_1.combineLatest(this._container.renderService.size$, this._configuration$.pipe(operators_1.distinctUntilChanged(function (value1, value2) {
36157             return value1[0] === value2[0] && value1[1] === value2[1];
36158         }, function (configuration) {
36159             return [configuration.minWidth, configuration.maxWidth];
36160         }))).pipe(operators_1.map(function (_a) {
36161             var size = _a[0], configuration = _a[1];
36162             return _this._sequenceDOMRenderer.getContainerWidth(size, configuration);
36163         }))
36164             .subscribe(this._containerWidth$);
36165         this._playingSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
36166             return configuration.playing;
36167         }), operators_1.distinctUntilChanged())
36168             .subscribe(function (playing) {
36169             if (playing) {
36170                 _this._navigator.playService.play();
36171             }
36172             else {
36173                 _this._navigator.playService.stop();
36174             }
36175         });
36176         this._hoveredKeySubscription = this._sequenceDOMRenderer.mouseEnterDirection$.pipe(operators_1.switchMap(function (direction) {
36177             var edgeTo$ = edgeStatus$.pipe(operators_1.map(function (edgeStatus) {
36178                 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
36179                     var edge = _a[_i];
36180                     if (edge.data.direction === direction) {
36181                         return edge.to;
36182                     }
36183                 }
36184                 return null;
36185             }), operators_1.takeUntil(_this._sequenceDOMRenderer.mouseLeaveDirection$));
36186             return rxjs_1.concat(edgeTo$, rxjs_1.of(null));
36187         }), operators_1.distinctUntilChanged())
36188             .subscribe(this._hoveredKeySubject$);
36189         this._emitHoveredKeySubscription = this._hoveredKey$
36190             .subscribe(function (key) {
36191             _this.fire(SequenceComponent.hoveredkeychanged, key);
36192         });
36193     };
36194     SequenceComponent.prototype._deactivate = function () {
36195         this._emitHoveredKeySubscription.unsubscribe();
36196         this._renderSubscription.unsubscribe();
36197         this._playingSubscription.unsubscribe();
36198         this._containerWidthSubscription.unsubscribe();
36199         this._hoveredKeySubscription.unsubscribe();
36200         this._setSpeedSubscription.unsubscribe();
36201         this._setDirectionSubscription.unsubscribe();
36202         this._setSequenceGraphModeSubscription.unsubscribe();
36203         this._setSpatialGraphModeSubscription.unsubscribe();
36204         this._sequenceSubscription.unsubscribe();
36205         this._moveSubscription.unsubscribe();
36206         this._cacheSequenceNodesSubscription.unsubscribe();
36207         this._stopSubscription.unsubscribe();
36208         this._sequenceDOMRenderer.deactivate();
36209     };
36210     SequenceComponent.prototype._getDefaultConfiguration = function () {
36211         return {
36212             direction: Edge_1.EdgeDirection.Next,
36213             maxWidth: 108,
36214             minWidth: 70,
36215             playing: false,
36216             visible: true,
36217         };
36218     };
36219     /** @inheritdoc */
36220     SequenceComponent.componentName = "sequence";
36221     /**
36222      * Event fired when playing starts or stops.
36223      *
36224      * @event SequenceComponent#playingchanged
36225      * @type {boolean} Indicates whether the player is playing.
36226      */
36227     SequenceComponent.playingchanged = "playingchanged";
36228     /**
36229      * Event fired when the hovered key changes.
36230      *
36231      * @description Emits the key of the node for the direction
36232      * arrow that is being hovered. When the mouse leaves a
36233      * direction arrow null is emitted.
36234      *
36235      * @event SequenceComponent#hoveredkeychanged
36236      * @type {string} The hovered key, null if no key is hovered.
36237      */
36238     SequenceComponent.hoveredkeychanged = "hoveredkeychanged";
36239     return SequenceComponent;
36240 }(Component_1.Component));
36241 exports.SequenceComponent = SequenceComponent;
36242 Component_1.ComponentService.register(SequenceComponent);
36243 exports.default = SequenceComponent;
36244
36245 },{"../../Component":291,"../../Edge":292,"../../Graph":295,"rxjs":43,"rxjs/operators":241}],350:[function(require,module,exports){
36246 "use strict";
36247 Object.defineProperty(exports, "__esModule", { value: true });
36248 var rxjs_1 = require("rxjs");
36249 var operators_1 = require("rxjs/operators");
36250 var vd = require("virtual-dom");
36251 var Component_1 = require("../../Component");
36252 var Edge_1 = require("../../Edge");
36253 var Error_1 = require("../../Error");
36254 var SequenceDOMRenderer = /** @class */ (function () {
36255     function SequenceDOMRenderer(container) {
36256         this._container = container;
36257         this._minThresholdWidth = 320;
36258         this._maxThresholdWidth = 1480;
36259         this._minThresholdHeight = 240;
36260         this._maxThresholdHeight = 820;
36261         this._stepperDefaultWidth = 108;
36262         this._controlsDefaultWidth = 88;
36263         this._defaultHeight = 30;
36264         this._expandControls = false;
36265         this._mode = Component_1.SequenceMode.Default;
36266         this._speed = 0.5;
36267         this._changingSpeed = false;
36268         this._index = null;
36269         this._changingPosition = false;
36270         this._mouseEnterDirection$ = new rxjs_1.Subject();
36271         this._mouseLeaveDirection$ = new rxjs_1.Subject();
36272         this._notifyChanged$ = new rxjs_1.Subject();
36273         this._notifyChangingPositionChanged$ = new rxjs_1.Subject();
36274         this._notifySpeedChanged$ = new rxjs_1.Subject();
36275         this._notifyIndexChanged$ = new rxjs_1.Subject();
36276     }
36277     Object.defineProperty(SequenceDOMRenderer.prototype, "changed$", {
36278         get: function () {
36279             return this._notifyChanged$;
36280         },
36281         enumerable: true,
36282         configurable: true
36283     });
36284     Object.defineProperty(SequenceDOMRenderer.prototype, "changingPositionChanged$", {
36285         get: function () {
36286             return this._notifyChangingPositionChanged$;
36287         },
36288         enumerable: true,
36289         configurable: true
36290     });
36291     Object.defineProperty(SequenceDOMRenderer.prototype, "speed$", {
36292         get: function () {
36293             return this._notifySpeedChanged$;
36294         },
36295         enumerable: true,
36296         configurable: true
36297     });
36298     Object.defineProperty(SequenceDOMRenderer.prototype, "index$", {
36299         get: function () {
36300             return this._notifyIndexChanged$;
36301         },
36302         enumerable: true,
36303         configurable: true
36304     });
36305     Object.defineProperty(SequenceDOMRenderer.prototype, "mouseEnterDirection$", {
36306         get: function () {
36307             return this._mouseEnterDirection$;
36308         },
36309         enumerable: true,
36310         configurable: true
36311     });
36312     Object.defineProperty(SequenceDOMRenderer.prototype, "mouseLeaveDirection$", {
36313         get: function () {
36314             return this._mouseLeaveDirection$;
36315         },
36316         enumerable: true,
36317         configurable: true
36318     });
36319     SequenceDOMRenderer.prototype.activate = function () {
36320         var _this = this;
36321         if (!!this._changingSubscription) {
36322             return;
36323         }
36324         this._changingSubscription = rxjs_1.merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$.pipe(operators_1.filter(function (touchEvent) {
36325             return touchEvent.touches.length === 0;
36326         })))
36327             .subscribe(function (event) {
36328             if (_this._changingSpeed) {
36329                 _this._changingSpeed = false;
36330             }
36331             if (_this._changingPosition) {
36332                 _this._setChangingPosition(false);
36333             }
36334         });
36335     };
36336     SequenceDOMRenderer.prototype.deactivate = function () {
36337         if (!this._changingSubscription) {
36338             return;
36339         }
36340         this._changingSpeed = false;
36341         this._changingPosition = false;
36342         this._expandControls = false;
36343         this._mode = Component_1.SequenceMode.Default;
36344         this._changingSubscription.unsubscribe();
36345         this._changingSubscription = null;
36346     };
36347     SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, speed, index, max, component, navigator) {
36348         if (configuration.visible === false) {
36349             return vd.h("div.SequenceContainer", {}, []);
36350         }
36351         var stepper = this._createStepper(edgeStatus, configuration, containerWidth, component, navigator);
36352         var controls = this._createSequenceControls(containerWidth);
36353         var playback = this._createPlaybackControls(containerWidth, speed, component, configuration);
36354         var timeline = this._createTimelineControls(containerWidth, index, max);
36355         return vd.h("div.SequenceContainer", [stepper, controls, playback, timeline]);
36356     };
36357     SequenceDOMRenderer.prototype.getContainerWidth = function (size, configuration) {
36358         var minWidth = configuration.minWidth;
36359         var maxWidth = configuration.maxWidth;
36360         if (maxWidth < minWidth) {
36361             maxWidth = minWidth;
36362         }
36363         var relativeWidth = (size.width - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
36364         var relativeHeight = (size.height - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
36365         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
36366         return minWidth + coeff * (maxWidth - minWidth);
36367     };
36368     SequenceDOMRenderer.prototype._createPositionInput = function (index, max) {
36369         var _this = this;
36370         this._index = index;
36371         var onPosition = function (e) {
36372             _this._index = Number(e.target.value);
36373             _this._notifyIndexChanged$.next(_this._index);
36374         };
36375         var boundingRect = this._container.domContainer.getBoundingClientRect();
36376         var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 65;
36377         var onStart = function (e) {
36378             e.stopPropagation();
36379             _this._setChangingPosition(true);
36380         };
36381         var onMove = function (e) {
36382             if (_this._changingPosition === true) {
36383                 e.stopPropagation();
36384             }
36385         };
36386         var onKeyDown = function (e) {
36387             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
36388                 e.key === "ArrowRight" || e.key === "ArrowUp") {
36389                 e.preventDefault();
36390             }
36391         };
36392         var positionInputProperties = {
36393             max: max != null ? max : 1,
36394             min: 0,
36395             onchange: onPosition,
36396             oninput: onPosition,
36397             onkeydown: onKeyDown,
36398             onmousedown: onStart,
36399             onmousemove: onMove,
36400             ontouchmove: onMove,
36401             ontouchstart: onStart,
36402             style: {
36403                 width: width + "px",
36404             },
36405             type: "range",
36406             value: index != null ? index : 0,
36407         };
36408         var disabled = index == null || max == null || max <= 1;
36409         if (disabled) {
36410             positionInputProperties.disabled = "true";
36411         }
36412         var positionInput = vd.h("input.SequencePosition", positionInputProperties, []);
36413         var positionContainerClass = disabled ? ".SequencePositionContainerDisabled" : ".SequencePositionContainer";
36414         return vd.h("div" + positionContainerClass, [positionInput]);
36415     };
36416     SequenceDOMRenderer.prototype._createSpeedInput = function (speed) {
36417         var _this = this;
36418         this._speed = speed;
36419         var onSpeed = function (e) {
36420             _this._speed = Number(e.target.value) / 1000;
36421             _this._notifySpeedChanged$.next(_this._speed);
36422         };
36423         var boundingRect = this._container.domContainer.getBoundingClientRect();
36424         var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 160;
36425         var onStart = function (e) {
36426             _this._changingSpeed = true;
36427             e.stopPropagation();
36428         };
36429         var onMove = function (e) {
36430             if (_this._changingSpeed === true) {
36431                 e.stopPropagation();
36432             }
36433         };
36434         var onKeyDown = function (e) {
36435             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
36436                 e.key === "ArrowRight" || e.key === "ArrowUp") {
36437                 e.preventDefault();
36438             }
36439         };
36440         var speedInput = vd.h("input.SequenceSpeed", {
36441             max: 1000,
36442             min: 0,
36443             onchange: onSpeed,
36444             oninput: onSpeed,
36445             onkeydown: onKeyDown,
36446             onmousedown: onStart,
36447             onmousemove: onMove,
36448             ontouchmove: onMove,
36449             ontouchstart: onStart,
36450             style: {
36451                 width: width + "px",
36452             },
36453             type: "range",
36454             value: 1000 * speed,
36455         }, []);
36456         return vd.h("div.SequenceSpeedContainer", [speedInput]);
36457     };
36458     SequenceDOMRenderer.prototype._createPlaybackControls = function (containerWidth, speed, component, configuration) {
36459         var _this = this;
36460         if (this._mode !== Component_1.SequenceMode.Playback) {
36461             return vd.h("div.SequencePlayback", []);
36462         }
36463         var switchIcon = vd.h("div.SequenceSwitchIcon.SequenceIconVisible", []);
36464         var direction = configuration.direction === Edge_1.EdgeDirection.Next ?
36465             Edge_1.EdgeDirection.Prev : Edge_1.EdgeDirection.Next;
36466         var playing = configuration.playing;
36467         var switchButtonProperties = {
36468             onclick: function () {
36469                 if (!playing) {
36470                     component.setDirection(direction);
36471                 }
36472             },
36473         };
36474         var switchButtonClassName = configuration.playing ? ".SequenceSwitchButtonDisabled" : ".SequenceSwitchButton";
36475         var switchButton = vd.h("div" + switchButtonClassName, switchButtonProperties, [switchIcon]);
36476         var slowIcon = vd.h("div.SequenceSlowIcon.SequenceIconVisible", []);
36477         var slowContainer = vd.h("div.SequenceSlowContainer", [slowIcon]);
36478         var fastIcon = vd.h("div.SequenceFastIcon.SequenceIconVisible", []);
36479         var fastContainer = vd.h("div.SequenceFastContainer", [fastIcon]);
36480         var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
36481         var closeButtonProperties = {
36482             onclick: function () {
36483                 _this._mode = Component_1.SequenceMode.Default;
36484                 _this._notifyChanged$.next(_this);
36485             },
36486         };
36487         var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
36488         var speedInput = this._createSpeedInput(speed);
36489         var playbackChildren = [switchButton, slowContainer, speedInput, fastContainer, closeButton];
36490         var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
36491         var playbackProperties = { style: { top: top + "px" } };
36492         return vd.h("div.SequencePlayback", playbackProperties, playbackChildren);
36493     };
36494     SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
36495         var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
36496             configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
36497         var onclick = configuration.playing ?
36498             function (e) { component.stop(); } :
36499             canPlay ? function (e) { component.play(); } : null;
36500         var buttonProperties = { onclick: onclick };
36501         var iconClass = configuration.playing ?
36502             "Stop" :
36503             canPlay ? "Play" : "PlayDisabled";
36504         var iconProperties = { className: iconClass };
36505         if (configuration.direction === Edge_1.EdgeDirection.Prev) {
36506             iconProperties.style = {
36507                 transform: "rotate(180deg) translate(50%, 50%)",
36508             };
36509         }
36510         var icon = vd.h("div.SequenceComponentIcon", iconProperties, []);
36511         var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
36512         return vd.h("div." + buttonClass, buttonProperties, [icon]);
36513     };
36514     SequenceDOMRenderer.prototype._createSequenceControls = function (containerWidth) {
36515         var _this = this;
36516         var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
36517         var expanderProperties = {
36518             onclick: function () {
36519                 _this._expandControls = !_this._expandControls;
36520                 _this._mode = Component_1.SequenceMode.Default;
36521                 _this._notifyChanged$.next(_this);
36522             },
36523             style: {
36524                 "border-bottom-right-radius": borderRadius + "px",
36525                 "border-top-right-radius": borderRadius + "px",
36526             },
36527         };
36528         var expanderBar = vd.h("div.SequenceExpanderBar", []);
36529         var expander = vd.h("div.SequenceExpanderButton", expanderProperties, [expanderBar]);
36530         var fastIconClassName = this._mode === Component_1.SequenceMode.Playback ?
36531             ".SequenceFastIconGrey.SequenceIconVisible" : ".SequenceFastIcon";
36532         var fastIcon = vd.h("div" + fastIconClassName, []);
36533         var playbackProperties = {
36534             onclick: function () {
36535                 _this._mode = _this._mode === Component_1.SequenceMode.Playback ?
36536                     Component_1.SequenceMode.Default :
36537                     Component_1.SequenceMode.Playback;
36538                 _this._notifyChanged$.next(_this);
36539             },
36540         };
36541         var playback = vd.h("div.SequencePlaybackButton", playbackProperties, [fastIcon]);
36542         var timelineIconClassName = this._mode === Component_1.SequenceMode.Timeline ?
36543             ".SequenceTimelineIconGrey.SequenceIconVisible" : ".SequenceTimelineIcon";
36544         var timelineIcon = vd.h("div" + timelineIconClassName, []);
36545         var timelineProperties = {
36546             onclick: function () {
36547                 _this._mode = _this._mode === Component_1.SequenceMode.Timeline ?
36548                     Component_1.SequenceMode.Default :
36549                     Component_1.SequenceMode.Timeline;
36550                 _this._notifyChanged$.next(_this);
36551             },
36552         };
36553         var timeline = vd.h("div.SequenceTimelineButton", timelineProperties, [timelineIcon]);
36554         var properties = {
36555             style: {
36556                 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
36557                 transform: "translate(" + (containerWidth / 2 + 2) + "px, 0)",
36558                 width: (this._controlsDefaultWidth / this._stepperDefaultWidth * containerWidth) + "px",
36559             },
36560         };
36561         var className = ".SequenceControls" +
36562             (this._expandControls ? ".SequenceControlsExpanded" : "");
36563         return vd.h("div" + className, properties, [playback, timeline, expander]);
36564     };
36565     SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, containerWidth, configuration, navigator) {
36566         var _this = this;
36567         var nextProperties = {
36568             onclick: nextKey != null ?
36569                 function (e) {
36570                     navigator.moveDir$(Edge_1.EdgeDirection.Next)
36571                         .subscribe(undefined, function (error) {
36572                         if (!(error instanceof Error_1.AbortMapillaryError)) {
36573                             console.error(error);
36574                         }
36575                     });
36576                 } :
36577                 null,
36578             onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
36579             onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
36580         };
36581         var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
36582         var prevProperties = {
36583             onclick: prevKey != null ?
36584                 function (e) {
36585                     navigator.moveDir$(Edge_1.EdgeDirection.Prev)
36586                         .subscribe(undefined, function (error) {
36587                         if (!(error instanceof Error_1.AbortMapillaryError)) {
36588                             console.error(error);
36589                         }
36590                     });
36591                 } :
36592                 null,
36593             onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
36594             onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
36595             style: {
36596                 "border-bottom-left-radius": borderRadius + "px",
36597                 "border-top-left-radius": borderRadius + "px",
36598             },
36599         };
36600         var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
36601         var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
36602         var nextIcon = vd.h("div.SequenceComponentIcon", []);
36603         var prevIcon = vd.h("div.SequenceComponentIcon", []);
36604         return [
36605             vd.h("div." + prevClass, prevProperties, [prevIcon]),
36606             vd.h("div." + nextClass, nextProperties, [nextIcon]),
36607         ];
36608     };
36609     SequenceDOMRenderer.prototype._createStepper = function (edgeStatus, configuration, containerWidth, component, navigator) {
36610         var nextKey = null;
36611         var prevKey = null;
36612         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
36613             var edge = _a[_i];
36614             if (edge.data.direction === Edge_1.EdgeDirection.Next) {
36615                 nextKey = edge.to;
36616             }
36617             if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
36618                 prevKey = edge.to;
36619             }
36620         }
36621         var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
36622         var buttons = this._createSequenceArrows(nextKey, prevKey, containerWidth, configuration, navigator);
36623         buttons.splice(1, 0, playingButton);
36624         var containerProperties = {
36625             oncontextmenu: function (event) { event.preventDefault(); },
36626             style: {
36627                 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
36628                 width: containerWidth + "px",
36629             },
36630         };
36631         return vd.h("div.SequenceStepper", containerProperties, buttons);
36632     };
36633     SequenceDOMRenderer.prototype._createTimelineControls = function (containerWidth, index, max) {
36634         var _this = this;
36635         if (this._mode !== Component_1.SequenceMode.Timeline) {
36636             return vd.h("div.SequenceTimeline", []);
36637         }
36638         var positionInput = this._createPositionInput(index, max);
36639         var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
36640         var closeButtonProperties = {
36641             onclick: function () {
36642                 _this._mode = Component_1.SequenceMode.Default;
36643                 _this._notifyChanged$.next(_this);
36644             },
36645         };
36646         var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
36647         var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
36648         var playbackProperties = { style: { top: top + "px" } };
36649         return vd.h("div.SequenceTimeline", playbackProperties, [positionInput, closeButton]);
36650     };
36651     SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
36652         var className = direction === Edge_1.EdgeDirection.Next ?
36653             "SequenceStepNext" :
36654             "SequenceStepPrev";
36655         if (key == null) {
36656             className += "Disabled";
36657         }
36658         else {
36659             if (highlightKey === key) {
36660                 className += "Highlight";
36661             }
36662         }
36663         return className;
36664     };
36665     SequenceDOMRenderer.prototype._setChangingPosition = function (value) {
36666         this._changingPosition = value;
36667         this._notifyChangingPositionChanged$.next(value);
36668     };
36669     return SequenceDOMRenderer;
36670 }());
36671 exports.SequenceDOMRenderer = SequenceDOMRenderer;
36672 exports.default = SequenceDOMRenderer;
36673
36674 },{"../../Component":291,"../../Edge":292,"../../Error":293,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],351:[function(require,module,exports){
36675 "use strict";
36676 Object.defineProperty(exports, "__esModule", { value: true });
36677 var SequenceMode;
36678 (function (SequenceMode) {
36679     SequenceMode[SequenceMode["Default"] = 0] = "Default";
36680     SequenceMode[SequenceMode["Playback"] = 1] = "Playback";
36681     SequenceMode[SequenceMode["Timeline"] = 2] = "Timeline";
36682 })(SequenceMode = exports.SequenceMode || (exports.SequenceMode = {}));
36683 exports.default = SequenceMode;
36684
36685 },{}],352:[function(require,module,exports){
36686 "use strict";
36687 Object.defineProperty(exports, "__esModule", { value: true });
36688
36689 var path = require("path");
36690 var Shaders = /** @class */ (function () {
36691     function Shaders() {
36692     }
36693     Shaders.equirectangular = {
36694         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}",
36695         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}",
36696     };
36697     Shaders.equirectangularCurtain = {
36698         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}",
36699         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}",
36700     };
36701     Shaders.perspective = {
36702         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}",
36703         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}",
36704     };
36705     Shaders.perspectiveCurtain = {
36706         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",
36707         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}",
36708     };
36709     Shaders.fisheye = {
36710         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;\n    float y = vRstq.y;\n    float z = vRstq.z;\n\n    float r = sqrt(x * x + y * y);\n    float theta = atan(r, z);\n\n    if (radial_peak > 0. && theta > radial_peak) {\n        theta = radial_peak;\n    }\n\n    float theta2 = theta * theta;\n    float theta_d = theta * (1.0 + theta2 * (k1 + theta2 * k2));\n    float s = focal * theta_d / r;\n\n    float u = scale_x * s * x + 0.5;\n    float v = -scale_y * s * 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}\n",
36711         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}",
36712     };
36713     Shaders.fisheyeCurtain = {
36714         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;\n    float y = vRstq.y;\n    float z = vRstq.z;\n\n    float r2 = sqrt(x * x + y * y);\n    float theta = atan(r2, z);\n\n    if (radial_peak > 0. && theta > radial_peak) {\n        theta = radial_peak;\n    }\n\n    float theta2 = theta * theta;\n    float theta_d = theta * (1.0 + theta2 * (k1 + theta2 * k2));\n    float s = focal * theta_d / r2;\n\n    float u = scale_x * s * x + 0.5;\n    float v = -scale_y * s * 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",
36715         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}",
36716     };
36717     Shaders.perspectiveDistorted = {
36718         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",
36719         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",
36720     };
36721     Shaders.perspectiveDistortedCurtain = {
36722         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",
36723         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",
36724     };
36725     return Shaders;
36726 }());
36727 exports.Shaders = Shaders;
36728
36729
36730 },{"path":39}],353:[function(require,module,exports){
36731 "use strict";
36732 var __extends = (this && this.__extends) || (function () {
36733     var extendStatics = function (d, b) {
36734         extendStatics = Object.setPrototypeOf ||
36735             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
36736             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
36737         return extendStatics(d, b);
36738     }
36739     return function (d, b) {
36740         extendStatics(d, b);
36741         function __() { this.constructor = d; }
36742         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36743     };
36744 })();
36745 Object.defineProperty(exports, "__esModule", { value: true });
36746 var rxjs_1 = require("rxjs");
36747 var operators_1 = require("rxjs/operators");
36748 var Component_1 = require("../../Component");
36749 var Geo_1 = require("../../Geo");
36750 var State_1 = require("../../State");
36751 var Render_1 = require("../../Render");
36752 var Tiles_1 = require("../../Tiles");
36753 var Utils_1 = require("../../Utils");
36754 /**
36755  * @class SliderComponent
36756  *
36757  * @classdesc Component for comparing pairs of images. Renders
36758  * a slider for adjusting the curtain of the first image.
36759  *
36760  * Deactivate the sequence, direction and image plane
36761  * components when activating the slider component to avoid
36762  * interfering UI elements.
36763  *
36764  * To retrive and use the slider component
36765  *
36766  * @example
36767  * ```
36768  * var viewer = new Mapillary.Viewer(
36769  *     "<element-id>",
36770  *     "<client-id>",
36771  *     "<my key>");
36772  *
36773  * viewer.deactivateComponent("imagePlane");
36774  * viewer.deactivateComponent("direction");
36775  * viewer.deactivateComponent("sequence");
36776  *
36777  * viewer.activateComponent("slider");
36778  *
36779  * var sliderComponent = viewer.getComponent("slider");
36780  * ```
36781  */
36782 var SliderComponent = /** @class */ (function (_super) {
36783     __extends(SliderComponent, _super);
36784     /** @ignore */
36785     function SliderComponent(name, container, navigator, viewportCoords) {
36786         var _this = _super.call(this, name, container, navigator) || this;
36787         _this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
36788         _this._domRenderer = new Component_1.SliderDOMRenderer(container);
36789         _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
36790         _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
36791         _this._spatial = new Geo_1.Spatial();
36792         _this._glRendererOperation$ = new rxjs_1.Subject();
36793         _this._glRendererCreator$ = new rxjs_1.Subject();
36794         _this._glRendererDisposer$ = new rxjs_1.Subject();
36795         _this._glRenderer$ = _this._glRendererOperation$.pipe(operators_1.scan(function (glRenderer, operation) {
36796             return operation(glRenderer);
36797         }, null), operators_1.filter(function (glRenderer) {
36798             return glRenderer != null;
36799         }), operators_1.distinctUntilChanged(undefined, function (glRenderer) {
36800             return glRenderer.frameId;
36801         }));
36802         _this._glRendererCreator$.pipe(operators_1.map(function () {
36803             return function (glRenderer) {
36804                 if (glRenderer != null) {
36805                     throw new Error("Multiple slider states can not be created at the same time");
36806                 }
36807                 return new Component_1.SliderGLRenderer();
36808             };
36809         }))
36810             .subscribe(_this._glRendererOperation$);
36811         _this._glRendererDisposer$.pipe(operators_1.map(function () {
36812             return function (glRenderer) {
36813                 glRenderer.dispose();
36814                 return null;
36815             };
36816         }))
36817             .subscribe(_this._glRendererOperation$);
36818         return _this;
36819     }
36820     /**
36821      * Set the initial position.
36822      *
36823      * @description Configures the intial position of the slider.
36824      * The inital position value will be used when the component
36825      * is activated.
36826      *
36827      * @param {number} initialPosition - Initial slider position.
36828      */
36829     SliderComponent.prototype.setInitialPosition = function (initialPosition) {
36830         this.configure({ initialPosition: initialPosition });
36831     };
36832     /**
36833      * Set the image keys.
36834      *
36835      * @description Configures the component to show the image
36836      * planes for the supplied image keys.
36837      *
36838      * @param {ISliderKeys} keys - Slider keys object specifying
36839      * the images to be shown in the foreground and the background.
36840      */
36841     SliderComponent.prototype.setKeys = function (keys) {
36842         this.configure({ keys: keys });
36843     };
36844     /**
36845      * Set the slider mode.
36846      *
36847      * @description Configures the mode for transitions between
36848      * image pairs.
36849      *
36850      * @param {SliderMode} mode - Slider mode to be set.
36851      */
36852     SliderComponent.prototype.setSliderMode = function (mode) {
36853         this.configure({ mode: mode });
36854     };
36855     /**
36856      * Set the value controlling if the slider is visible.
36857      *
36858      * @param {boolean} sliderVisible - Value indicating if
36859      * the slider should be visible or not.
36860      */
36861     SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
36862         this.configure({ sliderVisible: sliderVisible });
36863     };
36864     SliderComponent.prototype._activate = function () {
36865         var _this = this;
36866         this._modeSubcription = this._domRenderer.mode$
36867             .subscribe(function (mode) {
36868             _this.setSliderMode(mode);
36869         });
36870         this._glRenderSubscription = this._glRenderer$.pipe(operators_1.map(function (glRenderer) {
36871             var renderHash = {
36872                 name: _this._name,
36873                 render: {
36874                     frameId: glRenderer.frameId,
36875                     needsRender: glRenderer.needsRender,
36876                     render: glRenderer.render.bind(glRenderer),
36877                     stage: Render_1.GLRenderStage.Background,
36878                 },
36879             };
36880             return renderHash;
36881         }))
36882             .subscribe(this._container.glRenderer.render$);
36883         var position$ = rxjs_1.concat(this.configuration$.pipe(operators_1.map(function (configuration) {
36884             return configuration.initialPosition != null ?
36885                 configuration.initialPosition : 1;
36886         }), operators_1.first()), this._domRenderer.position$);
36887         var mode$ = this.configuration$.pipe(operators_1.map(function (configuration) {
36888             return configuration.mode;
36889         }), operators_1.distinctUntilChanged());
36890         var motionless$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
36891             return frame.state.motionless;
36892         }), operators_1.distinctUntilChanged());
36893         var fullPano$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
36894             return frame.state.currentNode.fullPano;
36895         }), operators_1.distinctUntilChanged());
36896         var sliderVisible$ = rxjs_1.combineLatest(this._configuration$.pipe(operators_1.map(function (configuration) {
36897             return configuration.sliderVisible;
36898         })), this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
36899             return !(frame.state.currentNode == null ||
36900                 frame.state.previousNode == null ||
36901                 (frame.state.currentNode.pano && !frame.state.currentNode.fullPano) ||
36902                 (frame.state.previousNode.pano && !frame.state.previousNode.fullPano) ||
36903                 (frame.state.currentNode.fullPano && !frame.state.previousNode.fullPano));
36904         }), operators_1.distinctUntilChanged())).pipe(operators_1.map(function (_a) {
36905             var sliderVisible = _a[0], enabledState = _a[1];
36906             return sliderVisible && enabledState;
36907         }), operators_1.distinctUntilChanged());
36908         this._waitSubscription = rxjs_1.combineLatest(mode$, motionless$, fullPano$, sliderVisible$).pipe(operators_1.withLatestFrom(this._navigator.stateService.state$))
36909             .subscribe(function (_a) {
36910             var _b = _a[0], mode = _b[0], motionless = _b[1], fullPano = _b[2], sliderVisible = _b[3], state = _a[1];
36911             var interactive = sliderVisible &&
36912                 (motionless || mode === Component_1.SliderMode.Stationary || fullPano);
36913             if (interactive && state !== State_1.State.WaitingInteractively) {
36914                 _this._navigator.stateService.waitInteractively();
36915             }
36916             else if (!interactive && state !== State_1.State.Waiting) {
36917                 _this._navigator.stateService.wait();
36918             }
36919         });
36920         this._moveSubscription = rxjs_1.combineLatest(position$, mode$, motionless$, fullPano$, sliderVisible$)
36921             .subscribe(function (_a) {
36922             var position = _a[0], mode = _a[1], motionless = _a[2], fullPano = _a[3], sliderVisible = _a[4];
36923             if (motionless || mode === Component_1.SliderMode.Stationary || fullPano) {
36924                 _this._navigator.stateService.moveTo(1);
36925             }
36926             else {
36927                 _this._navigator.stateService.moveTo(position);
36928             }
36929         });
36930         this._domRenderSubscription = rxjs_1.combineLatest(position$, mode$, motionless$, fullPano$, sliderVisible$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
36931             var position = _a[0], mode = _a[1], motionless = _a[2], fullPano = _a[3], sliderVisible = _a[4], size = _a[5];
36932             return {
36933                 name: _this._name,
36934                 vnode: _this._domRenderer.render(position, mode, motionless, fullPano, sliderVisible),
36935             };
36936         }))
36937             .subscribe(this._container.domRenderer.render$);
36938         this._glRendererCreator$.next(null);
36939         this._updateCurtainSubscription = rxjs_1.combineLatest(position$, fullPano$, sliderVisible$, this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$).pipe(operators_1.map(function (_a) {
36940             var position = _a[0], fullPano = _a[1], visible = _a[2], render = _a[3], transform = _a[4];
36941             if (!fullPano) {
36942                 return visible ? position : 1;
36943             }
36944             var basicMin = _this._viewportCoords.viewportToBasic(-1.15, 0, transform, render.perspective);
36945             var basicMax = _this._viewportCoords.viewportToBasic(1.15, 0, transform, render.perspective);
36946             var shiftedMax = basicMax[0] < basicMin[0] ? basicMax[0] + 1 : basicMax[0];
36947             var basicPosition = basicMin[0] + position * (shiftedMax - basicMin[0]);
36948             return basicPosition > 1 ? basicPosition - 1 : basicPosition;
36949         }), operators_1.map(function (position) {
36950             return function (glRenderer) {
36951                 glRenderer.updateCurtain(position);
36952                 return glRenderer;
36953             };
36954         }))
36955             .subscribe(this._glRendererOperation$);
36956         this._stateSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentState$, mode$).pipe(operators_1.map(function (_a) {
36957             var frame = _a[0], mode = _a[1];
36958             return function (glRenderer) {
36959                 glRenderer.update(frame, mode);
36960                 return glRenderer;
36961             };
36962         }))
36963             .subscribe(this._glRendererOperation$);
36964         this._setKeysSubscription = this._configuration$.pipe(operators_1.filter(function (configuration) {
36965             return configuration.keys != null;
36966         }), operators_1.switchMap(function (configuration) {
36967             return rxjs_1.zip(rxjs_1.zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground)).pipe(operators_1.map(function (nodes) {
36968                 return { background: nodes[0], foreground: nodes[1] };
36969             })), _this._navigator.stateService.currentState$.pipe(operators_1.first())).pipe(operators_1.map(function (nf) {
36970                 return { nodes: nf[0], state: nf[1].state };
36971             }));
36972         }))
36973             .subscribe(function (co) {
36974             if (co.state.currentNode != null &&
36975                 co.state.previousNode != null &&
36976                 co.state.currentNode.key === co.nodes.foreground.key &&
36977                 co.state.previousNode.key === co.nodes.background.key) {
36978                 return;
36979             }
36980             if (co.state.currentNode.key === co.nodes.background.key) {
36981                 _this._navigator.stateService.setNodes([co.nodes.foreground]);
36982                 return;
36983             }
36984             if (co.state.currentNode.key === co.nodes.foreground.key &&
36985                 co.state.trajectory.length === 1) {
36986                 _this._navigator.stateService.prependNodes([co.nodes.background]);
36987                 return;
36988             }
36989             _this._navigator.stateService.setNodes([co.nodes.background]);
36990             _this._navigator.stateService.setNodes([co.nodes.foreground]);
36991         }, function (e) {
36992             console.error(e);
36993         });
36994         var previousNode$ = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
36995             return frame.state.previousNode;
36996         }), operators_1.filter(function (node) {
36997             return node != null;
36998         }), operators_1.distinctUntilChanged(undefined, function (node) {
36999             return node.key;
37000         }));
37001         var textureProvider$ = this._navigator.stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
37002             return frame.state.currentNode.key;
37003         }), operators_1.withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), operators_1.map(function (_a) {
37004             var frame = _a[0], renderer = _a[1], size = _a[2];
37005             var state = frame.state;
37006             var viewportSize = Math.max(size.width, size.height);
37007             var currentNode = state.currentNode;
37008             var currentTransform = state.currentTransform;
37009             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
37010             return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
37011         }), operators_1.publishReplay(1), operators_1.refCount());
37012         this._textureProviderSubscription = textureProvider$.subscribe(function () { });
37013         this._setTextureProviderSubscription = textureProvider$.pipe(operators_1.map(function (provider) {
37014             return function (renderer) {
37015                 renderer.setTextureProvider(provider.key, provider);
37016                 return renderer;
37017             };
37018         }))
37019             .subscribe(this._glRendererOperation$);
37020         this._setTileSizeSubscription = this._container.renderService.size$.pipe(operators_1.switchMap(function (size) {
37021             return rxjs_1.combineLatest(textureProvider$, rxjs_1.of(size)).pipe(operators_1.first());
37022         }))
37023             .subscribe(function (_a) {
37024             var provider = _a[0], size = _a[1];
37025             var viewportSize = Math.max(size.width, size.height);
37026             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
37027             provider.setTileSize(tileSize);
37028         });
37029         this._abortTextureProviderSubscription = textureProvider$.pipe(operators_1.pairwise())
37030             .subscribe(function (pair) {
37031             var previous = pair[0];
37032             previous.abort();
37033         });
37034         var roiTrigger$ = rxjs_1.combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(operators_1.debounceTime(250))).pipe(operators_1.map(function (_a) {
37035             var camera = _a[0], size = _a[1];
37036             return [
37037                 camera.camera.position.clone(),
37038                 camera.camera.lookat.clone(),
37039                 camera.zoom.valueOf(),
37040                 size.height.valueOf(),
37041                 size.width.valueOf()
37042             ];
37043         }), operators_1.pairwise(), operators_1.skipWhile(function (pls) {
37044             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
37045         }), operators_1.map(function (pls) {
37046             var samePosition = pls[0][0].equals(pls[1][0]);
37047             var sameLookat = pls[0][1].equals(pls[1][1]);
37048             var sameZoom = pls[0][2] === pls[1][2];
37049             var sameHeight = pls[0][3] === pls[1][3];
37050             var sameWidth = pls[0][4] === pls[1][4];
37051             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
37052         }), operators_1.distinctUntilChanged(), operators_1.filter(function (stalled) {
37053             return stalled;
37054         }), operators_1.switchMap(function (stalled) {
37055             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.first());
37056         }), operators_1.withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$));
37057         this._setRegionOfInterestSubscription = textureProvider$.pipe(operators_1.switchMap(function (provider) {
37058             return roiTrigger$.pipe(operators_1.map(function (_a) {
37059                 var camera = _a[0], size = _a[1], transform = _a[2];
37060                 return [
37061                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
37062                     provider,
37063                 ];
37064             }));
37065         }), operators_1.filter(function (args) {
37066             return !args[1].disposed;
37067         }))
37068             .subscribe(function (args) {
37069             var roi = args[0];
37070             var provider = args[1];
37071             provider.setRegionOfInterest(roi);
37072         });
37073         var hasTexture$ = textureProvider$.pipe(operators_1.switchMap(function (provider) {
37074             return provider.hasTexture$;
37075         }), operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
37076         this._hasTextureSubscription = hasTexture$.subscribe(function () { });
37077         var nodeImage$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
37078             return frame.state.nodesAhead === 0;
37079         }), operators_1.map(function (frame) {
37080             return frame.state.currentNode;
37081         }), operators_1.distinctUntilChanged(undefined, function (node) {
37082             return node.key;
37083         }), operators_1.debounceTime(1000), operators_1.withLatestFrom(hasTexture$), operators_1.filter(function (args) {
37084             return !args[1];
37085         }), operators_1.map(function (args) {
37086             return args[0];
37087         }), operators_1.filter(function (node) {
37088             return node.pano ?
37089                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
37090                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
37091         }), operators_1.switchMap(function (node) {
37092             var baseImageSize = node.pano ?
37093                 Utils_1.Settings.basePanoramaSize :
37094                 Utils_1.Settings.baseImageSize;
37095             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
37096                 return rxjs_1.empty();
37097             }
37098             var image$ = node
37099                 .cacheImage$(Utils_1.Settings.maxImageSize).pipe(operators_1.map(function (n) {
37100                 return [n.image, n];
37101             }));
37102             return image$.pipe(operators_1.takeUntil(hasTexture$.pipe(operators_1.filter(function (hasTexture) {
37103                 return hasTexture;
37104             }))), operators_1.catchError(function (error, caught) {
37105                 console.error("Failed to fetch high res image (" + node.key + ")", error);
37106                 return rxjs_1.empty();
37107             }));
37108         })).pipe(operators_1.publish(), operators_1.refCount());
37109         this._updateBackgroundSubscription = nodeImage$.pipe(operators_1.withLatestFrom(textureProvider$))
37110             .subscribe(function (args) {
37111             if (args[0][1].key !== args[1].key ||
37112                 args[1].disposed) {
37113                 return;
37114             }
37115             args[1].updateBackground(args[0][0]);
37116         });
37117         this._updateTextureImageSubscription = nodeImage$.pipe(operators_1.map(function (imn) {
37118             return function (renderer) {
37119                 renderer.updateTextureImage(imn[0], imn[1]);
37120                 return renderer;
37121             };
37122         }))
37123             .subscribe(this._glRendererOperation$);
37124         var textureProviderPrev$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
37125             return !!frame.state.previousNode;
37126         }), operators_1.distinctUntilChanged(undefined, function (frame) {
37127             return frame.state.previousNode.key;
37128         }), operators_1.withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), operators_1.map(function (_a) {
37129             var frame = _a[0], renderer = _a[1], size = _a[2];
37130             var state = frame.state;
37131             var viewportSize = Math.max(size.width, size.height);
37132             var previousNode = state.previousNode;
37133             var previousTransform = state.previousTransform;
37134             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
37135             return new Tiles_1.TextureProvider(previousNode.key, previousTransform.basicWidth, previousTransform.basicHeight, tileSize, previousNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
37136         }), operators_1.publishReplay(1), operators_1.refCount());
37137         this._textureProviderSubscriptionPrev = textureProviderPrev$.subscribe(function () { });
37138         this._setTextureProviderSubscriptionPrev = textureProviderPrev$.pipe(operators_1.map(function (provider) {
37139             return function (renderer) {
37140                 renderer.setTextureProviderPrev(provider.key, provider);
37141                 return renderer;
37142             };
37143         }))
37144             .subscribe(this._glRendererOperation$);
37145         this._setTileSizeSubscriptionPrev = this._container.renderService.size$.pipe(operators_1.switchMap(function (size) {
37146             return rxjs_1.combineLatest(textureProviderPrev$, rxjs_1.of(size)).pipe(operators_1.first());
37147         }))
37148             .subscribe(function (_a) {
37149             var provider = _a[0], size = _a[1];
37150             var viewportSize = Math.max(size.width, size.height);
37151             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
37152             provider.setTileSize(tileSize);
37153         });
37154         this._abortTextureProviderSubscriptionPrev = textureProviderPrev$.pipe(operators_1.pairwise())
37155             .subscribe(function (pair) {
37156             var previous = pair[0];
37157             previous.abort();
37158         });
37159         var roiTriggerPrev$ = rxjs_1.combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(operators_1.debounceTime(250))).pipe(operators_1.map(function (_a) {
37160             var camera = _a[0], size = _a[1];
37161             return [
37162                 camera.camera.position.clone(),
37163                 camera.camera.lookat.clone(),
37164                 camera.zoom.valueOf(),
37165                 size.height.valueOf(),
37166                 size.width.valueOf()
37167             ];
37168         }), operators_1.pairwise(), operators_1.skipWhile(function (pls) {
37169             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
37170         }), operators_1.map(function (pls) {
37171             var samePosition = pls[0][0].equals(pls[1][0]);
37172             var sameLookat = pls[0][1].equals(pls[1][1]);
37173             var sameZoom = pls[0][2] === pls[1][2];
37174             var sameHeight = pls[0][3] === pls[1][3];
37175             var sameWidth = pls[0][4] === pls[1][4];
37176             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
37177         }), operators_1.distinctUntilChanged(), operators_1.filter(function (stalled) {
37178             return stalled;
37179         }), operators_1.switchMap(function (stalled) {
37180             return _this._container.renderService.renderCameraFrame$.pipe(operators_1.first());
37181         }), operators_1.withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$));
37182         this._setRegionOfInterestSubscriptionPrev = textureProviderPrev$.pipe(operators_1.switchMap(function (provider) {
37183             return roiTriggerPrev$.pipe(operators_1.map(function (_a) {
37184                 var camera = _a[0], size = _a[1], transform = _a[2];
37185                 return [
37186                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
37187                     provider,
37188                 ];
37189             }));
37190         }), operators_1.filter(function (args) {
37191             return !args[1].disposed;
37192         }), operators_1.withLatestFrom(this._navigator.stateService.currentState$))
37193             .subscribe(function (_a) {
37194             var _b = _a[0], roi = _b[0], provider = _b[1], frame = _a[1];
37195             var shiftedRoi = null;
37196             if (frame.state.previousNode.fullPano) {
37197                 if (frame.state.currentNode.fullPano) {
37198                     var currentViewingDirection = _this._spatial.viewingDirection(frame.state.currentNode.rotation);
37199                     var previousViewingDirection = _this._spatial.viewingDirection(frame.state.previousNode.rotation);
37200                     var directionDiff = _this._spatial.angleBetweenVector2(currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y);
37201                     var shift = directionDiff / (2 * Math.PI);
37202                     var bbox = {
37203                         maxX: _this._spatial.wrap(roi.bbox.maxX + shift, 0, 1),
37204                         maxY: roi.bbox.maxY,
37205                         minX: _this._spatial.wrap(roi.bbox.minX + shift, 0, 1),
37206                         minY: roi.bbox.minY,
37207                     };
37208                     shiftedRoi = {
37209                         bbox: bbox,
37210                         pixelHeight: roi.pixelHeight,
37211                         pixelWidth: roi.pixelWidth,
37212                     };
37213                 }
37214                 else {
37215                     var currentViewingDirection = _this._spatial.viewingDirection(frame.state.currentNode.rotation);
37216                     var previousViewingDirection = _this._spatial.viewingDirection(frame.state.previousNode.rotation);
37217                     var directionDiff = _this._spatial.angleBetweenVector2(currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y);
37218                     var shiftX = directionDiff / (2 * Math.PI);
37219                     var a1 = _this._spatial.angleToPlane(currentViewingDirection.toArray(), [0, 0, 1]);
37220                     var a2 = _this._spatial.angleToPlane(previousViewingDirection.toArray(), [0, 0, 1]);
37221                     var shiftY = (a2 - a1) / (2 * Math.PI);
37222                     var currentTransform = frame.state.currentTransform;
37223                     var size = Math.max(currentTransform.basicWidth, currentTransform.basicHeight);
37224                     var hFov = size > 0 ?
37225                         2 * Math.atan(0.5 * currentTransform.basicWidth / (size * currentTransform.focal)) :
37226                         Math.PI / 3;
37227                     var vFov = size > 0 ?
37228                         2 * Math.atan(0.5 * currentTransform.basicHeight / (size * currentTransform.focal)) :
37229                         Math.PI / 3;
37230                     var spanningWidth = hFov / (2 * Math.PI);
37231                     var spanningHeight = vFov / Math.PI;
37232                     var basicWidth = (roi.bbox.maxX - roi.bbox.minX) * spanningWidth;
37233                     var basicHeight = (roi.bbox.maxY - roi.bbox.minY) * spanningHeight;
37234                     var pixelWidth = roi.pixelWidth * spanningWidth;
37235                     var pixelHeight = roi.pixelHeight * spanningHeight;
37236                     var zoomShiftX = (roi.bbox.minX + roi.bbox.maxX) / 2 - 0.5;
37237                     var zoomShiftY = (roi.bbox.minY + roi.bbox.maxY) / 2 - 0.5;
37238                     var minX = 0.5 + shiftX + spanningWidth * zoomShiftX - basicWidth / 2;
37239                     var maxX = 0.5 + shiftX + spanningWidth * zoomShiftX + basicWidth / 2;
37240                     var minY = 0.5 + shiftY + spanningHeight * zoomShiftY - basicHeight / 2;
37241                     var maxY = 0.5 + shiftY + spanningHeight * zoomShiftY + basicHeight / 2;
37242                     var bbox = {
37243                         maxX: _this._spatial.wrap(maxX, 0, 1),
37244                         maxY: maxY,
37245                         minX: _this._spatial.wrap(minX, 0, 1),
37246                         minY: minY,
37247                     };
37248                     shiftedRoi = {
37249                         bbox: bbox,
37250                         pixelHeight: pixelHeight,
37251                         pixelWidth: pixelWidth,
37252                     };
37253                 }
37254             }
37255             else {
37256                 var currentBasicAspect = frame.state.currentTransform.basicAspect;
37257                 var previousBasicAspect = frame.state.previousTransform.basicAspect;
37258                 var _c = _this._getBasicCorners(currentBasicAspect, previousBasicAspect), _d = _c[0], cornerMinX = _d[0], cornerMinY = _d[1], _e = _c[1], cornerMaxX = _e[0], cornerMaxY = _e[1];
37259                 var basicWidth = cornerMaxX - cornerMinX;
37260                 var basicHeight = cornerMaxY - cornerMinY;
37261                 var pixelWidth = roi.pixelWidth / basicWidth;
37262                 var pixelHeight = roi.pixelHeight / basicHeight;
37263                 var minX = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.minX / basicWidth;
37264                 var maxX = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.maxX / basicWidth;
37265                 var minY = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.minY / basicHeight;
37266                 var maxY = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.maxY / basicHeight;
37267                 var bbox = {
37268                     maxX: maxX,
37269                     maxY: maxY,
37270                     minX: minX,
37271                     minY: minY,
37272                 };
37273                 _this._clipBoundingBox(bbox);
37274                 shiftedRoi = {
37275                     bbox: bbox,
37276                     pixelHeight: pixelHeight,
37277                     pixelWidth: pixelWidth,
37278                 };
37279             }
37280             provider.setRegionOfInterest(shiftedRoi);
37281         });
37282         var hasTexturePrev$ = textureProviderPrev$.pipe(operators_1.switchMap(function (provider) {
37283             return provider.hasTexture$;
37284         }), operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
37285         this._hasTextureSubscriptionPrev = hasTexturePrev$.subscribe(function () { });
37286         var nodeImagePrev$ = this._navigator.stateService.currentState$.pipe(operators_1.filter(function (frame) {
37287             return frame.state.nodesAhead === 0 && !!frame.state.previousNode;
37288         }), operators_1.map(function (frame) {
37289             return frame.state.previousNode;
37290         }), operators_1.distinctUntilChanged(undefined, function (node) {
37291             return node.key;
37292         }), operators_1.debounceTime(1000), operators_1.withLatestFrom(hasTexturePrev$), operators_1.filter(function (args) {
37293             return !args[1];
37294         }), operators_1.map(function (args) {
37295             return args[0];
37296         }), operators_1.filter(function (node) {
37297             return node.pano ?
37298                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
37299                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
37300         }), operators_1.switchMap(function (node) {
37301             var baseImageSize = node.pano ?
37302                 Utils_1.Settings.basePanoramaSize :
37303                 Utils_1.Settings.baseImageSize;
37304             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
37305                 return rxjs_1.empty();
37306             }
37307             var image$ = node
37308                 .cacheImage$(Utils_1.Settings.maxImageSize).pipe(operators_1.map(function (n) {
37309                 return [n.image, n];
37310             }));
37311             return image$.pipe(operators_1.takeUntil(hasTexturePrev$.pipe(operators_1.filter(function (hasTexture) {
37312                 return hasTexture;
37313             }))), operators_1.catchError(function (error, caught) {
37314                 console.error("Failed to fetch high res image (" + node.key + ")", error);
37315                 return rxjs_1.empty();
37316             }));
37317         })).pipe(operators_1.publish(), operators_1.refCount());
37318         this._updateBackgroundSubscriptionPrev = nodeImagePrev$.pipe(operators_1.withLatestFrom(textureProviderPrev$))
37319             .subscribe(function (args) {
37320             if (args[0][1].key !== args[1].key ||
37321                 args[1].disposed) {
37322                 return;
37323             }
37324             args[1].updateBackground(args[0][0]);
37325         });
37326         this._updateTextureImageSubscriptionPrev = nodeImagePrev$.pipe(operators_1.map(function (imn) {
37327             return function (renderer) {
37328                 renderer.updateTextureImage(imn[0], imn[1]);
37329                 return renderer;
37330             };
37331         }))
37332             .subscribe(this._glRendererOperation$);
37333     };
37334     SliderComponent.prototype._deactivate = function () {
37335         var _this = this;
37336         this._waitSubscription.unsubscribe();
37337         this._navigator.stateService.state$.pipe(operators_1.first())
37338             .subscribe(function (state) {
37339             if (state !== State_1.State.Traversing) {
37340                 _this._navigator.stateService.traverse();
37341             }
37342         });
37343         this._glRendererDisposer$.next(null);
37344         this._domRenderer.deactivate();
37345         this._modeSubcription.unsubscribe();
37346         this._setKeysSubscription.unsubscribe();
37347         this._stateSubscription.unsubscribe();
37348         this._glRenderSubscription.unsubscribe();
37349         this._domRenderSubscription.unsubscribe();
37350         this._moveSubscription.unsubscribe();
37351         this._updateCurtainSubscription.unsubscribe();
37352         this._textureProviderSubscription.unsubscribe();
37353         this._setTextureProviderSubscription.unsubscribe();
37354         this._setTileSizeSubscription.unsubscribe();
37355         this._abortTextureProviderSubscription.unsubscribe();
37356         this._setRegionOfInterestSubscription.unsubscribe();
37357         this._hasTextureSubscription.unsubscribe();
37358         this._updateBackgroundSubscription.unsubscribe();
37359         this._updateTextureImageSubscription.unsubscribe();
37360         this._textureProviderSubscriptionPrev.unsubscribe();
37361         this._setTextureProviderSubscriptionPrev.unsubscribe();
37362         this._setTileSizeSubscriptionPrev.unsubscribe();
37363         this._abortTextureProviderSubscriptionPrev.unsubscribe();
37364         this._setRegionOfInterestSubscriptionPrev.unsubscribe();
37365         this._hasTextureSubscriptionPrev.unsubscribe();
37366         this._updateBackgroundSubscriptionPrev.unsubscribe();
37367         this._updateTextureImageSubscriptionPrev.unsubscribe();
37368         this.configure({ keys: null });
37369     };
37370     SliderComponent.prototype._getDefaultConfiguration = function () {
37371         return {
37372             initialPosition: 1,
37373             mode: Component_1.SliderMode.Motion,
37374             sliderVisible: true,
37375         };
37376     };
37377     SliderComponent.prototype._catchCacheNode$ = function (key) {
37378         return this._navigator.graphService.cacheNode$(key).pipe(operators_1.catchError(function (error, caught) {
37379             console.error("Failed to cache slider node (" + key + ")", error);
37380             return rxjs_1.empty();
37381         }));
37382     };
37383     SliderComponent.prototype._getBasicCorners = function (currentAspect, previousAspect) {
37384         var offsetX;
37385         var offsetY;
37386         if (currentAspect > previousAspect) {
37387             offsetX = 0.5;
37388             offsetY = 0.5 * currentAspect / previousAspect;
37389         }
37390         else {
37391             offsetX = 0.5 * previousAspect / currentAspect;
37392             offsetY = 0.5;
37393         }
37394         return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]];
37395     };
37396     SliderComponent.prototype._clipBoundingBox = function (bbox) {
37397         bbox.minX = Math.max(0, Math.min(1, bbox.minX));
37398         bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
37399         bbox.minY = Math.max(0, Math.min(1, bbox.minY));
37400         bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
37401     };
37402     SliderComponent.componentName = "slider";
37403     return SliderComponent;
37404 }(Component_1.Component));
37405 exports.SliderComponent = SliderComponent;
37406 Component_1.ComponentService.register(SliderComponent);
37407 exports.default = SliderComponent;
37408
37409
37410 },{"../../Component":291,"../../Geo":294,"../../Render":297,"../../State":298,"../../Tiles":300,"../../Utils":301,"rxjs":43,"rxjs/operators":241}],354:[function(require,module,exports){
37411 "use strict";
37412 Object.defineProperty(exports, "__esModule", { value: true });
37413 var rxjs_1 = require("rxjs");
37414 var operators_1 = require("rxjs/operators");
37415 var vd = require("virtual-dom");
37416 var Component_1 = require("../../Component");
37417 var SliderDOMRenderer = /** @class */ (function () {
37418     function SliderDOMRenderer(container) {
37419         this._container = container;
37420         this._interacting = false;
37421         this._notifyModeChanged$ = new rxjs_1.Subject();
37422         this._notifyPositionChanged$ = new rxjs_1.Subject();
37423         this._stopInteractionSubscription = null;
37424     }
37425     Object.defineProperty(SliderDOMRenderer.prototype, "mode$", {
37426         get: function () {
37427             return this._notifyModeChanged$;
37428         },
37429         enumerable: true,
37430         configurable: true
37431     });
37432     Object.defineProperty(SliderDOMRenderer.prototype, "position$", {
37433         get: function () {
37434             return this._notifyPositionChanged$;
37435         },
37436         enumerable: true,
37437         configurable: true
37438     });
37439     SliderDOMRenderer.prototype.activate = function () {
37440         var _this = this;
37441         if (!!this._stopInteractionSubscription) {
37442             return;
37443         }
37444         this._stopInteractionSubscription = rxjs_1.merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$.pipe(operators_1.filter(function (touchEvent) {
37445             return touchEvent.touches.length === 0;
37446         })))
37447             .subscribe(function (event) {
37448             if (_this._interacting) {
37449                 _this._interacting = false;
37450             }
37451         });
37452     };
37453     SliderDOMRenderer.prototype.deactivate = function () {
37454         if (!this._stopInteractionSubscription) {
37455             return;
37456         }
37457         this._interacting = false;
37458         this._stopInteractionSubscription.unsubscribe();
37459         this._stopInteractionSubscription = null;
37460     };
37461     SliderDOMRenderer.prototype.render = function (position, mode, motionless, pano, visible) {
37462         var children = [];
37463         if (visible) {
37464             children.push(vd.h("div.SliderBorder", []));
37465             var modeVisible = !(motionless || pano);
37466             if (modeVisible) {
37467                 children.push(this._createModeButton(mode));
37468                 children.push(this._createModeButton2d(mode));
37469             }
37470             children.push(this._createPositionInput(position, modeVisible));
37471         }
37472         var boundingRect = this._container.domContainer.getBoundingClientRect();
37473         var width = Math.max(215, Math.min(400, boundingRect.width - 100));
37474         return vd.h("div.SliderContainer", { style: { width: width + "px" } }, children);
37475     };
37476     SliderDOMRenderer.prototype._createModeButton = function (mode) {
37477         var _this = this;
37478         var properties = {
37479             onclick: function () {
37480                 if (mode === Component_1.SliderMode.Motion) {
37481                     return;
37482                 }
37483                 _this._notifyModeChanged$.next(Component_1.SliderMode.Motion);
37484             },
37485         };
37486         var className = mode === Component_1.SliderMode.Stationary ?
37487             "SliderModeButtonDisabled" :
37488             "SliderModeButton";
37489         return vd.h("div." + className, properties, [vd.h("div.SliderModeIcon", [])]);
37490     };
37491     SliderDOMRenderer.prototype._createModeButton2d = function (mode) {
37492         var _this = this;
37493         var properties = {
37494             onclick: function () {
37495                 if (mode === Component_1.SliderMode.Stationary) {
37496                     return;
37497                 }
37498                 _this._notifyModeChanged$.next(Component_1.SliderMode.Stationary);
37499             },
37500         };
37501         var className = mode === Component_1.SliderMode.Motion ?
37502             "SliderModeButton2dDisabled" :
37503             "SliderModeButton2d";
37504         return vd.h("div." + className, properties, [vd.h("div.SliderModeIcon2d", [])]);
37505     };
37506     SliderDOMRenderer.prototype._createPositionInput = function (position, modeVisible) {
37507         var _this = this;
37508         var onChange = function (e) {
37509             _this._notifyPositionChanged$.next(Number(e.target.value) / 1000);
37510         };
37511         var onStart = function (e) {
37512             _this._interacting = true;
37513             e.stopPropagation();
37514         };
37515         var onMove = function (e) {
37516             if (_this._interacting) {
37517                 e.stopPropagation();
37518             }
37519         };
37520         var onKeyDown = function (e) {
37521             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
37522                 e.key === "ArrowRight" || e.key === "ArrowUp") {
37523                 e.preventDefault();
37524             }
37525         };
37526         var boundingRect = this._container.domContainer.getBoundingClientRect();
37527         var width = Math.max(215, Math.min(400, boundingRect.width - 105)) - 84 + (modeVisible ? 0 : 52);
37528         var positionInput = vd.h("input.SliderPosition", {
37529             max: 1000,
37530             min: 0,
37531             onchange: onChange,
37532             oninput: onChange,
37533             onkeydown: onKeyDown,
37534             onmousedown: onStart,
37535             onmousemove: onMove,
37536             ontouchmove: onMove,
37537             ontouchstart: onStart,
37538             style: {
37539                 width: width + "px",
37540             },
37541             type: "range",
37542             value: 1000 * position,
37543         }, []);
37544         return vd.h("div.SliderPositionContainer", [positionInput]);
37545     };
37546     return SliderDOMRenderer;
37547 }());
37548 exports.SliderDOMRenderer = SliderDOMRenderer;
37549 exports.default = SliderDOMRenderer;
37550
37551 },{"../../Component":291,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],355:[function(require,module,exports){
37552 "use strict";
37553 Object.defineProperty(exports, "__esModule", { value: true });
37554 var Component_1 = require("../../Component");
37555 var Geo_1 = require("../../Geo");
37556 var SliderGLRenderer = /** @class */ (function () {
37557     function SliderGLRenderer() {
37558         this._factory = new Component_1.MeshFactory();
37559         this._scene = new Component_1.MeshScene();
37560         this._spatial = new Geo_1.Spatial();
37561         this._currentKey = null;
37562         this._previousKey = null;
37563         this._disabled = false;
37564         this._curtain = 1;
37565         this._frameId = 0;
37566         this._needsRender = false;
37567         this._mode = null;
37568         this._currentProviderDisposers = {};
37569         this._previousProviderDisposers = {};
37570     }
37571     Object.defineProperty(SliderGLRenderer.prototype, "disabled", {
37572         get: function () {
37573             return this._disabled;
37574         },
37575         enumerable: true,
37576         configurable: true
37577     });
37578     Object.defineProperty(SliderGLRenderer.prototype, "frameId", {
37579         get: function () {
37580             return this._frameId;
37581         },
37582         enumerable: true,
37583         configurable: true
37584     });
37585     Object.defineProperty(SliderGLRenderer.prototype, "needsRender", {
37586         get: function () {
37587             return this._needsRender;
37588         },
37589         enumerable: true,
37590         configurable: true
37591     });
37592     SliderGLRenderer.prototype.setTextureProvider = function (key, provider) {
37593         this._setTextureProvider(key, this._currentKey, provider, this._currentProviderDisposers, this._updateTexture.bind(this));
37594     };
37595     SliderGLRenderer.prototype.setTextureProviderPrev = function (key, provider) {
37596         this._setTextureProvider(key, this._previousKey, provider, this._previousProviderDisposers, this._updateTexturePrev.bind(this));
37597     };
37598     SliderGLRenderer.prototype.update = function (frame, mode) {
37599         this._updateFrameId(frame.id);
37600         this._updateImagePlanes(frame.state, mode);
37601     };
37602     SliderGLRenderer.prototype.updateCurtain = function (curtain) {
37603         if (this._curtain === curtain) {
37604             return;
37605         }
37606         this._curtain = curtain;
37607         this._updateCurtain();
37608         this._needsRender = true;
37609     };
37610     SliderGLRenderer.prototype.updateTexture = function (image, node) {
37611         var planes = node.key === this._currentKey ?
37612             this._scene.planes :
37613             node.key === this._previousKey ?
37614                 this._scene.planesOld :
37615                 {};
37616         if (Object.keys(planes).length === 0) {
37617             return;
37618         }
37619         this._needsRender = true;
37620         for (var key in planes) {
37621             if (!planes.hasOwnProperty(key)) {
37622                 continue;
37623             }
37624             var plane = planes[key];
37625             var material = plane.material;
37626             var texture = material.uniforms.projectorTex.value;
37627             texture.image = image;
37628             texture.needsUpdate = true;
37629         }
37630     };
37631     SliderGLRenderer.prototype.updateTextureImage = function (image, node) {
37632         if (this._currentKey !== node.key) {
37633             return;
37634         }
37635         this._needsRender = true;
37636         var planes = this._scene.planes;
37637         for (var key in planes) {
37638             if (!planes.hasOwnProperty(key)) {
37639                 continue;
37640             }
37641             var plane = planes[key];
37642             var material = plane.material;
37643             var texture = material.uniforms.projectorTex.value;
37644             texture.image = image;
37645             texture.needsUpdate = true;
37646         }
37647     };
37648     SliderGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
37649         if (!this.disabled) {
37650             renderer.render(this._scene.sceneOld, perspectiveCamera);
37651         }
37652         renderer.render(this._scene.scene, perspectiveCamera);
37653         this._needsRender = false;
37654     };
37655     SliderGLRenderer.prototype.dispose = function () {
37656         this._scene.clear();
37657         for (var key in this._currentProviderDisposers) {
37658             if (!this._currentProviderDisposers.hasOwnProperty(key)) {
37659                 continue;
37660             }
37661             this._currentProviderDisposers[key]();
37662         }
37663         for (var key in this._previousProviderDisposers) {
37664             if (!this._previousProviderDisposers.hasOwnProperty(key)) {
37665                 continue;
37666             }
37667             this._previousProviderDisposers[key]();
37668         }
37669         this._currentProviderDisposers = {};
37670         this._previousProviderDisposers = {};
37671     };
37672     SliderGLRenderer.prototype._getBasicCorners = function (currentAspect, previousAspect) {
37673         var offsetX;
37674         var offsetY;
37675         if (currentAspect > previousAspect) {
37676             offsetX = 0.5;
37677             offsetY = 0.5 * currentAspect / previousAspect;
37678         }
37679         else {
37680             offsetX = 0.5 * previousAspect / currentAspect;
37681             offsetY = 0.5;
37682         }
37683         return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]];
37684     };
37685     SliderGLRenderer.prototype._setDisabled = function (state) {
37686         this._disabled = state.currentNode == null ||
37687             state.previousNode == null ||
37688             (state.currentNode.pano && !state.currentNode.fullPano) ||
37689             (state.previousNode.pano && !state.previousNode.fullPano) ||
37690             (state.currentNode.fullPano && !state.previousNode.fullPano);
37691     };
37692     SliderGLRenderer.prototype._setTextureProvider = function (key, originalKey, provider, providerDisposers, updateTexture) {
37693         var _this = this;
37694         if (key !== originalKey) {
37695             return;
37696         }
37697         var createdSubscription = provider.textureCreated$
37698             .subscribe(updateTexture);
37699         var updatedSubscription = provider.textureUpdated$
37700             .subscribe(function (updated) {
37701             _this._needsRender = true;
37702         });
37703         var dispose = function () {
37704             createdSubscription.unsubscribe();
37705             updatedSubscription.unsubscribe();
37706             provider.dispose();
37707         };
37708         if (key in providerDisposers) {
37709             var disposeProvider = providerDisposers[key];
37710             disposeProvider();
37711             delete providerDisposers[key];
37712         }
37713         providerDisposers[key] = dispose;
37714     };
37715     SliderGLRenderer.prototype._updateCurtain = function () {
37716         var planes = this._scene.planes;
37717         for (var key in planes) {
37718             if (!planes.hasOwnProperty(key)) {
37719                 continue;
37720             }
37721             var plane = planes[key];
37722             var shaderMaterial = plane.material;
37723             if (!!shaderMaterial.uniforms.curtain) {
37724                 shaderMaterial.uniforms.curtain.value = this._curtain;
37725             }
37726         }
37727     };
37728     SliderGLRenderer.prototype._updateFrameId = function (frameId) {
37729         this._frameId = frameId;
37730     };
37731     SliderGLRenderer.prototype._updateImagePlanes = function (state, mode) {
37732         var currentChanged = state.currentNode != null && this._currentKey !== state.currentNode.key;
37733         var previousChanged = state.previousNode != null && this._previousKey !== state.previousNode.key;
37734         var modeChanged = this._mode !== mode;
37735         if (!(currentChanged || previousChanged || modeChanged)) {
37736             return;
37737         }
37738         this._setDisabled(state);
37739         this._needsRender = true;
37740         this._mode = mode;
37741         var motionless = state.motionless || mode === Component_1.SliderMode.Stationary || state.currentNode.pano;
37742         if (this.disabled || previousChanged) {
37743             if (this._previousKey in this._previousProviderDisposers) {
37744                 this._previousProviderDisposers[this._previousKey]();
37745                 delete this._previousProviderDisposers[this._previousKey];
37746             }
37747         }
37748         if (this.disabled) {
37749             this._scene.setImagePlanesOld({});
37750         }
37751         else {
37752             if (previousChanged || modeChanged) {
37753                 var previousNode = state.previousNode;
37754                 this._previousKey = previousNode.key;
37755                 var elements = state.currentTransform.rt.elements;
37756                 var translation = [elements[12], elements[13], elements[14]];
37757                 var currentAspect = state.currentTransform.basicAspect;
37758                 var previousAspect = state.previousTransform.basicAspect;
37759                 var textureScale = currentAspect > previousAspect ?
37760                     [1, previousAspect / currentAspect] :
37761                     [currentAspect / previousAspect, 1];
37762                 var rotation = state.currentNode.rotation;
37763                 var width = state.currentNode.width;
37764                 var height = state.currentNode.height;
37765                 if (previousNode.fullPano) {
37766                     rotation = state.previousNode.rotation;
37767                     translation = this._spatial
37768                         .rotate(this._spatial
37769                         .opticalCenter(state.currentNode.rotation, translation)
37770                         .toArray(), rotation)
37771                         .multiplyScalar(-1)
37772                         .toArray();
37773                     width = state.previousNode.width;
37774                     height = state.previousNode.height;
37775                 }
37776                 var transform = new Geo_1.Transform(state.currentNode.orientation, width, height, state.currentNode.focal, state.currentNode.scale, previousNode.gpano, rotation, translation, previousNode.image, textureScale);
37777                 var mesh = undefined;
37778                 if (previousNode.fullPano) {
37779                     mesh = this._factory.createMesh(previousNode, motionless || state.currentNode.fullPano ? transform : state.previousTransform);
37780                 }
37781                 else {
37782                     if (motionless) {
37783                         var _a = this._getBasicCorners(currentAspect, previousAspect), _b = _a[0], basicX0 = _b[0], basicY0 = _b[1], _c = _a[1], basicX1 = _c[0], basicY1 = _c[1];
37784                         mesh = this._factory.createFlatMesh(state.previousNode, transform, basicX0, basicX1, basicY0, basicY1);
37785                     }
37786                     else {
37787                         mesh = this._factory.createMesh(state.previousNode, state.previousTransform);
37788                     }
37789                 }
37790                 var previousPlanes = {};
37791                 previousPlanes[previousNode.key] = mesh;
37792                 this._scene.setImagePlanesOld(previousPlanes);
37793             }
37794         }
37795         if (currentChanged || modeChanged) {
37796             if (this._currentKey in this._currentProviderDisposers) {
37797                 this._currentProviderDisposers[this._currentKey]();
37798                 delete this._currentProviderDisposers[this._currentKey];
37799             }
37800             this._currentKey = state.currentNode.key;
37801             var planes = {};
37802             if (state.currentNode.fullPano) {
37803                 planes[state.currentNode.key] = this._factory.createCurtainMesh(state.currentNode, state.currentTransform);
37804             }
37805             else if (state.currentNode.pano && !state.currentNode.fullPano) {
37806                 planes[state.currentNode.key] = this._factory.createMesh(state.currentNode, state.currentTransform);
37807             }
37808             else {
37809                 if (motionless) {
37810                     planes[state.currentNode.key] = this._factory.createDistortedCurtainMesh(state.currentNode, state.currentTransform);
37811                 }
37812                 else {
37813                     planes[state.currentNode.key] = this._factory.createCurtainMesh(state.currentNode, state.currentTransform);
37814                 }
37815             }
37816             this._scene.setImagePlanes(planes);
37817             this._updateCurtain();
37818         }
37819     };
37820     SliderGLRenderer.prototype._updateTexture = function (texture) {
37821         this._needsRender = true;
37822         var planes = this._scene.planes;
37823         for (var key in planes) {
37824             if (!planes.hasOwnProperty(key)) {
37825                 continue;
37826             }
37827             var plane = planes[key];
37828             var material = plane.material;
37829             var oldTexture = material.uniforms.projectorTex.value;
37830             material.uniforms.projectorTex.value = null;
37831             oldTexture.dispose();
37832             material.uniforms.projectorTex.value = texture;
37833         }
37834     };
37835     SliderGLRenderer.prototype._updateTexturePrev = function (texture) {
37836         this._needsRender = true;
37837         var planes = this._scene.planesOld;
37838         for (var key in planes) {
37839             if (!planes.hasOwnProperty(key)) {
37840                 continue;
37841             }
37842             var plane = planes[key];
37843             var material = plane.material;
37844             var oldTexture = material.uniforms.projectorTex.value;
37845             material.uniforms.projectorTex.value = null;
37846             oldTexture.dispose();
37847             material.uniforms.projectorTex.value = texture;
37848         }
37849     };
37850     return SliderGLRenderer;
37851 }());
37852 exports.SliderGLRenderer = SliderGLRenderer;
37853 exports.default = SliderGLRenderer;
37854
37855
37856 },{"../../Component":291,"../../Geo":294}],356:[function(require,module,exports){
37857 "use strict";
37858 Object.defineProperty(exports, "__esModule", { value: true });
37859 var CameraVisualizationMode;
37860 (function (CameraVisualizationMode) {
37861     CameraVisualizationMode[CameraVisualizationMode["Default"] = 0] = "Default";
37862     CameraVisualizationMode[CameraVisualizationMode["Cluster"] = 1] = "Cluster";
37863     CameraVisualizationMode[CameraVisualizationMode["ConnectedComponent"] = 2] = "ConnectedComponent";
37864     CameraVisualizationMode[CameraVisualizationMode["Sequence"] = 3] = "Sequence";
37865 })(CameraVisualizationMode = exports.CameraVisualizationMode || (exports.CameraVisualizationMode = {}));
37866 exports.default = CameraVisualizationMode;
37867
37868 },{}],357:[function(require,module,exports){
37869 "use strict";
37870 Object.defineProperty(exports, "__esModule", { value: true });
37871 var CameraVisualizationMode_1 = require("./CameraVisualizationMode");
37872 exports.CameraVisualizationMode = CameraVisualizationMode_1.CameraVisualizationMode;
37873
37874 },{"./CameraVisualizationMode":356}],358:[function(require,module,exports){
37875 "use strict";
37876 Object.defineProperty(exports, "__esModule", { value: true });
37877 var geohash = require("latlon-geohash");
37878 var pako = require("pako");
37879 var rxjs_1 = require("rxjs");
37880 var operators_1 = require("rxjs/operators");
37881 var Error_1 = require("../../Error");
37882 var Utils_1 = require("../../Utils");
37883 var SpatialDataCache = /** @class */ (function () {
37884     function SpatialDataCache(graphService) {
37885         this._graphService = graphService;
37886         this._tiles = {};
37887         this._cacheRequests = {};
37888         this._clusterReconstructions = {};
37889         this._clusterReconstructionTiles = {};
37890         this._tileClusters = {};
37891         this._cachingTiles$ = {};
37892         this._cachingClusterReconstructions$ = {};
37893     }
37894     SpatialDataCache.prototype.cacheClusterReconstructions$ = function (hash) {
37895         var _this = this;
37896         if (!this.hasTile(hash)) {
37897             throw new Error("Cannot cache reconstructions of a non-existing tile.");
37898         }
37899         if (this.hasClusterReconstructions(hash)) {
37900             throw new Error("Cannot cache reconstructions that already exists.");
37901         }
37902         if (this.isCachingClusterReconstructions(hash)) {
37903             return this._cachingClusterReconstructions$[hash];
37904         }
37905         var clusterKeys = this.getTile(hash)
37906             .filter(function (nd) {
37907             return !!nd.clusterKey;
37908         })
37909             .map(function (nd) {
37910             return nd.clusterKey;
37911         })
37912             .filter(function (v, i, a) {
37913             return a.indexOf(v) === i;
37914         });
37915         this._tileClusters[hash] = clusterKeys;
37916         this._cacheRequests[hash] = [];
37917         this._cachingClusterReconstructions$[hash] = rxjs_1.from(clusterKeys).pipe(operators_1.mergeMap(function (key) {
37918             if (_this._hasClusterReconstruction(key)) {
37919                 return rxjs_1.of(_this._getClusterReconstruction(key));
37920             }
37921             return _this._getClusterReconstruction$(key, _this._cacheRequests[hash])
37922                 .pipe(operators_1.catchError(function (error) {
37923                 if (error instanceof Error_1.AbortMapillaryError) {
37924                     return rxjs_1.empty();
37925                 }
37926                 console.error(error);
37927                 return rxjs_1.empty();
37928             }));
37929         }, 6), operators_1.filter(function () {
37930             return hash in _this._tileClusters;
37931         }), operators_1.tap(function (reconstruction) {
37932             if (!_this._hasClusterReconstruction(reconstruction.key)) {
37933                 _this._clusterReconstructions[reconstruction.key] = reconstruction;
37934             }
37935             if (!(reconstruction.key in _this._clusterReconstructionTiles)) {
37936                 _this._clusterReconstructionTiles[reconstruction.key] = [];
37937             }
37938             if (_this._clusterReconstructionTiles[reconstruction.key].indexOf(hash) === -1) {
37939                 _this._clusterReconstructionTiles[reconstruction.key].push(hash);
37940             }
37941         }), operators_1.finalize(function () {
37942             if (hash in _this._cachingClusterReconstructions$) {
37943                 delete _this._cachingClusterReconstructions$[hash];
37944             }
37945             if (hash in _this._cacheRequests) {
37946                 delete _this._cacheRequests[hash];
37947             }
37948         }), operators_1.publish(), operators_1.refCount());
37949         return this._cachingClusterReconstructions$[hash];
37950     };
37951     SpatialDataCache.prototype.cacheTile$ = function (hash) {
37952         var _this = this;
37953         if (hash.length !== 8) {
37954             throw new Error("Hash needs to be level 8.");
37955         }
37956         if (this.hasTile(hash)) {
37957             throw new Error("Cannot cache tile that already exists.");
37958         }
37959         if (this.isCachingTile(hash)) {
37960             return this._cachingTiles$[hash];
37961         }
37962         var bounds = geohash.bounds(hash);
37963         var sw = { lat: bounds.sw.lat, lon: bounds.sw.lon };
37964         var ne = { lat: bounds.ne.lat, lon: bounds.ne.lon };
37965         this._cachingTiles$[hash] = this._graphService.cacheBoundingBox$(sw, ne).pipe(operators_1.catchError(function (error) {
37966             console.error(error);
37967             return rxjs_1.empty();
37968         }), operators_1.map(function (nodes) {
37969             return nodes
37970                 .map(function (n) {
37971                 return _this._createNodeData(n);
37972             });
37973         }), operators_1.filter(function () {
37974             return !(hash in _this._tiles);
37975         }), operators_1.tap(function (nodeData) {
37976             var _a;
37977             _this._tiles[hash] = [];
37978             (_a = _this._tiles[hash]).push.apply(_a, nodeData);
37979             delete _this._cachingTiles$[hash];
37980         }), operators_1.finalize(function () {
37981             if (hash in _this._cachingTiles$) {
37982                 delete _this._cachingTiles$[hash];
37983             }
37984         }), operators_1.publish(), operators_1.refCount());
37985         return this._cachingTiles$[hash];
37986     };
37987     SpatialDataCache.prototype.isCachingClusterReconstructions = function (hash) {
37988         return hash in this._cachingClusterReconstructions$;
37989     };
37990     SpatialDataCache.prototype.isCachingTile = function (hash) {
37991         return hash in this._cachingTiles$;
37992     };
37993     SpatialDataCache.prototype.hasClusterReconstructions = function (hash) {
37994         if (hash in this._cachingClusterReconstructions$ ||
37995             !(hash in this._tileClusters)) {
37996             return false;
37997         }
37998         for (var _i = 0, _a = this._tileClusters[hash]; _i < _a.length; _i++) {
37999             var key = _a[_i];
38000             if (!(key in this._clusterReconstructions)) {
38001                 return false;
38002             }
38003         }
38004         return true;
38005     };
38006     SpatialDataCache.prototype.hasTile = function (hash) {
38007         return !(hash in this._cachingTiles$) && hash in this._tiles;
38008     };
38009     SpatialDataCache.prototype.getClusterReconstructions = function (hash) {
38010         var _this = this;
38011         return hash in this._tileClusters ?
38012             this._tileClusters[hash]
38013                 .map(function (key) {
38014                 return _this._clusterReconstructions[key];
38015             })
38016                 .filter(function (reconstruction) {
38017                 return !!reconstruction;
38018             }) :
38019             [];
38020     };
38021     SpatialDataCache.prototype.getTile = function (hash) {
38022         return hash in this._tiles ? this._tiles[hash] : [];
38023     };
38024     SpatialDataCache.prototype.uncache = function (keepHashes) {
38025         for (var _i = 0, _a = Object.keys(this._cacheRequests); _i < _a.length; _i++) {
38026             var hash = _a[_i];
38027             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
38028                 continue;
38029             }
38030             for (var _b = 0, _c = this._cacheRequests[hash]; _b < _c.length; _b++) {
38031                 var request = _c[_b];
38032                 request.abort();
38033             }
38034             delete this._cacheRequests[hash];
38035         }
38036         for (var _d = 0, _e = Object.keys(this._tileClusters); _d < _e.length; _d++) {
38037             var hash = _e[_d];
38038             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
38039                 continue;
38040             }
38041             for (var _f = 0, _g = this._tileClusters[hash]; _f < _g.length; _f++) {
38042                 var key = _g[_f];
38043                 if (!(key in this._clusterReconstructionTiles)) {
38044                     continue;
38045                 }
38046                 var index = this._clusterReconstructionTiles[key].indexOf(hash);
38047                 if (index === -1) {
38048                     continue;
38049                 }
38050                 this._clusterReconstructionTiles[key].splice(index, 1);
38051                 if (this._clusterReconstructionTiles[key].length > 0) {
38052                     continue;
38053                 }
38054                 delete this._clusterReconstructionTiles[key];
38055                 delete this._clusterReconstructions[key];
38056             }
38057             delete this._tileClusters[hash];
38058         }
38059         for (var _h = 0, _j = Object.keys(this._tiles); _h < _j.length; _h++) {
38060             var hash = _j[_h];
38061             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
38062                 continue;
38063             }
38064             delete this._tiles[hash];
38065         }
38066     };
38067     SpatialDataCache.prototype._createNodeData = function (node) {
38068         return {
38069             alt: node.alt,
38070             cameraProjection: node.cameraProjection,
38071             clusterKey: node.clusterKey,
38072             focal: node.focal,
38073             gpano: node.gpano,
38074             height: node.height,
38075             k1: node.ck1,
38076             k2: node.ck2,
38077             key: node.key,
38078             lat: node.latLon.lat,
38079             lon: node.latLon.lon,
38080             mergeCC: node.mergeCC,
38081             orientation: node.orientation,
38082             originalLat: node.originalLatLon.lat,
38083             originalLon: node.originalLatLon.lon,
38084             rotation: [node.rotation[0], node.rotation[1], node.rotation[2]],
38085             scale: node.scale,
38086             sequenceKey: node.sequenceKey,
38087             width: node.width,
38088         };
38089     };
38090     SpatialDataCache.prototype._getClusterReconstruction = function (key) {
38091         return this._clusterReconstructions[key];
38092     };
38093     SpatialDataCache.prototype._getClusterReconstruction$ = function (key, requests) {
38094         return rxjs_1.Observable.create(function (subscriber) {
38095             var xhr = new XMLHttpRequest();
38096             xhr.open("GET", Utils_1.Urls.clusterReconstruction(key), true);
38097             xhr.responseType = "arraybuffer";
38098             xhr.timeout = 15000;
38099             xhr.onload = function () {
38100                 if (!xhr.response) {
38101                     subscriber.error(new Error("Cluster reconstruction retreival failed (" + key + ")"));
38102                 }
38103                 else {
38104                     var inflated = pako.inflate(xhr.response, { to: "string" });
38105                     var reconstructions = JSON.parse(inflated);
38106                     if (reconstructions.length < 1) {
38107                         subscriber.error(new Error("No cluster reconstruction exists (" + key + ")"));
38108                     }
38109                     var reconstruction = reconstructions[0];
38110                     reconstruction.key = key;
38111                     subscriber.next(reconstruction);
38112                     subscriber.complete();
38113                 }
38114             };
38115             xhr.onerror = function () {
38116                 subscriber.error(new Error("Failed to get cluster reconstruction (" + key + ")"));
38117             };
38118             xhr.ontimeout = function () {
38119                 subscriber.error(new Error("Cluster reconstruction request timed out (" + key + ")"));
38120             };
38121             xhr.onabort = function () {
38122                 subscriber.error(new Error_1.AbortMapillaryError("Cluster reconstruction request was aborted (" + key + ")"));
38123             };
38124             requests.push(xhr);
38125             xhr.send(null);
38126         });
38127     };
38128     SpatialDataCache.prototype._hasClusterReconstruction = function (key) {
38129         return key in this._clusterReconstructions;
38130     };
38131     return SpatialDataCache;
38132 }());
38133 exports.SpatialDataCache = SpatialDataCache;
38134 exports.default = SpatialDataCache;
38135
38136 },{"../../Error":293,"../../Utils":301,"latlon-geohash":21,"pako":23,"rxjs":43,"rxjs/operators":241}],359:[function(require,module,exports){
38137 "use strict";
38138 var __extends = (this && this.__extends) || (function () {
38139     var extendStatics = function (d, b) {
38140         extendStatics = Object.setPrototypeOf ||
38141             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
38142             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
38143         return extendStatics(d, b);
38144     }
38145     return function (d, b) {
38146         extendStatics(d, b);
38147         function __() { this.constructor = d; }
38148         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
38149     };
38150 })();
38151 Object.defineProperty(exports, "__esModule", { value: true });
38152 var geohash = require("latlon-geohash");
38153 var rxjs_1 = require("rxjs");
38154 var operators_1 = require("rxjs/operators");
38155 var Component_1 = require("../../Component");
38156 var Geo_1 = require("../../Geo");
38157 var Render_1 = require("../../Render");
38158 var PlayService_1 = require("../../viewer/PlayService");
38159 var State_1 = require("../../state/State");
38160 var CameraVisualizationMode_1 = require("./CameraVisualizationMode");
38161 var SpatialDataComponent = /** @class */ (function (_super) {
38162     __extends(SpatialDataComponent, _super);
38163     function SpatialDataComponent(name, container, navigator) {
38164         var _this = _super.call(this, name, container, navigator) || this;
38165         _this._cache = new Component_1.SpatialDataCache(navigator.graphService);
38166         _this._scene = new Component_1.SpatialDataScene(_this._getDefaultConfiguration());
38167         _this._viewportCoords = new Geo_1.ViewportCoords();
38168         _this._geoCoords = new Geo_1.GeoCoords();
38169         return _this;
38170     }
38171     SpatialDataComponent.prototype._activate = function () {
38172         var _this = this;
38173         this._earthControlsSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
38174             return configuration.earthControls;
38175         }), operators_1.distinctUntilChanged(), operators_1.withLatestFrom(this._navigator.stateService.state$))
38176             .subscribe(function (_a) {
38177             var earth = _a[0], state = _a[1];
38178             if (earth && state !== State_1.default.Earth) {
38179                 _this._navigator.stateService.earth();
38180             }
38181             else if (!earth && state === State_1.default.Earth) {
38182                 _this._navigator.stateService.traverse();
38183             }
38184         });
38185         var direction$ = this._container.renderService.bearing$.pipe(operators_1.map(function (bearing) {
38186             var direction = "";
38187             if (bearing > 292.5 || bearing <= 67.5) {
38188                 direction += "n";
38189             }
38190             if (bearing > 112.5 && bearing <= 247.5) {
38191                 direction += "s";
38192             }
38193             if (bearing > 22.5 && bearing <= 157.5) {
38194                 direction += "e";
38195             }
38196             if (bearing > 202.5 && bearing <= 337.5) {
38197                 direction += "w";
38198             }
38199             return direction;
38200         }), operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
38201         var hash$ = this._navigator.stateService.reference$.pipe(operators_1.tap(function () {
38202             _this._scene.uncache();
38203         }), operators_1.switchMap(function () {
38204             return _this._navigator.stateService.currentNode$.pipe(operators_1.map(function (node) {
38205                 return geohash.encode(node.latLon.lat, node.latLon.lon, 8);
38206             }), operators_1.distinctUntilChanged());
38207         }), operators_1.publishReplay(1), operators_1.refCount());
38208         var sequencePlay$ = rxjs_1.combineLatest(this._navigator.playService.playing$, this._navigator.playService.speed$).pipe(operators_1.map(function (_a) {
38209             var playing = _a[0], speed = _a[1];
38210             return playing && speed > PlayService_1.default.sequenceSpeed;
38211         }), operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
38212         var hashes$ = rxjs_1.combineLatest(this._navigator.stateService.state$.pipe(operators_1.map(function (state) {
38213             return state === State_1.default.Earth;
38214         }), operators_1.distinctUntilChanged()), hash$, sequencePlay$, direction$).pipe(operators_1.distinctUntilChanged(function (_a, _b) {
38215             var e1 = _a[0], h1 = _a[1], s1 = _a[2], d1 = _a[3];
38216             var e2 = _b[0], h2 = _b[1], s2 = _b[2], d2 = _b[3];
38217             if (e1 !== e2) {
38218                 return false;
38219             }
38220             if (e1) {
38221                 return h1 === h2 && s1 === s2;
38222             }
38223             return h1 === h2 && s1 === s2 && d1 === d2;
38224         }), operators_1.concatMap(function (_a) {
38225             var earth = _a[0], hash = _a[1], sequencePlay = _a[2], direction = _a[3];
38226             if (earth) {
38227                 return sequencePlay ?
38228                     rxjs_1.of([hash]) :
38229                     rxjs_1.of(_this._adjacentComponent(hash, 4));
38230             }
38231             return sequencePlay ?
38232                 rxjs_1.of([hash, geohash.neighbours(hash)[direction]]) :
38233                 rxjs_1.of(_this._computeTiles(hash, direction));
38234         }), operators_1.publish(), operators_1.refCount());
38235         var tile$ = hashes$.pipe(operators_1.switchMap(function (hashes) {
38236             return rxjs_1.from(hashes).pipe(operators_1.mergeMap(function (h) {
38237                 var t$ = _this._cache.hasTile(h) ?
38238                     rxjs_1.of(_this._cache.getTile(h)) :
38239                     _this._cache.cacheTile$(h);
38240                 return rxjs_1.combineLatest(rxjs_1.of(h), t$);
38241             }, 6));
38242         }), operators_1.publish(), operators_1.refCount());
38243         this._addTileSubscription = tile$.pipe(operators_1.withLatestFrom(this._navigator.stateService.reference$))
38244             .subscribe(function (_a) {
38245             var hash = _a[0][0], reference = _a[1];
38246             if (_this._scene.hasTile(hash)) {
38247                 return;
38248             }
38249             _this._scene.addTile(_this._computeTileBBox(hash, reference), hash);
38250         });
38251         this._addNodeSubscription = tile$.pipe(operators_1.withLatestFrom(this._navigator.stateService.reference$))
38252             .subscribe(function (_a) {
38253             var _b = _a[0], hash = _b[0], datas = _b[1], reference = _a[1];
38254             for (var _i = 0, datas_1 = datas; _i < datas_1.length; _i++) {
38255                 var data = datas_1[_i];
38256                 if (_this._scene.hasNode(data.key, hash)) {
38257                     continue;
38258                 }
38259                 _this._scene.addNode(data, _this._createTransform(data, reference), _this._computeOriginalPosition(data, reference), hash);
38260             }
38261         });
38262         this._addReconstructionSubscription = tile$.pipe(operators_1.concatMap(function (_a) {
38263             var hash = _a[0];
38264             var reconstructions$;
38265             if (_this._cache.hasClusterReconstructions(hash)) {
38266                 reconstructions$ = rxjs_1.from(_this._cache.getClusterReconstructions(hash));
38267             }
38268             else if (_this._cache.isCachingClusterReconstructions(hash)) {
38269                 reconstructions$ = _this._cache.cacheClusterReconstructions$(hash).pipe(operators_1.last(null, {}), operators_1.switchMap(function () {
38270                     return rxjs_1.from(_this._cache.getClusterReconstructions(hash));
38271                 }));
38272             }
38273             else if (_this._cache.hasTile(hash)) {
38274                 reconstructions$ = _this._cache.cacheClusterReconstructions$(hash);
38275             }
38276             else {
38277                 reconstructions$ = rxjs_1.empty();
38278             }
38279             return rxjs_1.combineLatest(rxjs_1.of(hash), reconstructions$);
38280         }), operators_1.withLatestFrom(this._navigator.stateService.reference$))
38281             .subscribe(function (_a) {
38282             var _b = _a[0], hash = _b[0], reconstruction = _b[1], reference = _a[1];
38283             if (_this._scene.hasClusterReconstruction(reconstruction.key, hash)) {
38284                 return;
38285             }
38286             _this._scene.addClusterReconstruction(reconstruction, _this._computeTranslation(reconstruction, reference), hash);
38287         });
38288         this._cameraVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
38289             return configuration.camerasVisible;
38290         }), operators_1.distinctUntilChanged())
38291             .subscribe(function (visible) {
38292             _this._scene.setCameraVisibility(visible);
38293         });
38294         this._pointVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
38295             return configuration.pointsVisible;
38296         }), operators_1.distinctUntilChanged())
38297             .subscribe(function (visible) {
38298             _this._scene.setPointVisibility(visible);
38299         });
38300         this._positionVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
38301             return configuration.positionsVisible;
38302         }), operators_1.distinctUntilChanged())
38303             .subscribe(function (visible) {
38304             _this._scene.setPositionVisibility(visible);
38305         });
38306         this._tileVisibilitySubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
38307             return configuration.tilesVisible;
38308         }), operators_1.distinctUntilChanged())
38309             .subscribe(function (visible) {
38310             _this._scene.setTileVisibility(visible);
38311         });
38312         this._ccToModeSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
38313             return configuration.connectedComponents === true ?
38314                 CameraVisualizationMode_1.default.ConnectedComponent :
38315                 CameraVisualizationMode_1.default.Default;
38316         }), operators_1.distinctUntilChanged())
38317             .subscribe(function (mode) {
38318             _this.configure({ cameraVisualizationMode: mode });
38319         });
38320         this._cameraVisualizationModeSubscription = this._configuration$.pipe(operators_1.map(function (configuration) {
38321             return configuration.cameraVisualizationMode;
38322         }), operators_1.distinctUntilChanged())
38323             .subscribe(function (mode) {
38324             _this._scene.setCameraVisualizationMode(mode);
38325         });
38326         this._uncacheSubscription = hash$
38327             .subscribe(function (hash) {
38328             var keepHashes = _this._adjacentComponent(hash, 4);
38329             _this._scene.uncache(keepHashes);
38330             _this._cache.uncache(keepHashes);
38331         });
38332         this._moveSubscription = this._navigator.playService.playing$.pipe(operators_1.switchMap(function (playing) {
38333             return playing ?
38334                 rxjs_1.empty() :
38335                 _this._container.mouseService.dblClick$;
38336         }), operators_1.withLatestFrom(this._container.renderService.renderCamera$), operators_1.switchMap(function (_a) {
38337             var event = _a[0], render = _a[1];
38338             var element = _this._container.element;
38339             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
38340             var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
38341             var key = _this._scene.intersectObjects(viewport, render.perspective);
38342             return !!key ?
38343                 _this._navigator.moveToKey$(key).pipe(operators_1.catchError(function () {
38344                     return rxjs_1.empty();
38345                 })) :
38346                 rxjs_1.empty();
38347         }))
38348             .subscribe();
38349         this._renderSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
38350             var scene = _this._scene;
38351             return {
38352                 name: _this._name,
38353                 render: {
38354                     frameId: frame.id,
38355                     needsRender: scene.needsRender,
38356                     render: scene.render.bind(scene),
38357                     stage: Render_1.GLRenderStage.Foreground,
38358                 },
38359             };
38360         }))
38361             .subscribe(this._container.glRenderer.render$);
38362     };
38363     SpatialDataComponent.prototype._deactivate = function () {
38364         var _this = this;
38365         this._cache.uncache();
38366         this._scene.uncache();
38367         this._addNodeSubscription.unsubscribe();
38368         this._addReconstructionSubscription.unsubscribe();
38369         this._addTileSubscription.unsubscribe();
38370         this._cameraVisibilitySubscription.unsubscribe();
38371         this._earthControlsSubscription.unsubscribe();
38372         this._moveSubscription.unsubscribe();
38373         this._pointVisibilitySubscription.unsubscribe();
38374         this._positionVisibilitySubscription.unsubscribe();
38375         this._renderSubscription.unsubscribe();
38376         this._tileVisibilitySubscription.unsubscribe();
38377         this._uncacheSubscription.unsubscribe();
38378         this._cameraVisualizationModeSubscription.unsubscribe();
38379         this._ccToModeSubscription.unsubscribe();
38380         this._navigator.stateService.state$.pipe(operators_1.first())
38381             .subscribe(function (state) {
38382             if (state === State_1.default.Earth) {
38383                 _this._navigator.stateService.traverse();
38384             }
38385         });
38386     };
38387     SpatialDataComponent.prototype._getDefaultConfiguration = function () {
38388         return {
38389             cameraVisualizationMode: CameraVisualizationMode_1.default.Default,
38390             camerasVisible: false,
38391             connectedComponents: false,
38392             pointsVisible: true,
38393             positionsVisible: false,
38394             tilesVisible: false,
38395         };
38396     };
38397     SpatialDataComponent.prototype._adjacentComponent = function (hash, depth) {
38398         var hashSet = new Set();
38399         hashSet.add(hash);
38400         this._adjacentComponentRecursive(hashSet, [hash], 0, depth);
38401         return this._setToArray(hashSet);
38402     };
38403     SpatialDataComponent.prototype._adjacentComponentRecursive = function (hashSet, currentHashes, currentDepth, maxDepth) {
38404         if (currentDepth === maxDepth) {
38405             return;
38406         }
38407         var neighbours = [];
38408         for (var _i = 0, currentHashes_1 = currentHashes; _i < currentHashes_1.length; _i++) {
38409             var hash = currentHashes_1[_i];
38410             var hashNeighbours = geohash.neighbours(hash);
38411             for (var direction in hashNeighbours) {
38412                 if (!hashNeighbours.hasOwnProperty(direction)) {
38413                     continue;
38414                 }
38415                 neighbours.push(hashNeighbours[direction]);
38416             }
38417         }
38418         var newHashes = [];
38419         for (var _a = 0, neighbours_1 = neighbours; _a < neighbours_1.length; _a++) {
38420             var neighbour = neighbours_1[_a];
38421             if (!hashSet.has(neighbour)) {
38422                 hashSet.add(neighbour);
38423                 newHashes.push(neighbour);
38424             }
38425         }
38426         this._adjacentComponentRecursive(hashSet, newHashes, currentDepth + 1, maxDepth);
38427     };
38428     SpatialDataComponent.prototype._computeOriginalPosition = function (data, reference) {
38429         return this._geoCoords.geodeticToEnu(data.originalLat, data.originalLon, data.alt, reference.lat, reference.lon, reference.alt);
38430     };
38431     SpatialDataComponent.prototype._computeTileBBox = function (hash, reference) {
38432         var bounds = geohash.bounds(hash);
38433         var sw = this._geoCoords.geodeticToEnu(bounds.sw.lat, bounds.sw.lon, 0, reference.lat, reference.lon, reference.alt);
38434         var ne = this._geoCoords.geodeticToEnu(bounds.ne.lat, bounds.ne.lon, 0, reference.lat, reference.lon, reference.alt);
38435         return [sw, ne];
38436     };
38437     SpatialDataComponent.prototype._createTransform = function (data, reference) {
38438         var translation = Geo_1.Geo.computeTranslation({ alt: data.alt, lat: data.lat, lon: data.lon }, data.rotation, reference);
38439         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, data.cameraProjection);
38440         return transform;
38441     };
38442     SpatialDataComponent.prototype._computeTiles = function (hash, direction) {
38443         var hashSet = new Set();
38444         var directions = ["n", "ne", "e", "se", "s", "sw", "w", "nw"];
38445         this._computeTilesRecursive(hashSet, hash, direction, directions, 0, 2);
38446         return this._setToArray(hashSet);
38447     };
38448     SpatialDataComponent.prototype._computeTilesRecursive = function (hashSet, currentHash, direction, directions, currentDepth, maxDepth) {
38449         hashSet.add(currentHash);
38450         if (currentDepth === maxDepth) {
38451             return;
38452         }
38453         var neighbours = geohash.neighbours(currentHash);
38454         var directionIndex = directions.indexOf(direction);
38455         var length = directions.length;
38456         var directionNeighbours = [
38457             neighbours[directions[this._modulo((directionIndex - 1), length)]],
38458             neighbours[direction],
38459             neighbours[directions[this._modulo((directionIndex + 1), length)]],
38460         ];
38461         for (var _i = 0, directionNeighbours_1 = directionNeighbours; _i < directionNeighbours_1.length; _i++) {
38462             var directionNeighbour = directionNeighbours_1[_i];
38463             this._computeTilesRecursive(hashSet, directionNeighbour, direction, directions, currentDepth + 1, maxDepth);
38464         }
38465     };
38466     SpatialDataComponent.prototype._computeTranslation = function (reconstruction, reference) {
38467         return this._geoCoords.geodeticToEnu(reconstruction.reference_lla.latitude, reconstruction.reference_lla.longitude, reconstruction.reference_lla.altitude, reference.lat, reference.lon, reference.alt);
38468     };
38469     SpatialDataComponent.prototype._modulo = function (a, n) {
38470         return ((a % n) + n) % n;
38471     };
38472     SpatialDataComponent.prototype._setToArray = function (s) {
38473         var a = [];
38474         s.forEach(function (value) {
38475             a.push(value);
38476         });
38477         return a;
38478     };
38479     SpatialDataComponent.componentName = "spatialData";
38480     return SpatialDataComponent;
38481 }(Component_1.Component));
38482 exports.SpatialDataComponent = SpatialDataComponent;
38483 Component_1.ComponentService.register(SpatialDataComponent);
38484 exports.default = SpatialDataComponent;
38485
38486 },{"../../Component":291,"../../Geo":294,"../../Render":297,"../../state/State":438,"../../viewer/PlayService":468,"./CameraVisualizationMode":356,"latlon-geohash":21,"rxjs":43,"rxjs/operators":241}],360:[function(require,module,exports){
38487 "use strict";
38488 Object.defineProperty(exports, "__esModule", { value: true });
38489 var THREE = require("three");
38490 var CameraVisualizationMode_1 = require("./CameraVisualizationMode");
38491 var SpatialDataScene = /** @class */ (function () {
38492     function SpatialDataScene(configuration, scene, raycaster) {
38493         this._scene = !!scene ? scene : new THREE.Scene();
38494         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster(undefined, undefined, 0.8);
38495         this._cameraColors = {};
38496         this._needsRender = false;
38497         this._interactiveObjects = [];
38498         this._nodes = {};
38499         this._tiles = {};
38500         this._tileClusterReconstructions = {};
38501         this._clusterReconstructions = {};
38502         this._cameraVisualizationMode = !!configuration.cameraVisualizationMode ?
38503             configuration.cameraVisualizationMode :
38504             CameraVisualizationMode_1.default.Default;
38505         if (this._cameraVisualizationMode === CameraVisualizationMode_1.default.Default &&
38506             configuration.connectedComponents === true) {
38507             this._cameraVisualizationMode = CameraVisualizationMode_1.default.ConnectedComponent;
38508         }
38509         this._camerasVisible = configuration.camerasVisible;
38510         this._pointsVisible = configuration.pointsVisible;
38511         this._positionsVisible = configuration.positionsVisible;
38512         this._tilesVisible = configuration.tilesVisible;
38513     }
38514     Object.defineProperty(SpatialDataScene.prototype, "needsRender", {
38515         get: function () {
38516             return this._needsRender;
38517         },
38518         enumerable: true,
38519         configurable: true
38520     });
38521     SpatialDataScene.prototype.addClusterReconstruction = function (reconstruction, translation, hash) {
38522         if (this.hasClusterReconstruction(reconstruction.key, hash)) {
38523             return;
38524         }
38525         var key = reconstruction.key;
38526         if (!(key in this._clusterReconstructions)) {
38527             this._clusterReconstructions[key] = {
38528                 points: new THREE.Object3D(),
38529                 tiles: [],
38530             };
38531             this._clusterReconstructions[key].points.visible = this._pointsVisible;
38532             this._clusterReconstructions[key].points.add(this._createClusterPoints(reconstruction, translation));
38533             this._scene.add(this._clusterReconstructions[key].points);
38534         }
38535         if (this._clusterReconstructions[key].tiles.indexOf(hash) === -1) {
38536             this._clusterReconstructions[key].tiles.push(hash);
38537         }
38538         if (!(hash in this._tileClusterReconstructions)) {
38539             this._tileClusterReconstructions[hash] = {
38540                 keys: [],
38541             };
38542         }
38543         if (this._tileClusterReconstructions[hash].keys.indexOf(key) === -1) {
38544             this._tileClusterReconstructions[hash].keys.push(key);
38545         }
38546         this._needsRender = true;
38547     };
38548     SpatialDataScene.prototype.addNode = function (data, transform, originalPosition, hash) {
38549         var key = data.key;
38550         var clusterKey = data.clusterKey;
38551         var sequenceKey = data.sequenceKey;
38552         var connectedComponent = !!data.mergeCC ? data.mergeCC.toString() : "";
38553         if (this.hasNode(key, hash)) {
38554             return;
38555         }
38556         if (!(hash in this._nodes)) {
38557             this._nodes[hash] = {
38558                 cameraKeys: {},
38559                 cameras: new THREE.Object3D(),
38560                 clusters: {},
38561                 connectedComponents: {},
38562                 keys: [],
38563                 positions: new THREE.Object3D(),
38564                 sequences: {},
38565             };
38566             this._nodes[hash].cameras.visible = this._camerasVisible;
38567             this._nodes[hash].positions.visible = this._positionsVisible;
38568             this._scene.add(this._nodes[hash].cameras, this._nodes[hash].positions);
38569         }
38570         if (!(connectedComponent in this._nodes[hash].connectedComponents)) {
38571             this._nodes[hash].connectedComponents[connectedComponent] = [];
38572         }
38573         if (!(clusterKey in this._nodes[hash].clusters)) {
38574             this._nodes[hash].clusters[clusterKey] = [];
38575         }
38576         if (!(sequenceKey in this._nodes[hash].sequences)) {
38577             this._nodes[hash].sequences[sequenceKey] = [];
38578         }
38579         var camera = this._createCamera(transform);
38580         this._nodes[hash].cameras.add(camera);
38581         for (var _i = 0, _a = camera.children; _i < _a.length; _i++) {
38582             var child = _a[_i];
38583             this._nodes[hash].cameraKeys[child.uuid] = key;
38584             this._interactiveObjects.push(child);
38585         }
38586         this._nodes[hash].connectedComponents[connectedComponent].push(camera);
38587         this._nodes[hash].clusters[clusterKey].push(camera);
38588         this._nodes[hash].sequences[sequenceKey].push(camera);
38589         var id = this._getId(clusterKey, connectedComponent, sequenceKey, this._cameraVisualizationMode);
38590         var color = this._getColor(id, this._cameraVisualizationMode);
38591         this._setCameraColor(color, camera);
38592         this._nodes[hash].positions.add(this._createPosition(transform, originalPosition));
38593         this._nodes[hash].keys.push(key);
38594         this._needsRender = true;
38595     };
38596     SpatialDataScene.prototype.addTile = function (tileBBox, hash) {
38597         if (this.hasTile(hash)) {
38598             return;
38599         }
38600         var sw = tileBBox[0];
38601         var ne = tileBBox[1];
38602         var geometry = new THREE.Geometry();
38603         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));
38604         var tile = new THREE.Line(geometry, new THREE.LineBasicMaterial());
38605         this._tiles[hash] = new THREE.Object3D();
38606         this._tiles[hash].visible = this._tilesVisible;
38607         this._tiles[hash].add(tile);
38608         this._scene.add(this._tiles[hash]);
38609         this._needsRender = true;
38610     };
38611     SpatialDataScene.prototype.uncache = function (keepHashes) {
38612         for (var _i = 0, _a = Object.keys(this._tileClusterReconstructions); _i < _a.length; _i++) {
38613             var hash = _a[_i];
38614             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
38615                 continue;
38616             }
38617             this._disposeReconstruction(hash);
38618         }
38619         for (var _b = 0, _c = Object.keys(this._nodes); _b < _c.length; _b++) {
38620             var hash = _c[_b];
38621             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
38622                 continue;
38623             }
38624             this._disposeNodes(hash);
38625         }
38626         for (var _d = 0, _e = Object.keys(this._tiles); _d < _e.length; _d++) {
38627             var hash = _e[_d];
38628             if (!!keepHashes && keepHashes.indexOf(hash) !== -1) {
38629                 continue;
38630             }
38631             this._disposeTile(hash);
38632         }
38633         this._needsRender = true;
38634     };
38635     SpatialDataScene.prototype.hasClusterReconstruction = function (key, hash) {
38636         return key in this._clusterReconstructions &&
38637             this._clusterReconstructions[key].tiles.indexOf(hash) !== -1;
38638     };
38639     SpatialDataScene.prototype.hasTile = function (hash) {
38640         return hash in this._tiles;
38641     };
38642     SpatialDataScene.prototype.hasNode = function (key, hash) {
38643         return hash in this._nodes && this._nodes[hash].keys.indexOf(key) !== -1;
38644     };
38645     SpatialDataScene.prototype.intersectObjects = function (_a, camera) {
38646         var viewportX = _a[0], viewportY = _a[1];
38647         if (!this._camerasVisible) {
38648             return null;
38649         }
38650         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
38651         var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
38652         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
38653             var intersect = intersects_1[_i];
38654             for (var hash in this._nodes) {
38655                 if (!this._nodes.hasOwnProperty(hash)) {
38656                     continue;
38657                 }
38658                 if (intersect.object.uuid in this._nodes[hash].cameraKeys) {
38659                     return this._nodes[hash].cameraKeys[intersect.object.uuid];
38660                 }
38661             }
38662         }
38663         return null;
38664     };
38665     SpatialDataScene.prototype.setCameraVisibility = function (visible) {
38666         if (visible === this._camerasVisible) {
38667             return;
38668         }
38669         for (var hash in this._nodes) {
38670             if (!this._nodes.hasOwnProperty(hash)) {
38671                 continue;
38672             }
38673             this._nodes[hash].cameras.visible = visible;
38674         }
38675         this._camerasVisible = visible;
38676         this._needsRender = true;
38677     };
38678     SpatialDataScene.prototype.setPointVisibility = function (visible) {
38679         if (visible === this._pointsVisible) {
38680             return;
38681         }
38682         for (var key in this._clusterReconstructions) {
38683             if (!this._clusterReconstructions.hasOwnProperty(key)) {
38684                 continue;
38685             }
38686             this._clusterReconstructions[key].points.visible = visible;
38687         }
38688         this._pointsVisible = visible;
38689         this._needsRender = true;
38690     };
38691     SpatialDataScene.prototype.setPositionVisibility = function (visible) {
38692         if (visible === this._positionsVisible) {
38693             return;
38694         }
38695         for (var hash in this._nodes) {
38696             if (!this._nodes.hasOwnProperty(hash)) {
38697                 continue;
38698             }
38699             this._nodes[hash].positions.visible = visible;
38700         }
38701         this._positionsVisible = visible;
38702         this._needsRender = true;
38703     };
38704     SpatialDataScene.prototype.setTileVisibility = function (visible) {
38705         if (visible === this._tilesVisible) {
38706             return;
38707         }
38708         for (var hash in this._tiles) {
38709             if (!this._tiles.hasOwnProperty(hash)) {
38710                 continue;
38711             }
38712             this._tiles[hash].visible = visible;
38713         }
38714         this._tilesVisible = visible;
38715         this._needsRender = true;
38716     };
38717     SpatialDataScene.prototype.setCameraVisualizationMode = function (mode) {
38718         if (mode === this._cameraVisualizationMode) {
38719             return;
38720         }
38721         for (var hash in this._nodes) {
38722             if (!this._nodes.hasOwnProperty(hash)) {
38723                 continue;
38724             }
38725             var cameras = undefined;
38726             if (mode === CameraVisualizationMode_1.default.Cluster) {
38727                 cameras = this._nodes[hash].clusters;
38728             }
38729             else if (mode === CameraVisualizationMode_1.default.ConnectedComponent) {
38730                 cameras = this._nodes[hash].connectedComponents;
38731             }
38732             else if (mode === CameraVisualizationMode_1.default.Sequence) {
38733                 cameras = this._nodes[hash].sequences;
38734             }
38735             else {
38736                 for (var _i = 0, _a = this._nodes[hash].cameras.children; _i < _a.length; _i++) {
38737                     var child = _a[_i];
38738                     var color = this._getColor("", mode);
38739                     this._setCameraColor(color, child);
38740                 }
38741                 continue;
38742             }
38743             for (var id in cameras) {
38744                 if (!cameras.hasOwnProperty(id)) {
38745                     continue;
38746                 }
38747                 var color = this._getColor(id, mode);
38748                 for (var _b = 0, _c = cameras[id]; _b < _c.length; _b++) {
38749                     var camera = _c[_b];
38750                     this._setCameraColor(color, camera);
38751                 }
38752             }
38753         }
38754         this._cameraVisualizationMode = mode;
38755         this._needsRender = true;
38756     };
38757     SpatialDataScene.prototype.render = function (perspectiveCamera, renderer) {
38758         renderer.render(this._scene, perspectiveCamera);
38759         this._needsRender = false;
38760     };
38761     SpatialDataScene.prototype._arrayToFloatArray = function (a, columns) {
38762         var n = a.length;
38763         var f = new Float32Array(n * columns);
38764         for (var i = 0; i < n; i++) {
38765             var item = a[i];
38766             var index = 3 * i;
38767             f[index + 0] = item[0];
38768             f[index + 1] = item[1];
38769             f[index + 2] = item[2];
38770         }
38771         return f;
38772     };
38773     SpatialDataScene.prototype._createAxis = function (transform) {
38774         var north = transform.unprojectBasic([0.5, 0], 0.22);
38775         var south = transform.unprojectBasic([0.5, 1], 0.16);
38776         var axis = new THREE.BufferGeometry();
38777         axis.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray([north, south], 3), 3));
38778         return new THREE.Line(axis, new THREE.LineBasicMaterial());
38779     };
38780     SpatialDataScene.prototype._createCamera = function (transform) {
38781         return !!transform.gpano ?
38782             this._createPanoCamera(transform) :
38783             this._createPrespectiveCamera(transform);
38784     };
38785     SpatialDataScene.prototype._createDiagonals = function (transform, depth) {
38786         var origin = transform.unprojectBasic([0, 0], 0, true);
38787         var topLeft = transform.unprojectBasic([0, 0], depth, true);
38788         var topRight = transform.unprojectBasic([1, 0], depth, true);
38789         var bottomRight = transform.unprojectBasic([1, 1], depth, true);
38790         var bottomLeft = transform.unprojectBasic([0, 1], depth, true);
38791         var vertices = [
38792             origin, topLeft,
38793             origin, topRight,
38794             origin, bottomRight,
38795             origin, bottomLeft,
38796         ];
38797         var diagonals = new THREE.BufferGeometry();
38798         diagonals.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray(vertices, 3), 3));
38799         return new THREE.LineSegments(diagonals, new THREE.LineBasicMaterial());
38800     };
38801     SpatialDataScene.prototype._createFrame = function (transform, depth) {
38802         var vertices2d = [];
38803         vertices2d.push.apply(vertices2d, this._subsample([0, 1], [0, 0], 20));
38804         vertices2d.push.apply(vertices2d, this._subsample([0, 0], [1, 0], 20));
38805         vertices2d.push.apply(vertices2d, this._subsample([1, 0], [1, 1], 20));
38806         var vertices3d = vertices2d
38807             .map(function (basic) {
38808             return transform.unprojectBasic(basic, depth, true);
38809         });
38810         var frame = new THREE.BufferGeometry();
38811         frame.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray(vertices3d, 3), 3));
38812         return new THREE.Line(frame, new THREE.LineBasicMaterial());
38813     };
38814     SpatialDataScene.prototype._createLatitude = function (basicY, numVertices, transform) {
38815         var positions = new Float32Array((numVertices + 1) * 3);
38816         for (var i = 0; i <= numVertices; i++) {
38817             var position = transform.unprojectBasic([i / numVertices, basicY], 0.16);
38818             var index = 3 * i;
38819             positions[index + 0] = position[0];
38820             positions[index + 1] = position[1];
38821             positions[index + 2] = position[2];
38822         }
38823         var latitude = new THREE.BufferGeometry();
38824         latitude.addAttribute("position", new THREE.BufferAttribute(positions, 3));
38825         return new THREE.Line(latitude, new THREE.LineBasicMaterial());
38826     };
38827     SpatialDataScene.prototype._createLongitude = function (basicX, numVertices, transform) {
38828         var positions = new Float32Array((numVertices + 1) * 3);
38829         for (var i = 0; i <= numVertices; i++) {
38830             var position = transform.unprojectBasic([basicX, i / numVertices], 0.16);
38831             var index = 3 * i;
38832             positions[index + 0] = position[0];
38833             positions[index + 1] = position[1];
38834             positions[index + 2] = position[2];
38835         }
38836         var latitude = new THREE.BufferGeometry();
38837         latitude.addAttribute("position", new THREE.BufferAttribute(positions, 3));
38838         return new THREE.Line(latitude, new THREE.LineBasicMaterial());
38839     };
38840     SpatialDataScene.prototype._createPanoCamera = function (transform) {
38841         var camera = new THREE.Object3D();
38842         camera.children.push(this._createAxis(transform));
38843         camera.children.push(this._createLatitude(0.5, 10, transform));
38844         camera.children.push(this._createLongitude(0, 6, transform));
38845         camera.children.push(this._createLongitude(0.25, 6, transform));
38846         camera.children.push(this._createLongitude(0.5, 6, transform));
38847         camera.children.push(this._createLongitude(0.75, 6, transform));
38848         return camera;
38849     };
38850     SpatialDataScene.prototype._createClusterPoints = function (reconstruction, translation) {
38851         var points = Object
38852             .keys(reconstruction.points)
38853             .map(function (key) {
38854             return reconstruction.points[key];
38855         });
38856         var numPoints = points.length;
38857         var positions = new Float32Array(numPoints * 3);
38858         var colors = new Float32Array(numPoints * 3);
38859         for (var i = 0; i < numPoints; i++) {
38860             var index = 3 * i;
38861             var coords = points[i].coordinates;
38862             var point = new THREE.Vector3(coords[0], coords[1], coords[2])
38863                 .add(new THREE.Vector3().fromArray(translation));
38864             positions[index + 0] = point.x;
38865             positions[index + 1] = point.y;
38866             positions[index + 2] = point.z;
38867             var color = points[i].color;
38868             colors[index + 0] = color[0] / 255.0;
38869             colors[index + 1] = color[1] / 255.0;
38870             colors[index + 2] = color[2] / 255.0;
38871         }
38872         var geometry = new THREE.BufferGeometry();
38873         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
38874         geometry.addAttribute("color", new THREE.BufferAttribute(colors, 3));
38875         var material = new THREE.PointsMaterial({
38876             size: 0.1,
38877             vertexColors: THREE.VertexColors,
38878         });
38879         return new THREE.Points(geometry, material);
38880     };
38881     SpatialDataScene.prototype._createPosition = function (transform, originalPosition) {
38882         var computedPosition = transform.unprojectBasic([0, 0], 0);
38883         var vertices = [originalPosition, computedPosition];
38884         var geometry = new THREE.BufferGeometry();
38885         geometry.addAttribute("position", new THREE.BufferAttribute(this._arrayToFloatArray(vertices, 3), 3));
38886         return new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: new THREE.Color(1, 0, 0) }));
38887     };
38888     SpatialDataScene.prototype._createPrespectiveCamera = function (transform) {
38889         var depth = 0.2;
38890         var camera = new THREE.Object3D();
38891         camera.children.push(this._createDiagonals(transform, depth));
38892         camera.children.push(this._createFrame(transform, depth));
38893         return camera;
38894     };
38895     SpatialDataScene.prototype._disposeCameras = function (hash) {
38896         var tileCameras = this._nodes[hash].cameras;
38897         for (var _i = 0, _a = tileCameras.children.slice(); _i < _a.length; _i++) {
38898             var camera = _a[_i];
38899             for (var _b = 0, _c = camera.children; _b < _c.length; _b++) {
38900                 var child = _c[_b];
38901                 child.geometry.dispose();
38902                 child.material.dispose();
38903                 var index = this._interactiveObjects.indexOf(child);
38904                 if (index !== -1) {
38905                     this._interactiveObjects.splice(index, 1);
38906                 }
38907                 else {
38908                     console.warn("Object does not exist (" + child.id + ") for " + hash);
38909                 }
38910             }
38911             tileCameras.remove(camera);
38912         }
38913         this._scene.remove(tileCameras);
38914     };
38915     SpatialDataScene.prototype._disposePoints = function (hash) {
38916         for (var _i = 0, _a = this._tileClusterReconstructions[hash].keys; _i < _a.length; _i++) {
38917             var key = _a[_i];
38918             if (!(key in this._clusterReconstructions)) {
38919                 continue;
38920             }
38921             var index = this._clusterReconstructions[key].tiles.indexOf(hash);
38922             if (index === -1) {
38923                 continue;
38924             }
38925             this._clusterReconstructions[key].tiles.splice(index, 1);
38926             if (this._clusterReconstructions[key].tiles.length > 0) {
38927                 continue;
38928             }
38929             for (var _b = 0, _c = this._clusterReconstructions[key].points.children.slice(); _b < _c.length; _b++) {
38930                 var points = _c[_b];
38931                 points.geometry.dispose();
38932                 points.material.dispose();
38933             }
38934             this._scene.remove(this._clusterReconstructions[key].points);
38935             delete this._clusterReconstructions[key];
38936         }
38937     };
38938     SpatialDataScene.prototype._disposePositions = function (hash) {
38939         var tilePositions = this._nodes[hash].positions;
38940         for (var _i = 0, _a = tilePositions.children.slice(); _i < _a.length; _i++) {
38941             var position = _a[_i];
38942             position.geometry.dispose();
38943             position.material.dispose();
38944             tilePositions.remove(position);
38945         }
38946         this._scene.remove(tilePositions);
38947     };
38948     SpatialDataScene.prototype._disposeNodes = function (hash) {
38949         this._disposeCameras(hash);
38950         this._disposePositions(hash);
38951         delete this._nodes[hash];
38952     };
38953     SpatialDataScene.prototype._disposeReconstruction = function (hash) {
38954         this._disposePoints(hash);
38955         delete this._tileClusterReconstructions[hash];
38956     };
38957     SpatialDataScene.prototype._disposeTile = function (hash) {
38958         var tile = this._tiles[hash];
38959         for (var _i = 0, _a = tile.children.slice(); _i < _a.length; _i++) {
38960             var line = _a[_i];
38961             line.geometry.dispose();
38962             line.material.dispose();
38963             tile.remove(line);
38964         }
38965         this._scene.remove(tile);
38966         delete this._tiles[hash];
38967     };
38968     SpatialDataScene.prototype._getColor = function (id, mode) {
38969         return mode !== CameraVisualizationMode_1.default.Default && id.length > 0 ?
38970             this._getCameraColor(id) :
38971             "#FFFFFF";
38972     };
38973     SpatialDataScene.prototype._getCameraColor = function (id) {
38974         if (!(id in this._cameraColors)) {
38975             this._cameraColors[id] = this._randomColor();
38976         }
38977         return this._cameraColors[id];
38978     };
38979     SpatialDataScene.prototype._getId = function (clusterKey, connectedComponent, sequenceKey, mode) {
38980         switch (mode) {
38981             case CameraVisualizationMode_1.default.Cluster:
38982                 return clusterKey;
38983             case CameraVisualizationMode_1.default.ConnectedComponent:
38984                 return connectedComponent;
38985             case CameraVisualizationMode_1.default.Sequence:
38986                 return sequenceKey;
38987             default:
38988                 return "";
38989         }
38990     };
38991     SpatialDataScene.prototype._interpolate = function (a, b, alpha) {
38992         return a + alpha * (b - a);
38993     };
38994     SpatialDataScene.prototype._randomColor = function () {
38995         return "hsl(" + Math.floor(360 * Math.random()) + ", 100%, 65%)";
38996     };
38997     SpatialDataScene.prototype._setCameraColor = function (color, camera) {
38998         for (var _i = 0, _a = camera.children; _i < _a.length; _i++) {
38999             var child = _a[_i];
39000             child.material.color = new THREE.Color(color);
39001         }
39002     };
39003     SpatialDataScene.prototype._subsample = function (p1, p2, subsamples) {
39004         if (subsamples < 1) {
39005             return [p1, p2];
39006         }
39007         var samples = [];
39008         for (var i = 0; i <= subsamples + 1; i++) {
39009             var p = [];
39010             for (var j = 0; j < 3; j++) {
39011                 p.push(this._interpolate(p1[j], p2[j], i / (subsamples + 1)));
39012             }
39013             samples.push(p);
39014         }
39015         return samples;
39016     };
39017     return SpatialDataScene;
39018 }());
39019 exports.SpatialDataScene = SpatialDataScene;
39020 exports.default = SpatialDataScene;
39021
39022 },{"./CameraVisualizationMode":356,"three":242}],361:[function(require,module,exports){
39023 "use strict";
39024 Object.defineProperty(exports, "__esModule", { value: true });
39025 var GeometryTagError_1 = require("./error/GeometryTagError");
39026 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
39027 var PointGeometry_1 = require("./geometry/PointGeometry");
39028 exports.PointGeometry = PointGeometry_1.PointGeometry;
39029 var PointsGeometry_1 = require("./geometry/PointsGeometry");
39030 exports.PointsGeometry = PointsGeometry_1.PointsGeometry;
39031 var RectGeometry_1 = require("./geometry/RectGeometry");
39032 exports.RectGeometry = RectGeometry_1.RectGeometry;
39033 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
39034 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
39035 var OutlineTag_1 = require("./tag/OutlineTag");
39036 exports.OutlineTag = OutlineTag_1.OutlineTag;
39037 var ExtremePointTag_1 = require("./tag/ExtremePointTag");
39038 exports.ExtremePointTag = ExtremePointTag_1.ExtremePointTag;
39039 var SpotTag_1 = require("./tag/SpotTag");
39040 exports.SpotTag = SpotTag_1.SpotTag;
39041 var TagDomain_1 = require("./tag/TagDomain");
39042 exports.TagDomain = TagDomain_1.TagDomain;
39043 var TagComponent_1 = require("./TagComponent");
39044 exports.TagComponent = TagComponent_1.TagComponent;
39045 var TagMode_1 = require("./TagMode");
39046 exports.TagMode = TagMode_1.TagMode;
39047
39048 },{"./TagComponent":362,"./TagMode":365,"./error/GeometryTagError":369,"./geometry/PointGeometry":371,"./geometry/PointsGeometry":372,"./geometry/PolygonGeometry":373,"./geometry/RectGeometry":374,"./tag/ExtremePointTag":388,"./tag/OutlineTag":392,"./tag/SpotTag":395,"./tag/TagDomain":397}],362:[function(require,module,exports){
39049 "use strict";
39050 var __extends = (this && this.__extends) || (function () {
39051     var extendStatics = function (d, b) {
39052         extendStatics = Object.setPrototypeOf ||
39053             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
39054             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
39055         return extendStatics(d, b);
39056     }
39057     return function (d, b) {
39058         extendStatics(d, b);
39059         function __() { this.constructor = d; }
39060         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
39061     };
39062 })();
39063 Object.defineProperty(exports, "__esModule", { value: true });
39064 var rxjs_1 = require("rxjs");
39065 var operators_1 = require("rxjs/operators");
39066 var when = require("when");
39067 var Component_1 = require("../../Component");
39068 var Geo_1 = require("../../Geo");
39069 var Render_1 = require("../../Render");
39070 /**
39071  * @class TagComponent
39072  *
39073  * @classdesc Component for showing and editing tags with different
39074  * geometries composed from 2D basic image coordinates (see the
39075  * {@link Viewer} class documentation for more information about coordinate
39076  * systems).
39077  *
39078  * The `add` method is used for adding new tags or replacing
39079  * tags already in the set. Tags are removed by id.
39080  *
39081  * If a tag already in the set has the same
39082  * id as one of the tags added, the old tag will be removed and
39083  * the added tag will take its place.
39084  *
39085  * The tag component mode can be set to either be non interactive or
39086  * to be in creating mode of a certain geometry type.
39087  *
39088  * The tag properties can be updated at any time and the change will
39089  * be visibile immediately.
39090  *
39091  * Tags are only relevant to a single image because they are based on
39092  * 2D basic image coordinates. Tags related to a certain image should
39093  * be removed when the viewer is moved to another node.
39094  *
39095  * To retrive and use the tag component
39096  *
39097  * @example
39098  * ```
39099  * var viewer = new Mapillary.Viewer(
39100  *     "<element-id>",
39101  *     "<client-id>",
39102  *     "<my key>",
39103  *     { component: { tag: true } });
39104  *
39105  * var tagComponent = viewer.getComponent("tag");
39106  * ```
39107  */
39108 var TagComponent = /** @class */ (function (_super) {
39109     __extends(TagComponent, _super);
39110     /** @ignore */
39111     function TagComponent(name, container, navigator) {
39112         var _this = _super.call(this, name, container, navigator) || this;
39113         _this._tagDomRenderer = new Component_1.TagDOMRenderer();
39114         _this._tagScene = new Component_1.TagScene();
39115         _this._tagSet = new Component_1.TagSet();
39116         _this._tagCreator = new Component_1.TagCreator(_this, navigator);
39117         _this._viewportCoords = new Geo_1.ViewportCoords();
39118         _this._createHandlers = {
39119             "CreatePoint": new Component_1.CreatePointHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
39120             "CreatePoints": new Component_1.CreatePointsHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
39121             "CreatePolygon": new Component_1.CreatePolygonHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
39122             "CreateRect": new Component_1.CreateRectHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
39123             "CreateRectDrag": new Component_1.CreateRectDragHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
39124             "Default": undefined,
39125         };
39126         _this._editVertexHandler = new Component_1.EditVertexHandler(_this, container, navigator, _this._viewportCoords, _this._tagSet);
39127         _this._renderTags$ = _this._tagSet.changed$.pipe(operators_1.map(function (tagSet) {
39128             var tags = tagSet.getAll();
39129             // ensure that tags are always rendered in the same order
39130             // to avoid hover tracking problems on first resize.
39131             tags.sort(function (t1, t2) {
39132                 var id1 = t1.tag.id;
39133                 var id2 = t2.tag.id;
39134                 if (id1 < id2) {
39135                     return -1;
39136                 }
39137                 if (id1 > id2) {
39138                     return 1;
39139                 }
39140                 return 0;
39141             });
39142             return tags;
39143         }), operators_1.share());
39144         _this._tagChanged$ = _this._renderTags$.pipe(operators_1.switchMap(function (tags) {
39145             return rxjs_1.from(tags).pipe(operators_1.mergeMap(function (tag) {
39146                 return rxjs_1.merge(tag.tag.changed$, tag.tag.geometryChanged$);
39147             }));
39148         }), operators_1.share());
39149         _this._renderTagGLChanged$ = _this._renderTags$.pipe(operators_1.switchMap(function (tags) {
39150             return rxjs_1.from(tags).pipe(operators_1.mergeMap(function (tag) {
39151                 return tag.glObjectsChanged$;
39152             }));
39153         }), operators_1.share());
39154         _this._createGeometryChanged$ = _this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
39155             return tag != null ?
39156                 tag.geometryChanged$ :
39157                 rxjs_1.empty();
39158         }), operators_1.share());
39159         _this._createGLObjectsChanged$ = _this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
39160             return tag != null ?
39161                 tag.glObjectsChanged$ :
39162                 rxjs_1.empty();
39163         }), operators_1.share());
39164         _this._creatingConfiguration$ = _this._configuration$.pipe(operators_1.distinctUntilChanged(function (c1, c2) {
39165             return c1.mode === c2.mode;
39166         }, function (configuration) {
39167             return {
39168                 createColor: configuration.createColor,
39169                 mode: configuration.mode,
39170             };
39171         }), operators_1.publishReplay(1), operators_1.refCount());
39172         _this._creatingConfiguration$
39173             .subscribe(function (configuration) {
39174             _this.fire(TagComponent.modechanged, configuration.mode);
39175         });
39176         return _this;
39177     }
39178     /**
39179      * Add tags to the tag set or replace tags in the tag set.
39180      *
39181      * @description If a tag already in the set has the same
39182      * id as one of the tags added, the old tag will be removed
39183      * the added tag will take its place.
39184      *
39185      * @param {Array<Tag>} tags - Tags to add.
39186      *
39187      * @example ```tagComponent.add([tag1, tag2]);```
39188      */
39189     TagComponent.prototype.add = function (tags) {
39190         var _this = this;
39191         if (this._activated) {
39192             this._navigator.stateService.currentTransform$.pipe(operators_1.first())
39193                 .subscribe(function (transform) {
39194                 _this._tagSet.add(tags, transform);
39195                 var renderTags = tags
39196                     .map(function (tag) {
39197                     return _this._tagSet.get(tag.id);
39198                 });
39199                 _this._tagScene.add(renderTags);
39200             });
39201         }
39202         else {
39203             this._tagSet.addDeactivated(tags);
39204         }
39205     };
39206     /**
39207      * Calculate the smallest rectangle containing all the points
39208      * in the points geometry.
39209      *
39210      * @description The result may be different depending on if the
39211      * current node is an equirectangular panorama or not. If the
39212      * current node is an equirectangular panorama the rectangle may
39213      * wrap the horizontal border of the image.
39214      *
39215      * @returns {Promise<Array<number>>} Promise to the rectangle
39216      * on the format specified for the {@link RectGeometry} in basic
39217      * coordinates.
39218      */
39219     TagComponent.prototype.calculateRect = function (geometry) {
39220         var _this = this;
39221         return when.promise(function (resolve, reject) {
39222             _this._navigator.stateService.currentTransform$.pipe(operators_1.first(), operators_1.map(function (transform) {
39223                 return geometry.getRect2d(transform);
39224             }))
39225                 .subscribe(function (rect) {
39226                 resolve(rect);
39227             }, function (error) {
39228                 reject(error);
39229             });
39230         });
39231     };
39232     /**
39233      * Force the creation of a geometry programatically using its
39234      * current vertices.
39235      *
39236      * @description The method only has an effect when the tag
39237      * mode is either of the following modes:
39238      *
39239      * TagMode.CreatePoints
39240      * TagMode.CreatePolygon
39241      * TagMode.CreateRect
39242      * TagMode.CreateRectDrag
39243      *
39244      * In the case of points or polygon creation, only the created
39245      * vertices are used, i.e. the mouse position is disregarded.
39246      *
39247      * In the case of rectangle creation the position of the mouse
39248      * at the time of the method call is used as one of the vertices
39249      * defining the rectangle.
39250      *
39251      * @fires TagComponent.geometrycreated
39252      *
39253      * @example
39254      * ```
39255      * tagComponent.on("geometrycreated", function(geometry) {
39256      *     console.log(geometry);
39257      * });
39258      *
39259      * tagComponent.create();
39260      * ```
39261      */
39262     TagComponent.prototype.create = function () {
39263         this._tagCreator.replayedTag$.pipe(operators_1.first(), operators_1.filter(function (tag) {
39264             return !!tag;
39265         }))
39266             .subscribe(function (tag) {
39267             tag.create();
39268         });
39269     };
39270     /**
39271      * Change the current tag mode.
39272      *
39273      * @description Change the tag mode to one of the create modes for creating new geometries.
39274      *
39275      * @param {TagMode} mode - New tag mode.
39276      *
39277      * @fires TagComponent#modechanged
39278      *
39279      * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);```
39280      */
39281     TagComponent.prototype.changeMode = function (mode) {
39282         this.configure({ mode: mode });
39283     };
39284     /**
39285      * Returns the tag in the tag set with the specified id, or
39286      * undefined if the id matches no tag.
39287      *
39288      * @param {string} tagId - Id of the tag.
39289      *
39290      * @example ```var tag = tagComponent.get("tagId");```
39291      */
39292     TagComponent.prototype.get = function (tagId) {
39293         if (this._activated) {
39294             var renderTag = this._tagSet.get(tagId);
39295             return renderTag !== undefined ? renderTag.tag : undefined;
39296         }
39297         else {
39298             return this._tagSet.getDeactivated(tagId);
39299         }
39300     };
39301     /**
39302      * Returns an array of all tags.
39303      *
39304      * @example ```var tags = tagComponent.getAll();```
39305      */
39306     TagComponent.prototype.getAll = function () {
39307         if (this.activated) {
39308             return this._tagSet
39309                 .getAll()
39310                 .map(function (renderTag) {
39311                 return renderTag.tag;
39312             });
39313         }
39314         else {
39315             return this._tagSet.getAllDeactivated();
39316         }
39317     };
39318     /**
39319      * Returns an array of tag ids for tags that contain the specified point.
39320      *
39321      * @description The pixel point must lie inside the polygon or rectangle
39322      * of an added tag for the tag id to be returned. Tag ids for
39323      * tags that do not have a fill will also be returned if the point is inside
39324      * the geometry of the tag. Tags with point geometries can not be retrieved.
39325      *
39326      * No tag ids will be returned for polygons rendered in cropped panoramas or
39327      * rectangles rendered in panoramas.
39328      *
39329      * Notice that the pixelPoint argument requires x, y coordinates from pixel space.
39330      *
39331      * With this function, you can use the coordinates provided by mouse
39332      * events to get information out of the tag component.
39333      *
39334      * If no tag at exist the pixel point, an empty array will be returned.
39335      *
39336      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
39337      * @returns {Promise<Array<string>>} Promise to the ids of the tags that
39338      * contain the specified pixel point.
39339      *
39340      * @example
39341      * ```
39342      * tagComponent.getTagIdsAt([100, 100])
39343      *     .then((tagIds) => { console.log(tagIds); });
39344      * ```
39345      */
39346     TagComponent.prototype.getTagIdsAt = function (pixelPoint) {
39347         var _this = this;
39348         return when.promise(function (resolve, reject) {
39349             _this._container.renderService.renderCamera$.pipe(operators_1.first(), operators_1.map(function (render) {
39350                 var viewport = _this._viewportCoords
39351                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
39352                 var ids = _this._tagScene.intersectObjects(viewport, render.perspective);
39353                 return ids;
39354             }))
39355                 .subscribe(function (ids) {
39356                 resolve(ids);
39357             }, function (error) {
39358                 reject(error);
39359             });
39360         });
39361     };
39362     /**
39363      * Check if a tag exist in the tag set.
39364      *
39365      * @param {string} tagId - Id of the tag.
39366      *
39367      * @example ```var tagExists = tagComponent.has("tagId");```
39368      */
39369     TagComponent.prototype.has = function (tagId) {
39370         return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
39371     };
39372     /**
39373      * Remove tags with the specified ids from the tag set.
39374      *
39375      * @param {Array<string>} tagIds - Ids for tags to remove.
39376      *
39377      * @example ```tagComponent.remove(["id-1", "id-2"]);```
39378      */
39379     TagComponent.prototype.remove = function (tagIds) {
39380         if (this._activated) {
39381             this._tagSet.remove(tagIds);
39382             this._tagScene.remove(tagIds);
39383         }
39384         else {
39385             this._tagSet.removeDeactivated(tagIds);
39386         }
39387     };
39388     /**
39389      * Remove all tags from the tag set.
39390      *
39391      * @example ```tagComponent.removeAll();```
39392      */
39393     TagComponent.prototype.removeAll = function () {
39394         if (this._activated) {
39395             this._tagSet.removeAll();
39396             this._tagScene.removeAll();
39397         }
39398         else {
39399             this._tagSet.removeAllDeactivated();
39400         }
39401     };
39402     TagComponent.prototype._activate = function () {
39403         var _this = this;
39404         this._editVertexHandler.enable();
39405         var handlerGeometryCreated$ = rxjs_1.from(Object.keys(this._createHandlers)).pipe(operators_1.map(function (key) {
39406             return _this._createHandlers[key];
39407         }), operators_1.filter(function (handler) {
39408             return !!handler;
39409         }), operators_1.mergeMap(function (handler) {
39410             return handler.geometryCreated$;
39411         }), operators_1.share());
39412         this._fireGeometryCreatedSubscription = handlerGeometryCreated$
39413             .subscribe(function (geometry) {
39414             _this.fire(TagComponent.geometrycreated, geometry);
39415         });
39416         this._fireCreateGeometryEventSubscription = this._tagCreator.tag$.pipe(operators_1.skipWhile(function (tag) {
39417             return tag == null;
39418         }), operators_1.distinctUntilChanged())
39419             .subscribe(function (tag) {
39420             var eventType = tag != null ?
39421                 TagComponent.creategeometrystart :
39422                 TagComponent.creategeometryend;
39423             _this.fire(eventType, _this);
39424         });
39425         this._handlerStopCreateSubscription = handlerGeometryCreated$
39426             .subscribe(function () {
39427             _this.changeMode(Component_1.TagMode.Default);
39428         });
39429         this._handlerEnablerSubscription = this._creatingConfiguration$
39430             .subscribe(function (configuration) {
39431             _this._disableCreateHandlers();
39432             var mode = Component_1.TagMode[configuration.mode];
39433             var handler = _this._createHandlers[mode];
39434             if (!!handler) {
39435                 handler.enable();
39436             }
39437         });
39438         this._fireTagsChangedSubscription = this._renderTags$
39439             .subscribe(function () {
39440             _this.fire(TagComponent.tagschanged, _this);
39441         });
39442         this._stopCreateSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
39443             return tag != null ?
39444                 tag.aborted$.pipe(operators_1.map(function () { return null; })) :
39445                 rxjs_1.empty();
39446         }))
39447             .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); });
39448         this._setGLCreateTagSubscription = this._tagCreator.tag$
39449             .subscribe(function (tag) {
39450             if (_this._tagScene.hasCreateTag()) {
39451                 _this._tagScene.removeCreateTag();
39452             }
39453             if (tag != null) {
39454                 _this._tagScene.addCreateTag(tag);
39455             }
39456         });
39457         this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$
39458             .subscribe(function (tag) {
39459             _this._tagScene.updateCreateTagObjects(tag);
39460         });
39461         this._updateGLObjectsSubscription = this._renderTagGLChanged$
39462             .subscribe(function (tag) {
39463             _this._tagScene.updateObjects(tag);
39464         });
39465         this._updateTagSceneSubscription = this._tagChanged$
39466             .subscribe(function () {
39467             _this._tagScene.update();
39468         });
39469         this._domSubscription = rxjs_1.combineLatest(this._renderTags$.pipe(operators_1.startWith([]), operators_1.tap(function () {
39470             _this._container.domRenderer.render$.next({
39471                 name: _this._name,
39472                 vnode: _this._tagDomRenderer.clear(),
39473             });
39474         })), 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) {
39475             var renderTags = _a[0], rc = _a[1], atlas = _a[2], size = _a[3], ct = _a[5];
39476             return {
39477                 name: _this._name,
39478                 vnode: _this._tagDomRenderer.render(renderTags, ct, atlas, rc.perspective, size),
39479             };
39480         }))
39481             .subscribe(this._container.domRenderer.render$);
39482         this._glSubscription = this._navigator.stateService.currentState$.pipe(operators_1.map(function (frame) {
39483             var tagScene = _this._tagScene;
39484             return {
39485                 name: _this._name,
39486                 render: {
39487                     frameId: frame.id,
39488                     needsRender: tagScene.needsRender,
39489                     render: tagScene.render.bind(tagScene),
39490                     stage: Render_1.GLRenderStage.Foreground,
39491                 },
39492             };
39493         }))
39494             .subscribe(this._container.glRenderer.render$);
39495         this._navigator.stateService.currentTransform$.pipe(operators_1.first())
39496             .subscribe(function (transform) {
39497             _this._tagSet.activate(transform);
39498             _this._tagScene.add(_this._tagSet.getAll());
39499         });
39500     };
39501     TagComponent.prototype._deactivate = function () {
39502         this._editVertexHandler.disable();
39503         this._disableCreateHandlers();
39504         this._tagScene.clear();
39505         this._tagSet.deactivate();
39506         this._tagCreator.delete$.next(null);
39507         this._updateGLObjectsSubscription.unsubscribe();
39508         this._updateTagSceneSubscription.unsubscribe();
39509         this._stopCreateSubscription.unsubscribe();
39510         this._setGLCreateTagSubscription.unsubscribe();
39511         this._createGLObjectsChangedSubscription.unsubscribe();
39512         this._domSubscription.unsubscribe();
39513         this._glSubscription.unsubscribe();
39514         this._fireCreateGeometryEventSubscription.unsubscribe();
39515         this._fireGeometryCreatedSubscription.unsubscribe();
39516         this._fireTagsChangedSubscription.unsubscribe();
39517         this._handlerStopCreateSubscription.unsubscribe();
39518         this._handlerEnablerSubscription.unsubscribe();
39519         this._container.element.classList.remove("component-tag-create");
39520     };
39521     TagComponent.prototype._getDefaultConfiguration = function () {
39522         return {
39523             createColor: 0xFFFFFF,
39524             indicatePointsCompleter: true,
39525             mode: Component_1.TagMode.Default,
39526         };
39527     };
39528     TagComponent.prototype._disableCreateHandlers = function () {
39529         var createHandlers = this._createHandlers;
39530         for (var key in createHandlers) {
39531             if (!createHandlers.hasOwnProperty(key)) {
39532                 continue;
39533             }
39534             var handler = createHandlers[key];
39535             if (!!handler) {
39536                 handler.disable();
39537             }
39538         }
39539     };
39540     /** @inheritdoc */
39541     TagComponent.componentName = "tag";
39542     /**
39543      * Event fired when an interaction to create a geometry ends.
39544      *
39545      * @description A create interaction can by a geometry being created
39546      * or by the creation being aborted.
39547      *
39548      * @event TagComponent#creategeometryend
39549      * @type {TagComponent} Tag component.
39550      * @example
39551      * ```
39552      * tagComponent.on("creategeometryend", function(component) {
39553      *     console.log(component);
39554      * });
39555      * ```
39556      */
39557     TagComponent.creategeometryend = "creategeometryend";
39558     /**
39559      * Event fired when an interaction to create a geometry starts.
39560      *
39561      * @description A create interaction starts when the first vertex
39562      * is created in the geometry.
39563      *
39564      * @event TagComponent#creategeometrystart
39565      * @type {TagComponent} Tag component.
39566      * @example
39567      * ```
39568      * tagComponent.on("creategeometrystart", function(component) {
39569      *     console.log(component);
39570      * });
39571      * ```
39572      */
39573     TagComponent.creategeometrystart = "creategeometrystart";
39574     /**
39575      * Event fired when the create mode is changed.
39576      *
39577      * @event TagComponent#modechanged
39578      * @type {TagMode} Tag mode
39579      * @example
39580      * ```
39581      * tagComponent.on("modechanged", function(mode) {
39582      *     console.log(mode);
39583      * });
39584      * ```
39585      */
39586     TagComponent.modechanged = "modechanged";
39587     /**
39588      * Event fired when a geometry has been created.
39589      *
39590      * @event TagComponent#geometrycreated
39591      * @type {Geometry} Created geometry.
39592      * @example
39593      * ```
39594      * tagComponent.on("geometrycreated", function(geometry) {
39595      *     console.log(geometry);
39596      * });
39597      * ```
39598      */
39599     TagComponent.geometrycreated = "geometrycreated";
39600     /**
39601      * Event fired when the tags collection has changed.
39602      *
39603      * @event TagComponent#tagschanged
39604      * @type {TagComponent} Tag component.
39605      * @example
39606      * ```
39607      * tagComponent.on("tagschanged", function(component) {
39608      *     console.log(component.getAll());
39609      * });
39610      * ```
39611      */
39612     TagComponent.tagschanged = "tagschanged";
39613     return TagComponent;
39614 }(Component_1.Component));
39615 exports.TagComponent = TagComponent;
39616 Component_1.ComponentService.register(TagComponent);
39617 exports.default = TagComponent;
39618
39619 },{"../../Component":291,"../../Geo":294,"../../Render":297,"rxjs":43,"rxjs/operators":241,"when":288}],363:[function(require,module,exports){
39620 "use strict";
39621 Object.defineProperty(exports, "__esModule", { value: true });
39622 var operators_1 = require("rxjs/operators");
39623 var rxjs_1 = require("rxjs");
39624 var Component_1 = require("../../Component");
39625 var TagCreator = /** @class */ (function () {
39626     function TagCreator(component, navigator) {
39627         this._component = component;
39628         this._navigator = navigator;
39629         this._tagOperation$ = new rxjs_1.Subject();
39630         this._createPoints$ = new rxjs_1.Subject();
39631         this._createPolygon$ = new rxjs_1.Subject();
39632         this._createRect$ = new rxjs_1.Subject();
39633         this._delete$ = new rxjs_1.Subject();
39634         this._tag$ = this._tagOperation$.pipe(operators_1.scan(function (tag, operation) {
39635             return operation(tag);
39636         }, null), operators_1.share());
39637         this._replayedTag$ = this._tag$.pipe(operators_1.publishReplay(1), operators_1.refCount());
39638         this._replayedTag$.subscribe();
39639         this._createPoints$.pipe(operators_1.withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
39640             var coord = _a[0], conf = _a[1], transform = _a[2];
39641             return function () {
39642                 var geometry = new Component_1.PointsGeometry([
39643                     [coord[0], coord[1]],
39644                     [coord[0], coord[1]],
39645                 ]);
39646                 return new Component_1.ExtremePointCreateTag(geometry, {
39647                     color: conf.createColor,
39648                     indicateCompleter: conf.indicatePointsCompleter,
39649                 }, transform);
39650             };
39651         }))
39652             .subscribe(this._tagOperation$);
39653         this._createRect$.pipe(operators_1.withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
39654             var coord = _a[0], conf = _a[1], transform = _a[2];
39655             return function () {
39656                 var geometry = new Component_1.RectGeometry([
39657                     coord[0],
39658                     coord[1],
39659                     coord[0],
39660                     coord[1],
39661                 ]);
39662                 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
39663             };
39664         }))
39665             .subscribe(this._tagOperation$);
39666         this._createPolygon$.pipe(operators_1.withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
39667             var coord = _a[0], conf = _a[1], transform = _a[2];
39668             return function () {
39669                 var geometry = new Component_1.PolygonGeometry([
39670                     [coord[0], coord[1]],
39671                     [coord[0], coord[1]],
39672                     [coord[0], coord[1]],
39673                 ]);
39674                 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
39675             };
39676         }))
39677             .subscribe(this._tagOperation$);
39678         this._delete$.pipe(operators_1.map(function () {
39679             return function () {
39680                 return null;
39681             };
39682         }))
39683             .subscribe(this._tagOperation$);
39684     }
39685     Object.defineProperty(TagCreator.prototype, "createRect$", {
39686         get: function () {
39687             return this._createRect$;
39688         },
39689         enumerable: true,
39690         configurable: true
39691     });
39692     Object.defineProperty(TagCreator.prototype, "createPolygon$", {
39693         get: function () {
39694             return this._createPolygon$;
39695         },
39696         enumerable: true,
39697         configurable: true
39698     });
39699     Object.defineProperty(TagCreator.prototype, "createPoints$", {
39700         get: function () {
39701             return this._createPoints$;
39702         },
39703         enumerable: true,
39704         configurable: true
39705     });
39706     Object.defineProperty(TagCreator.prototype, "delete$", {
39707         get: function () {
39708             return this._delete$;
39709         },
39710         enumerable: true,
39711         configurable: true
39712     });
39713     Object.defineProperty(TagCreator.prototype, "tag$", {
39714         get: function () {
39715             return this._tag$;
39716         },
39717         enumerable: true,
39718         configurable: true
39719     });
39720     Object.defineProperty(TagCreator.prototype, "replayedTag$", {
39721         get: function () {
39722             return this._replayedTag$;
39723         },
39724         enumerable: true,
39725         configurable: true
39726     });
39727     return TagCreator;
39728 }());
39729 exports.TagCreator = TagCreator;
39730 exports.default = TagCreator;
39731
39732 },{"../../Component":291,"rxjs":43,"rxjs/operators":241}],364:[function(require,module,exports){
39733 "use strict";
39734 Object.defineProperty(exports, "__esModule", { value: true });
39735 var vd = require("virtual-dom");
39736 var TagDOMRenderer = /** @class */ (function () {
39737     function TagDOMRenderer() {
39738     }
39739     TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, size) {
39740         var vNodes = [];
39741         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
39742             var tag = tags_1[_i];
39743             vNodes = vNodes.concat(tag.getDOMObjects(atlas, camera, size));
39744         }
39745         if (createTag != null) {
39746             vNodes = vNodes.concat(createTag.getDOMObjects(camera, size));
39747         }
39748         return vd.h("div.TagContainer", {}, vNodes);
39749     };
39750     TagDOMRenderer.prototype.clear = function () {
39751         return vd.h("div", {}, []);
39752     };
39753     return TagDOMRenderer;
39754 }());
39755 exports.TagDOMRenderer = TagDOMRenderer;
39756
39757 },{"virtual-dom":247}],365:[function(require,module,exports){
39758 "use strict";
39759 Object.defineProperty(exports, "__esModule", { value: true });
39760 /**
39761  * Enumeration for tag modes
39762  * @enum {number}
39763  * @readonly
39764  * @description Modes for the interaction in the tag component.
39765  */
39766 var TagMode;
39767 (function (TagMode) {
39768     /**
39769      * Disables creating tags.
39770      */
39771     TagMode[TagMode["Default"] = 0] = "Default";
39772     /**
39773      * Create a point geometry through a click.
39774      */
39775     TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint";
39776     /**
39777      * Create a points geometry through clicks.
39778      */
39779     TagMode[TagMode["CreatePoints"] = 2] = "CreatePoints";
39780     /**
39781      * Create a polygon geometry through clicks.
39782      */
39783     TagMode[TagMode["CreatePolygon"] = 3] = "CreatePolygon";
39784     /**
39785      * Create a rect geometry through clicks.
39786      */
39787     TagMode[TagMode["CreateRect"] = 4] = "CreateRect";
39788     /**
39789      * Create a rect geometry through drag.
39790      *
39791      * @description Claims the mouse which results in mouse handlers like
39792      * drag pan and scroll zoom becoming inactive.
39793      */
39794     TagMode[TagMode["CreateRectDrag"] = 5] = "CreateRectDrag";
39795 })(TagMode = exports.TagMode || (exports.TagMode = {}));
39796 exports.default = TagMode;
39797
39798 },{}],366:[function(require,module,exports){
39799 "use strict";
39800 Object.defineProperty(exports, "__esModule", { value: true });
39801 var TagOperation;
39802 (function (TagOperation) {
39803     TagOperation[TagOperation["None"] = 0] = "None";
39804     TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
39805     TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
39806 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
39807 exports.default = TagOperation;
39808
39809 },{}],367:[function(require,module,exports){
39810 "use strict";
39811 Object.defineProperty(exports, "__esModule", { value: true });
39812 var THREE = require("three");
39813 var TagScene = /** @class */ (function () {
39814     function TagScene(scene, raycaster) {
39815         this._createTag = null;
39816         this._needsRender = false;
39817         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
39818         this._scene = !!scene ? scene : new THREE.Scene();
39819         this._objectTags = {};
39820         this._retrievableObjects = [];
39821         this._tags = {};
39822     }
39823     Object.defineProperty(TagScene.prototype, "needsRender", {
39824         get: function () {
39825             return this._needsRender;
39826         },
39827         enumerable: true,
39828         configurable: true
39829     });
39830     TagScene.prototype.add = function (tags) {
39831         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
39832             var tag = tags_1[_i];
39833             if (tag.tag.id in this._tags) {
39834                 this._remove(tag.tag.id);
39835             }
39836             this._add(tag);
39837         }
39838         this._needsRender = true;
39839     };
39840     TagScene.prototype.addCreateTag = function (tag) {
39841         for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) {
39842             var object = _a[_i];
39843             this._scene.add(object);
39844         }
39845         this._createTag = { tag: tag, objects: tag.glObjects };
39846         this._needsRender = true;
39847     };
39848     TagScene.prototype.clear = function () {
39849         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
39850             var id = _a[_i];
39851             this._remove(id);
39852         }
39853         this._needsRender = false;
39854     };
39855     TagScene.prototype.get = function (id) {
39856         return this.has(id) ? this._tags[id].tag : undefined;
39857     };
39858     TagScene.prototype.has = function (id) {
39859         return id in this._tags;
39860     };
39861     TagScene.prototype.hasCreateTag = function () {
39862         return this._createTag != null;
39863     };
39864     TagScene.prototype.intersectObjects = function (_a, camera) {
39865         var viewportX = _a[0], viewportY = _a[1];
39866         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
39867         var intersects = this._raycaster.intersectObjects(this._retrievableObjects);
39868         var intersectedIds = [];
39869         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
39870             var intersect = intersects_1[_i];
39871             if (intersect.object.uuid in this._objectTags) {
39872                 intersectedIds.push(this._objectTags[intersect.object.uuid]);
39873             }
39874         }
39875         return intersectedIds;
39876     };
39877     TagScene.prototype.remove = function (ids) {
39878         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
39879             var id = ids_1[_i];
39880             this._remove(id);
39881         }
39882         this._needsRender = true;
39883     };
39884     TagScene.prototype.removeAll = function () {
39885         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
39886             var id = _a[_i];
39887             this._remove(id);
39888         }
39889         this._needsRender = true;
39890     };
39891     TagScene.prototype.removeCreateTag = function () {
39892         if (this._createTag == null) {
39893             return;
39894         }
39895         for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
39896             var object = _a[_i];
39897             this._scene.remove(object);
39898         }
39899         this._createTag.tag.dispose();
39900         this._createTag = null;
39901         this._needsRender = true;
39902     };
39903     TagScene.prototype.render = function (perspectiveCamera, renderer) {
39904         renderer.render(this._scene, perspectiveCamera);
39905         this._needsRender = false;
39906     };
39907     TagScene.prototype.update = function () {
39908         this._needsRender = true;
39909     };
39910     TagScene.prototype.updateCreateTagObjects = function (tag) {
39911         if (this._createTag.tag !== tag) {
39912             throw new Error("Create tags do not have the same reference.");
39913         }
39914         for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
39915             var object = _a[_i];
39916             this._scene.remove(object);
39917         }
39918         for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) {
39919             var object = _c[_b];
39920             this._scene.add(object);
39921         }
39922         this._createTag.objects = tag.glObjects;
39923         this._needsRender = true;
39924     };
39925     TagScene.prototype.updateObjects = function (tag) {
39926         var id = tag.tag.id;
39927         if (this._tags[id].tag !== tag) {
39928             throw new Error("Tags do not have the same reference.");
39929         }
39930         var tagObjects = this._tags[id];
39931         this._removeObjects(tagObjects);
39932         delete this._tags[id];
39933         this._add(tag);
39934         this._needsRender = true;
39935     };
39936     TagScene.prototype._add = function (tag) {
39937         var id = tag.tag.id;
39938         var tagObjects = { tag: tag, objects: [], retrievableObjects: [] };
39939         this._tags[id] = tagObjects;
39940         for (var _i = 0, _a = tag.getGLObjects(); _i < _a.length; _i++) {
39941             var object = _a[_i];
39942             tagObjects.objects.push(object);
39943             this._scene.add(object);
39944         }
39945         for (var _b = 0, _c = tag.getRetrievableObjects(); _b < _c.length; _b++) {
39946             var retrievableObject = _c[_b];
39947             tagObjects.retrievableObjects.push(retrievableObject);
39948             this._retrievableObjects.push(retrievableObject);
39949             this._objectTags[retrievableObject.uuid] = tag.tag.id;
39950         }
39951     };
39952     TagScene.prototype._remove = function (id) {
39953         var tagObjects = this._tags[id];
39954         this._removeObjects(tagObjects);
39955         tagObjects.tag.dispose();
39956         delete this._tags[id];
39957     };
39958     TagScene.prototype._removeObjects = function (tagObjects) {
39959         for (var _i = 0, _a = tagObjects.objects; _i < _a.length; _i++) {
39960             var object = _a[_i];
39961             this._scene.remove(object);
39962         }
39963         for (var _b = 0, _c = tagObjects.retrievableObjects; _b < _c.length; _b++) {
39964             var retrievableObject = _c[_b];
39965             var index = this._retrievableObjects.indexOf(retrievableObject);
39966             if (index !== -1) {
39967                 this._retrievableObjects.splice(index, 1);
39968             }
39969         }
39970     };
39971     return TagScene;
39972 }());
39973 exports.TagScene = TagScene;
39974 exports.default = TagScene;
39975
39976 },{"three":242}],368:[function(require,module,exports){
39977 "use strict";
39978 Object.defineProperty(exports, "__esModule", { value: true });
39979 var rxjs_1 = require("rxjs");
39980 var Component_1 = require("../../Component");
39981 var ExtremePointTag_1 = require("./tag/ExtremePointTag");
39982 var ExtremePointRenderTag_1 = require("./tag/ExtremePointRenderTag");
39983 var TagSet = /** @class */ (function () {
39984     function TagSet() {
39985         this._active = false;
39986         this._hash = {};
39987         this._hashDeactivated = {};
39988         this._notifyChanged$ = new rxjs_1.Subject();
39989     }
39990     Object.defineProperty(TagSet.prototype, "active", {
39991         get: function () {
39992             return this._active;
39993         },
39994         enumerable: true,
39995         configurable: true
39996     });
39997     Object.defineProperty(TagSet.prototype, "changed$", {
39998         get: function () {
39999             return this._notifyChanged$;
40000         },
40001         enumerable: true,
40002         configurable: true
40003     });
40004     TagSet.prototype.activate = function (transform) {
40005         if (this._active) {
40006             return;
40007         }
40008         for (var id in this._hashDeactivated) {
40009             if (!this._hashDeactivated.hasOwnProperty(id)) {
40010                 continue;
40011             }
40012             var tag = this._hashDeactivated[id];
40013             this._add(tag, transform);
40014         }
40015         this._hashDeactivated = {};
40016         this._active = true;
40017         this._notifyChanged$.next(this);
40018     };
40019     TagSet.prototype.deactivate = function () {
40020         if (!this._active) {
40021             return;
40022         }
40023         for (var id in this._hash) {
40024             if (!this._hash.hasOwnProperty(id)) {
40025                 continue;
40026             }
40027             this._hashDeactivated[id] = this._hash[id].tag;
40028         }
40029         this._hash = {};
40030         this._active = false;
40031     };
40032     TagSet.prototype.add = function (tags, transform) {
40033         this._assertActivationState(true);
40034         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
40035             var tag = tags_1[_i];
40036             this._add(tag, transform);
40037         }
40038         this._notifyChanged$.next(this);
40039     };
40040     TagSet.prototype.addDeactivated = function (tags) {
40041         this._assertActivationState(false);
40042         for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
40043             var tag = tags_2[_i];
40044             if (!(tag instanceof Component_1.OutlineTag ||
40045                 tag instanceof Component_1.SpotTag ||
40046                 tag instanceof ExtremePointTag_1.default)) {
40047                 throw new Error("Tag type not supported");
40048             }
40049             this._hashDeactivated[tag.id] = tag;
40050         }
40051     };
40052     TagSet.prototype.get = function (id) {
40053         return this.has(id) ? this._hash[id] : undefined;
40054     };
40055     TagSet.prototype.getAll = function () {
40056         var hash = this._hash;
40057         return Object.keys(hash)
40058             .map(function (id) {
40059             return hash[id];
40060         });
40061     };
40062     TagSet.prototype.getAllDeactivated = function () {
40063         var hashDeactivated = this._hashDeactivated;
40064         return Object.keys(hashDeactivated)
40065             .map(function (id) {
40066             return hashDeactivated[id];
40067         });
40068     };
40069     TagSet.prototype.getDeactivated = function (id) {
40070         return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined;
40071     };
40072     TagSet.prototype.has = function (id) {
40073         return id in this._hash;
40074     };
40075     TagSet.prototype.hasDeactivated = function (id) {
40076         return id in this._hashDeactivated;
40077     };
40078     TagSet.prototype.remove = function (ids) {
40079         this._assertActivationState(true);
40080         var hash = this._hash;
40081         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
40082             var id = ids_1[_i];
40083             if (!(id in hash)) {
40084                 continue;
40085             }
40086             delete hash[id];
40087         }
40088         this._notifyChanged$.next(this);
40089     };
40090     TagSet.prototype.removeAll = function () {
40091         this._assertActivationState(true);
40092         this._hash = {};
40093         this._notifyChanged$.next(this);
40094     };
40095     TagSet.prototype.removeAllDeactivated = function () {
40096         this._assertActivationState(false);
40097         this._hashDeactivated = {};
40098     };
40099     TagSet.prototype.removeDeactivated = function (ids) {
40100         this._assertActivationState(false);
40101         var hashDeactivated = this._hashDeactivated;
40102         for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) {
40103             var id = ids_2[_i];
40104             if (!(id in hashDeactivated)) {
40105                 continue;
40106             }
40107             delete hashDeactivated[id];
40108         }
40109     };
40110     TagSet.prototype._add = function (tag, transform) {
40111         if (tag instanceof Component_1.OutlineTag) {
40112             this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform);
40113         }
40114         else if (tag instanceof Component_1.SpotTag) {
40115             this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform);
40116         }
40117         else if (tag instanceof ExtremePointTag_1.default) {
40118             this._hash[tag.id] = new ExtremePointRenderTag_1.default(tag, transform);
40119         }
40120         else {
40121             throw new Error("Tag type not supported");
40122         }
40123     };
40124     TagSet.prototype._assertActivationState = function (should) {
40125         if (should !== this._active) {
40126             throw new Error("Tag set not in correct state for operation.");
40127         }
40128     };
40129     return TagSet;
40130 }());
40131 exports.TagSet = TagSet;
40132 exports.default = TagSet;
40133
40134 },{"../../Component":291,"./tag/ExtremePointRenderTag":387,"./tag/ExtremePointTag":388,"rxjs":43}],369:[function(require,module,exports){
40135 "use strict";
40136 var __extends = (this && this.__extends) || (function () {
40137     var extendStatics = function (d, b) {
40138         extendStatics = Object.setPrototypeOf ||
40139             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
40140             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
40141         return extendStatics(d, b);
40142     }
40143     return function (d, b) {
40144         extendStatics(d, b);
40145         function __() { this.constructor = d; }
40146         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40147     };
40148 })();
40149 Object.defineProperty(exports, "__esModule", { value: true });
40150 var Error_1 = require("../../../Error");
40151 var GeometryTagError = /** @class */ (function (_super) {
40152     __extends(GeometryTagError, _super);
40153     function GeometryTagError(message) {
40154         var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
40155         Object.setPrototypeOf(_this, GeometryTagError.prototype);
40156         _this.name = "GeometryTagError";
40157         return _this;
40158     }
40159     return GeometryTagError;
40160 }(Error_1.MapillaryError));
40161 exports.GeometryTagError = GeometryTagError;
40162 exports.default = Error_1.MapillaryError;
40163
40164 },{"../../../Error":293}],370:[function(require,module,exports){
40165 "use strict";
40166 Object.defineProperty(exports, "__esModule", { value: true });
40167 var rxjs_1 = require("rxjs");
40168 /**
40169  * @class Geometry
40170  * @abstract
40171  * @classdesc Represents a geometry.
40172  */
40173 var Geometry = /** @class */ (function () {
40174     /**
40175      * Create a geometry.
40176      *
40177      * @constructor
40178      * @ignore
40179      */
40180     function Geometry() {
40181         this._notifyChanged$ = new rxjs_1.Subject();
40182     }
40183     Object.defineProperty(Geometry.prototype, "changed$", {
40184         /**
40185          * Get changed observable.
40186          *
40187          * @description Emits the geometry itself every time the geometry
40188          * has changed.
40189          *
40190          * @returns {Observable<Geometry>} Observable emitting the geometry instance.
40191          * @ignore
40192          */
40193         get: function () {
40194             return this._notifyChanged$;
40195         },
40196         enumerable: true,
40197         configurable: true
40198     });
40199     return Geometry;
40200 }());
40201 exports.Geometry = Geometry;
40202 exports.default = Geometry;
40203
40204 },{"rxjs":43}],371:[function(require,module,exports){
40205 "use strict";
40206 var __extends = (this && this.__extends) || (function () {
40207     var extendStatics = function (d, b) {
40208         extendStatics = Object.setPrototypeOf ||
40209             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
40210             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
40211         return extendStatics(d, b);
40212     }
40213     return function (d, b) {
40214         extendStatics(d, b);
40215         function __() { this.constructor = d; }
40216         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40217     };
40218 })();
40219 Object.defineProperty(exports, "__esModule", { value: true });
40220 var Component_1 = require("../../../Component");
40221 /**
40222  * @class PointGeometry
40223  *
40224  * @classdesc Represents a point geometry in the 2D basic image coordinate system.
40225  *
40226  * @example
40227  * ```
40228  * var basicPoint = [0.5, 0.7];
40229  * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint);
40230  * ```
40231  */
40232 var PointGeometry = /** @class */ (function (_super) {
40233     __extends(PointGeometry, _super);
40234     /**
40235      * Create a point geometry.
40236      *
40237      * @constructor
40238      * @param {Array<number>} point - An array representing the basic coordinates of
40239      * the point.
40240      *
40241      * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
40242      */
40243     function PointGeometry(point) {
40244         var _this = _super.call(this) || this;
40245         var x = point[0];
40246         var y = point[1];
40247         if (x < 0 || x > 1 || y < 0 || y > 1) {
40248             throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
40249         }
40250         _this._point = point.slice();
40251         return _this;
40252     }
40253     Object.defineProperty(PointGeometry.prototype, "point", {
40254         /**
40255          * Get point property.
40256          * @returns {Array<number>} Array representing the basic coordinates of the point.
40257          */
40258         get: function () {
40259             return this._point;
40260         },
40261         enumerable: true,
40262         configurable: true
40263     });
40264     /**
40265      * Get the 2D basic coordinates for the centroid of the point, i.e. the 2D
40266      * basic coordinates of the point itself.
40267      *
40268      * @returns {Array<number>} 2D basic coordinates representing the centroid.
40269      * @ignore
40270      */
40271     PointGeometry.prototype.getCentroid2d = function () {
40272         return this._point.slice();
40273     };
40274     /**
40275      * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
40276      * world coordinates of the point itself.
40277      *
40278      * @param {Transform} transform - The transform of the node related to the point.
40279      * @returns {Array<number>} 3D world coordinates representing the centroid.
40280      * @ignore
40281      */
40282     PointGeometry.prototype.getCentroid3d = function (transform) {
40283         return transform.unprojectBasic(this._point, 200);
40284     };
40285     /**
40286      * Set the centroid of the point, i.e. the point coordinates.
40287      *
40288      * @param {Array<number>} value - The new value of the centroid.
40289      * @param {Transform} transform - The transform of the node related to the point.
40290      * @ignore
40291      */
40292     PointGeometry.prototype.setCentroid2d = function (value, transform) {
40293         var changed = [
40294             Math.max(0, Math.min(1, value[0])),
40295             Math.max(0, Math.min(1, value[1])),
40296         ];
40297         this._point[0] = changed[0];
40298         this._point[1] = changed[1];
40299         this._notifyChanged$.next(this);
40300     };
40301     return PointGeometry;
40302 }(Component_1.Geometry));
40303 exports.PointGeometry = PointGeometry;
40304 exports.default = PointGeometry;
40305
40306 },{"../../../Component":291}],372:[function(require,module,exports){
40307 "use strict";
40308 var __extends = (this && this.__extends) || (function () {
40309     var extendStatics = function (d, b) {
40310         extendStatics = Object.setPrototypeOf ||
40311             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
40312             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
40313         return extendStatics(d, b);
40314     }
40315     return function (d, b) {
40316         extendStatics(d, b);
40317         function __() { this.constructor = d; }
40318         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40319     };
40320 })();
40321 Object.defineProperty(exports, "__esModule", { value: true });
40322 var Component_1 = require("../../../Component");
40323 /**
40324  * @class PointsGeometry
40325  *
40326  * @classdesc Represents a point set in the 2D basic image coordinate system.
40327  *
40328  * @example
40329  * ```
40330  * var points = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5]];
40331  * var pointsGeometry = new Mapillary.TagComponent.PointsGeometry(points);
40332  * ```
40333  */
40334 var PointsGeometry = /** @class */ (function (_super) {
40335     __extends(PointsGeometry, _super);
40336     /**
40337      * Create a points geometry.
40338      *
40339      * @constructor
40340      * @param {Array<Array<number>>} points - Array of 2D points on the basic coordinate
40341      * system. The number of points must be greater than or equal to two.
40342      *
40343      * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
40344      */
40345     function PointsGeometry(points) {
40346         var _this = _super.call(this) || this;
40347         var pointsLength = points.length;
40348         if (pointsLength < 2) {
40349             throw new Component_1.GeometryTagError("A points geometry must have two or more positions.");
40350         }
40351         _this._points = [];
40352         for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
40353             var point = points_1[_i];
40354             if (point[0] < 0 || point[0] > 1 ||
40355                 point[1] < 0 || point[1] > 1) {
40356                 throw new Component_1.GeometryTagError("Basic coordinates of points must be on the interval [0, 1].");
40357             }
40358             _this._points.push(point.slice());
40359         }
40360         return _this;
40361     }
40362     Object.defineProperty(PointsGeometry.prototype, "points", {
40363         /**
40364          * Get points property.
40365          * @returns {Array<Array<number>>} Array of 2d points.
40366          */
40367         get: function () {
40368             return this._points;
40369         },
40370         enumerable: true,
40371         configurable: true
40372     });
40373     /**
40374      * Add a point to the point set.
40375      *
40376      * @param {Array<number>} point - Point to add.
40377      * @ignore
40378      */
40379     PointsGeometry.prototype.addPoint2d = function (point) {
40380         var clamped = [
40381             Math.max(0, Math.min(1, point[0])),
40382             Math.max(0, Math.min(1, point[1])),
40383         ];
40384         this._points.push(clamped);
40385         this._notifyChanged$.next(this);
40386     };
40387     /**
40388      * Get the coordinates of a point from the point set representation of the geometry.
40389      *
40390      * @param {number} index - Point index.
40391      * @returns {Array<number>} Array representing the 2D basic coordinates of the point.
40392      * @ignore
40393      */
40394     PointsGeometry.prototype.getPoint2d = function (index) {
40395         return this._points[index].slice();
40396     };
40397     /**
40398      * Remove a point from the point set.
40399      *
40400      * @param {number} index - The index of the point to remove.
40401      * @ignore
40402      */
40403     PointsGeometry.prototype.removePoint2d = function (index) {
40404         if (index < 0 ||
40405             index >= this._points.length ||
40406             this._points.length < 3) {
40407             throw new Component_1.GeometryTagError("Index for removed point must be valid.");
40408         }
40409         this._points.splice(index, 1);
40410         this._notifyChanged$.next(this);
40411     };
40412     /** @ignore */
40413     PointsGeometry.prototype.setVertex2d = function (index, value, transform) {
40414         this.setPoint2d(index, value, transform);
40415     };
40416     /** @ignore */
40417     PointsGeometry.prototype.setPoint2d = function (index, value, transform) {
40418         var changed = [
40419             Math.max(0, Math.min(1, value[0])),
40420             Math.max(0, Math.min(1, value[1])),
40421         ];
40422         this._points[index] = changed;
40423         this._notifyChanged$.next(this);
40424     };
40425     /** @ignore */
40426     PointsGeometry.prototype.getPoints3d = function (transform) {
40427         return this._getPoints3d(this._points, transform);
40428     };
40429     /** @ignore */
40430     PointsGeometry.prototype.getPoint3d = function (index, transform) {
40431         return transform.unprojectBasic(this._points[index], 200);
40432     };
40433     /** @ignore */
40434     PointsGeometry.prototype.getPoints2d = function () {
40435         return this._points.slice();
40436     };
40437     /** @ignore */
40438     PointsGeometry.prototype.getCentroid2d = function (transform) {
40439         if (!transform) {
40440             throw new Component_1.GeometryTagError("Get centroid must be called with a transform for points geometries.");
40441         }
40442         var _a = this.getRect2d(transform), minX = _a[0], minY = _a[1], maxX = _a[2], maxY = _a[3];
40443         var centroidX = minX < maxX ?
40444             (minX + maxX) / 2 :
40445             ((minX + maxX + 1) / 2) % 1;
40446         var centroidY = (minY + maxY) / 2;
40447         return [centroidX, centroidY];
40448     };
40449     /** @ignore */
40450     PointsGeometry.prototype.getCentroid3d = function (transform) {
40451         var centroid2d = this.getCentroid2d();
40452         return transform.unprojectBasic(centroid2d, 200);
40453     };
40454     /** @ignore */
40455     PointsGeometry.prototype.getRect2d = function (transform) {
40456         var minX = 1;
40457         var maxX = 0;
40458         var minY = 1;
40459         var maxY = 0;
40460         var points = this._points;
40461         for (var _i = 0, points_2 = points; _i < points_2.length; _i++) {
40462             var point = points_2[_i];
40463             if (point[0] < minX) {
40464                 minX = point[0];
40465             }
40466             if (point[0] > maxX) {
40467                 maxX = point[0];
40468             }
40469             if (point[1] < minY) {
40470                 minY = point[1];
40471             }
40472             if (point[1] > maxY) {
40473                 maxY = point[1];
40474             }
40475         }
40476         if (transform.fullPano) {
40477             var indices = [];
40478             for (var i = 0; i < points.length; i++) {
40479                 indices[i] = i;
40480             }
40481             indices.sort(function (a, b) {
40482                 return points[a][0] < points[b][0] ?
40483                     -1 :
40484                     points[a][0] > points[b][0] ?
40485                         1 :
40486                         a < b ? -1 : 1;
40487             });
40488             var maxDistanceX = points[indices[0]][0] + 1 - points[indices[indices.length - 1]][0];
40489             var leftMostIndex = 0;
40490             for (var i = 0; i < indices.length - 1; i++) {
40491                 var index1 = indices[i];
40492                 var index2 = indices[i + 1];
40493                 var distanceX = points[index2][0] - points[index1][0];
40494                 if (distanceX > maxDistanceX) {
40495                     maxDistanceX = distanceX;
40496                     leftMostIndex = i + 1;
40497                 }
40498             }
40499             if (leftMostIndex > 0) {
40500                 minX = points[indices[leftMostIndex]][0];
40501                 maxX = points[indices[leftMostIndex - 1]][0];
40502             }
40503         }
40504         return [minX, minY, maxX, maxY];
40505     };
40506     /** @ignore */
40507     PointsGeometry.prototype.setCentroid2d = function (value, transform) {
40508         throw new Error("Not implemented");
40509     };
40510     PointsGeometry.prototype._getPoints3d = function (points2d, transform) {
40511         return points2d
40512             .map(function (point) {
40513             return transform.unprojectBasic(point, 200);
40514         });
40515     };
40516     return PointsGeometry;
40517 }(Component_1.Geometry));
40518 exports.PointsGeometry = PointsGeometry;
40519 exports.default = PointsGeometry;
40520
40521 },{"../../../Component":291}],373:[function(require,module,exports){
40522 "use strict";
40523 var __extends = (this && this.__extends) || (function () {
40524     var extendStatics = function (d, b) {
40525         extendStatics = Object.setPrototypeOf ||
40526             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
40527             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
40528         return extendStatics(d, b);
40529     }
40530     return function (d, b) {
40531         extendStatics(d, b);
40532         function __() { this.constructor = d; }
40533         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40534     };
40535 })();
40536 Object.defineProperty(exports, "__esModule", { value: true });
40537 var Component_1 = require("../../../Component");
40538 /**
40539  * @class PolygonGeometry
40540  *
40541  * @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
40542  * All polygons and holes provided to the constructor needs to be closed.
40543  *
40544  * @example
40545  * ```
40546  * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
40547  * var polygonGeometry = new Mapillary.TagComponent.PolygonGeometry(basicPolygon);
40548  * ```
40549  */
40550 var PolygonGeometry = /** @class */ (function (_super) {
40551     __extends(PolygonGeometry, _super);
40552     /**
40553      * Create a polygon geometry.
40554      *
40555      * @constructor
40556      * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
40557      * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
40558      * Each array of holes vertices must be closed.
40559      *
40560      * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
40561      */
40562     function PolygonGeometry(polygon, holes) {
40563         var _this = _super.call(this) || this;
40564         var polygonLength = polygon.length;
40565         if (polygonLength < 3) {
40566             throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
40567         }
40568         if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
40569             polygon[0][1] !== polygon[polygonLength - 1][1]) {
40570             throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
40571         }
40572         _this._polygon = [];
40573         for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
40574             var vertex = polygon_1[_i];
40575             if (vertex[0] < 0 || vertex[0] > 1 ||
40576                 vertex[1] < 0 || vertex[1] > 1) {
40577                 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
40578             }
40579             _this._polygon.push(vertex.slice());
40580         }
40581         _this._holes = [];
40582         if (holes == null) {
40583             return _this;
40584         }
40585         for (var i = 0; i < holes.length; i++) {
40586             var hole = holes[i];
40587             var holeLength = hole.length;
40588             if (holeLength < 3) {
40589                 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
40590             }
40591             if (hole[0][0] !== hole[holeLength - 1][0] ||
40592                 hole[0][1] !== hole[holeLength - 1][1]) {
40593                 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
40594             }
40595             _this._holes.push([]);
40596             for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
40597                 var vertex = hole_1[_a];
40598                 if (vertex[0] < 0 || vertex[0] > 1 ||
40599                     vertex[1] < 0 || vertex[1] > 1) {
40600                     throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
40601                 }
40602                 _this._holes[i].push(vertex.slice());
40603             }
40604         }
40605         return _this;
40606     }
40607     Object.defineProperty(PolygonGeometry.prototype, "polygon", {
40608         /**
40609          * Get polygon property.
40610          * @returns {Array<Array<number>>} Closed 2d polygon.
40611          */
40612         get: function () {
40613             return this._polygon;
40614         },
40615         enumerable: true,
40616         configurable: true
40617     });
40618     Object.defineProperty(PolygonGeometry.prototype, "holes", {
40619         /**
40620          * Get holes property.
40621          * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
40622          */
40623         get: function () {
40624             return this._holes;
40625         },
40626         enumerable: true,
40627         configurable: true
40628     });
40629     /**
40630      * Add a vertex to the polygon by appending it after the last vertex.
40631      *
40632      * @param {Array<number>} vertex - Vertex to add.
40633      * @ignore
40634      */
40635     PolygonGeometry.prototype.addVertex2d = function (vertex) {
40636         var clamped = [
40637             Math.max(0, Math.min(1, vertex[0])),
40638             Math.max(0, Math.min(1, vertex[1])),
40639         ];
40640         this._polygon.splice(this._polygon.length - 1, 0, clamped);
40641         this._notifyChanged$.next(this);
40642     };
40643     /**
40644      * Get the coordinates of a vertex from the polygon representation of the geometry.
40645      *
40646      * @param {number} index - Vertex index.
40647      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
40648      * @ignore
40649      */
40650     PolygonGeometry.prototype.getVertex2d = function (index) {
40651         return this._polygon[index].slice();
40652     };
40653     /**
40654      * Remove a vertex from the polygon.
40655      *
40656      * @param {number} index - The index of the vertex to remove.
40657      * @ignore
40658      */
40659     PolygonGeometry.prototype.removeVertex2d = function (index) {
40660         if (index < 0 ||
40661             index >= this._polygon.length ||
40662             this._polygon.length < 4) {
40663             throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
40664         }
40665         if (index > 0 && index < this._polygon.length - 1) {
40666             this._polygon.splice(index, 1);
40667         }
40668         else {
40669             this._polygon.splice(0, 1);
40670             this._polygon.pop();
40671             var closing = this._polygon[0].slice();
40672             this._polygon.push(closing);
40673         }
40674         this._notifyChanged$.next(this);
40675     };
40676     /** @ignore */
40677     PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
40678         var changed = [
40679             Math.max(0, Math.min(1, value[0])),
40680             Math.max(0, Math.min(1, value[1])),
40681         ];
40682         if (index === 0 || index === this._polygon.length - 1) {
40683             this._polygon[0] = changed.slice();
40684             this._polygon[this._polygon.length - 1] = changed.slice();
40685         }
40686         else {
40687             this._polygon[index] = changed.slice();
40688         }
40689         this._notifyChanged$.next(this);
40690     };
40691     /** @ignore */
40692     PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
40693         var xs = this._polygon.map(function (point) { return point[0]; });
40694         var ys = this._polygon.map(function (point) { return point[1]; });
40695         var minX = Math.min.apply(Math, xs);
40696         var maxX = Math.max.apply(Math, xs);
40697         var minY = Math.min.apply(Math, ys);
40698         var maxY = Math.max.apply(Math, ys);
40699         var centroid = this.getCentroid2d();
40700         var minTranslationX = -minX;
40701         var maxTranslationX = 1 - maxX;
40702         var minTranslationY = -minY;
40703         var maxTranslationY = 1 - maxY;
40704         var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
40705         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
40706         for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
40707             var point = _a[_i];
40708             point[0] += translationX;
40709             point[1] += translationY;
40710         }
40711         this._notifyChanged$.next(this);
40712     };
40713     /** @ignore */
40714     PolygonGeometry.prototype.getPoints3d = function (transform) {
40715         return this._getPoints3d(this._subsample(this._polygon), transform);
40716     };
40717     /** @ignore */
40718     PolygonGeometry.prototype.getVertex3d = function (index, transform) {
40719         return transform.unprojectBasic(this._polygon[index], 200);
40720     };
40721     /** @ignore */
40722     PolygonGeometry.prototype.getVertices2d = function () {
40723         return this._polygon.slice();
40724     };
40725     /** @ignore */
40726     PolygonGeometry.prototype.getVertices3d = function (transform) {
40727         return this._getPoints3d(this._polygon, transform);
40728     };
40729     /**
40730      * Get a polygon representation of the 3D coordinates for the vertices of each hole
40731      * of the geometry. Line segments between vertices will possibly be subsampled
40732      * resulting in a larger number of points than the total number of vertices.
40733      *
40734      * @param {Transform} transform - The transform of the node related to the geometry.
40735      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
40736      * representing the vertices of each hole of the geometry.
40737      * @ignore
40738      */
40739     PolygonGeometry.prototype.getHolePoints3d = function (transform) {
40740         var _this = this;
40741         return this._holes
40742             .map(function (hole2d) {
40743             return _this._getPoints3d(_this._subsample(hole2d), transform);
40744         });
40745     };
40746     /**
40747      * Get a polygon representation of the 3D coordinates for the vertices of each hole
40748      * of the geometry.
40749      *
40750      * @param {Transform} transform - The transform of the node related to the geometry.
40751      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
40752      * representing the vertices of each hole of the geometry.
40753      * @ignore
40754      */
40755     PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
40756         var _this = this;
40757         return this._holes
40758             .map(function (hole2d) {
40759             return _this._getPoints3d(hole2d, transform);
40760         });
40761     };
40762     /** @ignore */
40763     PolygonGeometry.prototype.getCentroid2d = function () {
40764         var polygon = this._polygon;
40765         var area = 0;
40766         var centroidX = 0;
40767         var centroidY = 0;
40768         for (var i = 0; i < polygon.length - 1; i++) {
40769             var xi = polygon[i][0];
40770             var yi = polygon[i][1];
40771             var xi1 = polygon[i + 1][0];
40772             var yi1 = polygon[i + 1][1];
40773             var a = xi * yi1 - xi1 * yi;
40774             area += a;
40775             centroidX += (xi + xi1) * a;
40776             centroidY += (yi + yi1) * a;
40777         }
40778         area /= 2;
40779         centroidX /= 6 * area;
40780         centroidY /= 6 * area;
40781         return [centroidX, centroidY];
40782     };
40783     /** @ignore */
40784     PolygonGeometry.prototype.getCentroid3d = function (transform) {
40785         var centroid2d = this.getCentroid2d();
40786         return transform.unprojectBasic(centroid2d, 200);
40787     };
40788     /** @ignore */
40789     PolygonGeometry.prototype.get3dDomainTriangles3d = function (transform) {
40790         var _this = this;
40791         return this._triangulate(this._project(this._polygon, transform), this.getVertices3d(transform), this._holes
40792             .map(function (hole2d) {
40793             return _this._project(hole2d, transform);
40794         }), this.getHoleVertices3d(transform));
40795     };
40796     /** @ignore */
40797     PolygonGeometry.prototype.getTriangles3d = function (transform) {
40798         var _this = this;
40799         if (transform.fullPano) {
40800             return this._triangulatePano(this._polygon.slice(), this.holes.slice(), transform);
40801         }
40802         var points2d = this._project(this._subsample(this._polygon), transform);
40803         var points3d = this.getPoints3d(transform);
40804         var holes2d = this._holes
40805             .map(function (hole) {
40806             return _this._project(_this._subsample(hole), transform);
40807         });
40808         var holes3d = this.getHolePoints3d(transform);
40809         return this._triangulate(points2d, points3d, holes2d, holes3d);
40810     };
40811     /** @ignore */
40812     PolygonGeometry.prototype.getPoleOfInaccessibility2d = function () {
40813         return this._getPoleOfInaccessibility2d(this._polygon.slice());
40814     };
40815     /** @ignore */
40816     PolygonGeometry.prototype.getPoleOfInaccessibility3d = function (transform) {
40817         var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice());
40818         return transform.unprojectBasic(pole2d, 200);
40819     };
40820     PolygonGeometry.prototype._getPoints3d = function (points2d, transform) {
40821         return points2d
40822             .map(function (point) {
40823             return transform.unprojectBasic(point, 200);
40824         });
40825     };
40826     return PolygonGeometry;
40827 }(Component_1.VertexGeometry));
40828 exports.PolygonGeometry = PolygonGeometry;
40829 exports.default = PolygonGeometry;
40830
40831 },{"../../../Component":291}],374:[function(require,module,exports){
40832 "use strict";
40833 var __extends = (this && this.__extends) || (function () {
40834     var extendStatics = function (d, b) {
40835         extendStatics = Object.setPrototypeOf ||
40836             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
40837             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
40838         return extendStatics(d, b);
40839     }
40840     return function (d, b) {
40841         extendStatics(d, b);
40842         function __() { this.constructor = d; }
40843         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40844     };
40845 })();
40846 Object.defineProperty(exports, "__esModule", { value: true });
40847 var Component_1 = require("../../../Component");
40848 /**
40849  * @class RectGeometry
40850  *
40851  * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system.
40852  *
40853  * @example
40854  * ```
40855  * var basicRect = [0.5, 0.3, 0.7, 0.4];
40856  * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect);
40857  * ```
40858  */
40859 var RectGeometry = /** @class */ (function (_super) {
40860     __extends(RectGeometry, _super);
40861     /**
40862      * Create a rectangle geometry.
40863      *
40864      * @constructor
40865      * @param {Array<number>} rect - An array representing the top-left and bottom-right
40866      * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
40867      *
40868      * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
40869      */
40870     function RectGeometry(rect) {
40871         var _this = _super.call(this) || this;
40872         if (rect[1] > rect[3]) {
40873             throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
40874         }
40875         for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
40876             var coord = rect_1[_i];
40877             if (coord < 0 || coord > 1) {
40878                 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
40879             }
40880         }
40881         _this._anchorIndex = undefined;
40882         _this._rect = rect.slice(0, 4);
40883         _this._inverted = _this._rect[0] > _this._rect[2];
40884         return _this;
40885     }
40886     Object.defineProperty(RectGeometry.prototype, "anchorIndex", {
40887         /**
40888          * Get anchor index property.
40889          *
40890          * @returns {number} Index representing the current anchor property if
40891          * achoring indexing has been initialized. If anchor indexing has not been
40892          * initialized or has been terminated undefined will be returned.
40893          * @ignore
40894          */
40895         get: function () {
40896             return this._anchorIndex;
40897         },
40898         enumerable: true,
40899         configurable: true
40900     });
40901     Object.defineProperty(RectGeometry.prototype, "inverted", {
40902         /**
40903          * Get inverted property.
40904          *
40905          * @returns {boolean} Boolean determining whether the rect geometry is
40906          * inverted. For panoramas the rect geometrye may be inverted.
40907          * @ignore
40908          */
40909         get: function () {
40910             return this._inverted;
40911         },
40912         enumerable: true,
40913         configurable: true
40914     });
40915     Object.defineProperty(RectGeometry.prototype, "rect", {
40916         /**
40917          * Get rect property.
40918          *
40919          * @returns {Array<number>} Array representing the top-left and bottom-right
40920          * corners of the rectangle in basic coordinates.
40921          */
40922         get: function () {
40923             return this._rect;
40924         },
40925         enumerable: true,
40926         configurable: true
40927     });
40928     /**
40929      * Initialize anchor indexing to enable setting opposite vertex.
40930      *
40931      * @param {number} [index] - The index of the vertex to use as anchor.
40932      *
40933      * @throws {Error} If anchor indexing has already been initialized.
40934      * @throws {Error} If index is not valid (0 to 3).
40935      * @ignore
40936      */
40937     RectGeometry.prototype.initializeAnchorIndexing = function (index) {
40938         if (this._anchorIndex !== undefined) {
40939             throw new Error("Anchor indexing is already initialized.");
40940         }
40941         if (index < 0 || index > 3) {
40942             throw new Error("Invalid anchor index: " + index + ".");
40943         }
40944         this._anchorIndex = index === undefined ? 0 : index;
40945     };
40946     /**
40947      * Terminate anchor indexing to disable setting pposite vertex.
40948      * @ignore
40949      */
40950     RectGeometry.prototype.terminateAnchorIndexing = function () {
40951         this._anchorIndex = undefined;
40952     };
40953     /**
40954      * Set the value of the vertex opposite to the anchor in the polygon
40955      * representation of the rectangle.
40956      *
40957      * @description Setting the opposite vertex may change the anchor index.
40958      *
40959      * @param {Array<number>} opposite - The new value of the vertex opposite to the anchor.
40960      * @param {Transform} transform - The transform of the node related to the rectangle.
40961      *
40962      * @throws {Error} When anchor indexing has not been initialized.
40963      * @ignore
40964      */
40965     RectGeometry.prototype.setOppositeVertex2d = function (opposite, transform) {
40966         if (this._anchorIndex === undefined) {
40967             throw new Error("Anchor indexing needs to be initialized.");
40968         }
40969         var changed = [
40970             Math.max(0, Math.min(1, opposite[0])),
40971             Math.max(0, Math.min(1, opposite[1])),
40972         ];
40973         var original = this._rect.slice();
40974         var anchor = this._anchorIndex === 0 ? [original[0], original[3]] :
40975             this._anchorIndex === 1 ? [original[0], original[1]] :
40976                 this._anchorIndex === 2 ? [original[2], original[1]] :
40977                     [original[2], original[3]];
40978         if (transform.fullPano) {
40979             var deltaX = this._anchorIndex < 2 ?
40980                 changed[0] - original[2] :
40981                 changed[0] - original[0];
40982             if (!this._inverted && this._anchorIndex < 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
40983                 // right side passes boundary rightward
40984                 this._inverted = true;
40985                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
40986             }
40987             else if (!this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
40988                 // left side passes right side and boundary rightward
40989                 this._inverted = true;
40990                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
40991             }
40992             else if (this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[0] > 0.75 && deltaX < -0.5) {
40993                 this._inverted = false;
40994                 if (anchor[0] > changed[0]) {
40995                     // left side passes boundary rightward
40996                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
40997                 }
40998                 else {
40999                     // left side passes right side and boundary rightward
41000                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
41001                 }
41002             }
41003             else if (!this._inverted && this._anchorIndex >= 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
41004                 // left side passes boundary leftward
41005                 this._inverted = true;
41006                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
41007             }
41008             else if (!this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
41009                 // right side passes left side and boundary leftward
41010                 this._inverted = true;
41011                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
41012             }
41013             else if (this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[2] < 0.25 && deltaX > 0.5) {
41014                 this._inverted = false;
41015                 if (anchor[0] > changed[0]) {
41016                     // right side passes boundary leftward
41017                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
41018                 }
41019                 else {
41020                     // right side passes left side and boundary leftward
41021                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
41022                 }
41023             }
41024             else if (this._inverted && this._anchorIndex < 2 && changed[0] > original[0]) {
41025                 // inverted and right side passes left side completing a loop
41026                 this._inverted = false;
41027                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
41028             }
41029             else if (this._inverted && this._anchorIndex >= 2 && changed[0] < original[2]) {
41030                 // inverted and left side passes right side completing a loop
41031                 this._inverted = false;
41032                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
41033             }
41034             else if (this._inverted) {
41035                 // if still inverted only top and bottom can switch
41036                 if (this._anchorIndex < 2) {
41037                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
41038                 }
41039                 else {
41040                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
41041                 }
41042             }
41043             else {
41044                 // if still not inverted treat as non full pano
41045                 if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
41046                     this._anchorIndex = 0;
41047                 }
41048                 else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
41049                     this._anchorIndex = 1;
41050                 }
41051                 else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
41052                     this._anchorIndex = 2;
41053                 }
41054                 else {
41055                     this._anchorIndex = 3;
41056                 }
41057             }
41058             var rect = [];
41059             if (this._anchorIndex === 0) {
41060                 rect[0] = anchor[0];
41061                 rect[1] = changed[1];
41062                 rect[2] = changed[0];
41063                 rect[3] = anchor[1];
41064             }
41065             else if (this._anchorIndex === 1) {
41066                 rect[0] = anchor[0];
41067                 rect[1] = anchor[1];
41068                 rect[2] = changed[0];
41069                 rect[3] = changed[1];
41070             }
41071             else if (this._anchorIndex === 2) {
41072                 rect[0] = changed[0];
41073                 rect[1] = anchor[1];
41074                 rect[2] = anchor[0];
41075                 rect[3] = changed[1];
41076             }
41077             else {
41078                 rect[0] = changed[0];
41079                 rect[1] = changed[1];
41080                 rect[2] = anchor[0];
41081                 rect[3] = anchor[1];
41082             }
41083             if (!this._inverted && rect[0] > rect[2] ||
41084                 this._inverted && rect[0] < rect[2]) {
41085                 rect[0] = original[0];
41086                 rect[2] = original[2];
41087             }
41088             if (rect[1] > rect[3]) {
41089                 rect[1] = original[1];
41090                 rect[3] = original[3];
41091             }
41092             this._rect[0] = rect[0];
41093             this._rect[1] = rect[1];
41094             this._rect[2] = rect[2];
41095             this._rect[3] = rect[3];
41096         }
41097         else {
41098             if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
41099                 this._anchorIndex = 0;
41100             }
41101             else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
41102                 this._anchorIndex = 1;
41103             }
41104             else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
41105                 this._anchorIndex = 2;
41106             }
41107             else {
41108                 this._anchorIndex = 3;
41109             }
41110             var rect = [];
41111             if (this._anchorIndex === 0) {
41112                 rect[0] = anchor[0];
41113                 rect[1] = changed[1];
41114                 rect[2] = changed[0];
41115                 rect[3] = anchor[1];
41116             }
41117             else if (this._anchorIndex === 1) {
41118                 rect[0] = anchor[0];
41119                 rect[1] = anchor[1];
41120                 rect[2] = changed[0];
41121                 rect[3] = changed[1];
41122             }
41123             else if (this._anchorIndex === 2) {
41124                 rect[0] = changed[0];
41125                 rect[1] = anchor[1];
41126                 rect[2] = anchor[0];
41127                 rect[3] = changed[1];
41128             }
41129             else {
41130                 rect[0] = changed[0];
41131                 rect[1] = changed[1];
41132                 rect[2] = anchor[0];
41133                 rect[3] = anchor[1];
41134             }
41135             if (rect[0] > rect[2]) {
41136                 rect[0] = original[0];
41137                 rect[2] = original[2];
41138             }
41139             if (rect[1] > rect[3]) {
41140                 rect[1] = original[1];
41141                 rect[3] = original[3];
41142             }
41143             this._rect[0] = rect[0];
41144             this._rect[1] = rect[1];
41145             this._rect[2] = rect[2];
41146             this._rect[3] = rect[3];
41147         }
41148         this._notifyChanged$.next(this);
41149     };
41150     /**
41151      * Set the value of a vertex in the polygon representation of the rectangle.
41152      *
41153      * @description The polygon is defined to have the first vertex at the
41154      * bottom-left corner with the rest of the vertices following in clockwise order.
41155      *
41156      * @param {number} index - The index of the vertex to be set.
41157      * @param {Array<number>} value - The new value of the vertex.
41158      * @param {Transform} transform - The transform of the node related to the rectangle.
41159      * @ignore
41160      */
41161     RectGeometry.prototype.setVertex2d = function (index, value, transform) {
41162         var original = this._rect.slice();
41163         var changed = [
41164             Math.max(0, Math.min(1, value[0])),
41165             Math.max(0, Math.min(1, value[1])),
41166         ];
41167         var rect = [];
41168         if (index === 0) {
41169             rect[0] = changed[0];
41170             rect[1] = original[1];
41171             rect[2] = original[2];
41172             rect[3] = changed[1];
41173         }
41174         else if (index === 1) {
41175             rect[0] = changed[0];
41176             rect[1] = changed[1];
41177             rect[2] = original[2];
41178             rect[3] = original[3];
41179         }
41180         else if (index === 2) {
41181             rect[0] = original[0];
41182             rect[1] = changed[1];
41183             rect[2] = changed[0];
41184             rect[3] = original[3];
41185         }
41186         else if (index === 3) {
41187             rect[0] = original[0];
41188             rect[1] = original[1];
41189             rect[2] = changed[0];
41190             rect[3] = changed[1];
41191         }
41192         if (transform.fullPano) {
41193             var passingBoundaryLeftward = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
41194                 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
41195             var passingBoundaryRightward = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
41196                 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
41197             if (passingBoundaryLeftward || passingBoundaryRightward) {
41198                 this._inverted = !this._inverted;
41199             }
41200             else {
41201                 if (rect[0] - original[0] < -0.25) {
41202                     rect[0] = original[0];
41203                 }
41204                 if (rect[2] - original[2] > 0.25) {
41205                     rect[2] = original[2];
41206                 }
41207             }
41208             if (!this._inverted && rect[0] > rect[2] ||
41209                 this._inverted && rect[0] < rect[2]) {
41210                 rect[0] = original[0];
41211                 rect[2] = original[2];
41212             }
41213         }
41214         else {
41215             if (rect[0] > rect[2]) {
41216                 rect[0] = original[0];
41217                 rect[2] = original[2];
41218             }
41219         }
41220         if (rect[1] > rect[3]) {
41221             rect[1] = original[1];
41222             rect[3] = original[3];
41223         }
41224         this._rect[0] = rect[0];
41225         this._rect[1] = rect[1];
41226         this._rect[2] = rect[2];
41227         this._rect[3] = rect[3];
41228         this._notifyChanged$.next(this);
41229     };
41230     /** @ignore */
41231     RectGeometry.prototype.setCentroid2d = function (value, transform) {
41232         var original = this._rect.slice();
41233         var x0 = original[0];
41234         var x1 = this._inverted ? original[2] + 1 : original[2];
41235         var y0 = original[1];
41236         var y1 = original[3];
41237         var centerX = x0 + (x1 - x0) / 2;
41238         var centerY = y0 + (y1 - y0) / 2;
41239         var translationX = 0;
41240         if (transform.gpano != null &&
41241             transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
41242             translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
41243         }
41244         else {
41245             var minTranslationX = -x0;
41246             var maxTranslationX = 1 - x1;
41247             translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
41248         }
41249         var minTranslationY = -y0;
41250         var maxTranslationY = 1 - y1;
41251         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
41252         this._rect[0] = original[0] + translationX;
41253         this._rect[1] = original[1] + translationY;
41254         this._rect[2] = original[2] + translationX;
41255         this._rect[3] = original[3] + translationY;
41256         if (this._rect[0] < 0) {
41257             this._rect[0] += 1;
41258             this._inverted = !this._inverted;
41259         }
41260         else if (this._rect[0] > 1) {
41261             this._rect[0] -= 1;
41262             this._inverted = !this._inverted;
41263         }
41264         if (this._rect[2] < 0) {
41265             this._rect[2] += 1;
41266             this._inverted = !this._inverted;
41267         }
41268         else if (this._rect[2] > 1) {
41269             this._rect[2] -= 1;
41270             this._inverted = !this._inverted;
41271         }
41272         this._notifyChanged$.next(this);
41273     };
41274     /**
41275      * Get the 3D coordinates for the vertices of the rectangle with
41276      * interpolated points along the lines.
41277      *
41278      * @param {Transform} transform - The transform of the node related to
41279      * the rectangle.
41280      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
41281      * representing the rectangle.
41282      * @ignore
41283      */
41284     RectGeometry.prototype.getPoints3d = function (transform) {
41285         return this._getPoints2d()
41286             .map(function (point) {
41287             return transform.unprojectBasic(point, 200);
41288         });
41289     };
41290     /**
41291      * Get the coordinates of a vertex from the polygon representation of the geometry.
41292      *
41293      * @description The first vertex represents the bottom-left corner with the rest of
41294      * the vertices following in clockwise order. The method shifts the right side
41295      * coordinates of the rectangle by one unit to ensure that the vertices are ordered
41296      * clockwise.
41297      *
41298      * @param {number} index - Vertex index.
41299      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
41300      * @ignore
41301      */
41302     RectGeometry.prototype.getVertex2d = function (index) {
41303         return this._rectToVertices2d(this._rect)[index];
41304     };
41305     /**
41306      * Get the coordinates of a vertex from the polygon representation of the geometry.
41307      *
41308      * @description The first vertex represents the bottom-left corner with the rest of
41309      * the vertices following in clockwise order. The coordinates will not be shifted
41310      * so they may not appear in clockwise order when layed out on the plane.
41311      *
41312      * @param {number} index - Vertex index.
41313      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
41314      * @ignore
41315      */
41316     RectGeometry.prototype.getNonAdjustedVertex2d = function (index) {
41317         return this._rectToNonAdjustedVertices2d(this._rect)[index];
41318     };
41319     /**
41320      * Get a vertex from the polygon representation of the 3D coordinates for the
41321      * vertices of the geometry.
41322      *
41323      * @description The first vertex represents the bottom-left corner with the rest of
41324      * the vertices following in clockwise order.
41325      *
41326      * @param {number} index - Vertex index.
41327      * @param {Transform} transform - The transform of the node related to the geometry.
41328      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
41329      * the vertices of the geometry.
41330      * @ignore
41331      */
41332     RectGeometry.prototype.getVertex3d = function (index, transform) {
41333         return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
41334     };
41335     /**
41336      * Get a polygon representation of the 2D basic coordinates for the vertices of the rectangle.
41337      *
41338      * @description The first vertex represents the bottom-left corner with the rest of
41339      * the vertices following in clockwise order.
41340      *
41341      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates representing
41342      * the rectangle vertices.
41343      * @ignore
41344      */
41345     RectGeometry.prototype.getVertices2d = function () {
41346         return this._rectToVertices2d(this._rect);
41347     };
41348     /**
41349      * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
41350      *
41351      * @description The first vertex represents the bottom-left corner with the rest of
41352      * the vertices following in clockwise order.
41353      *
41354      * @param {Transform} transform - The transform of the node related to the rectangle.
41355      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
41356      * the rectangle vertices.
41357      * @ignore
41358      */
41359     RectGeometry.prototype.getVertices3d = function (transform) {
41360         return this._rectToVertices2d(this._rect)
41361             .map(function (vertex) {
41362             return transform.unprojectBasic(vertex, 200);
41363         });
41364     };
41365     /** @ignore */
41366     RectGeometry.prototype.getCentroid2d = function () {
41367         var rect = this._rect;
41368         var x0 = rect[0];
41369         var x1 = this._inverted ? rect[2] + 1 : rect[2];
41370         var y0 = rect[1];
41371         var y1 = rect[3];
41372         var centroidX = (x0 + x1) / 2;
41373         var centroidY = (y0 + y1) / 2;
41374         return [centroidX, centroidY];
41375     };
41376     /** @ignore */
41377     RectGeometry.prototype.getCentroid3d = function (transform) {
41378         var centroid2d = this.getCentroid2d();
41379         return transform.unprojectBasic(centroid2d, 200);
41380     };
41381     /**
41382      * @ignore
41383      */
41384     RectGeometry.prototype.getPoleOfInaccessibility2d = function () {
41385         return this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
41386     };
41387     /** @ignore */
41388     RectGeometry.prototype.getPoleOfInaccessibility3d = function (transform) {
41389         var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
41390         return transform.unprojectBasic(pole2d, 200);
41391     };
41392     /** @ignore */
41393     RectGeometry.prototype.getTriangles3d = function (transform) {
41394         return transform.fullPano ?
41395             [] :
41396             this._triangulate(this._project(this._getPoints2d(), transform), this.getPoints3d(transform));
41397     };
41398     /**
41399      * Check if a particular bottom-right value is valid according to the current
41400      * rectangle coordinates.
41401      *
41402      * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
41403      * @returns {boolean} Value indicating whether the provided bottom-right coordinates
41404      * are valid.
41405      * @ignore
41406      */
41407     RectGeometry.prototype.validate = function (bottomRight) {
41408         var rect = this._rect;
41409         if (!this._inverted && bottomRight[0] < rect[0] ||
41410             bottomRight[0] - rect[2] > 0.25 ||
41411             bottomRight[1] < rect[1]) {
41412             return false;
41413         }
41414         return true;
41415     };
41416     /**
41417      * Get the 2D coordinates for the vertices of the rectangle with
41418      * interpolated points along the lines.
41419      *
41420      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
41421      * representing the rectangle.
41422      */
41423     RectGeometry.prototype._getPoints2d = function () {
41424         var vertices2d = this._rectToVertices2d(this._rect);
41425         var sides = vertices2d.length - 1;
41426         var sections = 10;
41427         var points2d = [];
41428         for (var i = 0; i < sides; ++i) {
41429             var startX = vertices2d[i][0];
41430             var startY = vertices2d[i][1];
41431             var endX = vertices2d[i + 1][0];
41432             var endY = vertices2d[i + 1][1];
41433             var intervalX = (endX - startX) / (sections - 1);
41434             var intervalY = (endY - startY) / (sections - 1);
41435             for (var j = 0; j < sections; ++j) {
41436                 var point = [
41437                     startX + j * intervalX,
41438                     startY + j * intervalY,
41439                 ];
41440                 points2d.push(point);
41441             }
41442         }
41443         return points2d;
41444     };
41445     /**
41446      * Convert the top-left, bottom-right representation of a rectangle to a polygon
41447      * representation of the vertices starting at the bottom-left corner going
41448      * clockwise.
41449      *
41450      * @description The method shifts the right side coordinates of the rectangle
41451      * by one unit to ensure that the vertices are ordered clockwise.
41452      *
41453      * @param {Array<number>} rect - Top-left, bottom-right representation of a
41454      * rectangle.
41455      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
41456      * rectangle.
41457      */
41458     RectGeometry.prototype._rectToVertices2d = function (rect) {
41459         return [
41460             [rect[0], rect[3]],
41461             [rect[0], rect[1]],
41462             [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
41463             [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
41464             [rect[0], rect[3]],
41465         ];
41466     };
41467     /**
41468      * Convert the top-left, bottom-right representation of a rectangle to a polygon
41469      * representation of the vertices starting at the bottom-left corner going
41470      * clockwise.
41471      *
41472      * @description The first vertex represents the bottom-left corner with the rest of
41473      * the vertices following in clockwise order. The coordinates will not be shifted
41474      * to ensure that the vertices are ordered clockwise when layed out on the plane.
41475      *
41476      * @param {Array<number>} rect - Top-left, bottom-right representation of a
41477      * rectangle.
41478      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
41479      * rectangle.
41480      */
41481     RectGeometry.prototype._rectToNonAdjustedVertices2d = function (rect) {
41482         return [
41483             [rect[0], rect[3]],
41484             [rect[0], rect[1]],
41485             [rect[2], rect[1]],
41486             [rect[2], rect[3]],
41487             [rect[0], rect[3]],
41488         ];
41489     };
41490     return RectGeometry;
41491 }(Component_1.VertexGeometry));
41492 exports.RectGeometry = RectGeometry;
41493 exports.default = RectGeometry;
41494
41495 },{"../../../Component":291}],375:[function(require,module,exports){
41496 "use strict";
41497 var __extends = (this && this.__extends) || (function () {
41498     var extendStatics = function (d, b) {
41499         extendStatics = Object.setPrototypeOf ||
41500             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41501             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
41502         return extendStatics(d, b);
41503     }
41504     return function (d, b) {
41505         extendStatics(d, b);
41506         function __() { this.constructor = d; }
41507         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
41508     };
41509 })();
41510 Object.defineProperty(exports, "__esModule", { value: true });
41511 var earcut_1 = require("earcut");
41512 var martinez = require("martinez-polygon-clipping");
41513 var polylabel = require("@mapbox/polylabel");
41514 var THREE = require("three");
41515 var Component_1 = require("../../../Component");
41516 /**
41517  * @class VertexGeometry
41518  * @abstract
41519  * @classdesc Represents a vertex geometry.
41520  */
41521 var VertexGeometry = /** @class */ (function (_super) {
41522     __extends(VertexGeometry, _super);
41523     /**
41524      * Create a vertex geometry.
41525      *
41526      * @constructor
41527      * @ignore
41528      */
41529     function VertexGeometry() {
41530         var _this = _super.call(this) || this;
41531         _this._subsampleThreshold = 0.005;
41532         return _this;
41533     }
41534     /**
41535      * Finds the polygon pole of inaccessibility, the most distant internal
41536      * point from the polygon outline.
41537      *
41538      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
41539      * @returns {Array<number>} Point of inaccessibility.
41540      * @ignore
41541      */
41542     VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) {
41543         var pole2d = polylabel([points2d], 3e-2);
41544         return pole2d;
41545     };
41546     VertexGeometry.prototype._project = function (points2d, transform) {
41547         var camera = this._createCamera(transform.upVector().toArray(), transform.unprojectSfM([0, 0], 0), transform.unprojectSfM([0, 0], 10));
41548         return this._deunproject(points2d, transform, camera);
41549     };
41550     VertexGeometry.prototype._subsample = function (points2d, threshold) {
41551         if (threshold === void 0) { threshold = this._subsampleThreshold; }
41552         var subsampled = [];
41553         var length = points2d.length;
41554         for (var index = 0; index < length; index++) {
41555             var p1 = points2d[index];
41556             var p2 = points2d[(index + 1) % length];
41557             subsampled.push(p1);
41558             var dist = Math.sqrt(Math.pow((p2[0] - p1[0]), 2) + Math.pow((p2[1] - p1[1]), 2));
41559             var subsamples = Math.floor(dist / threshold);
41560             var coeff = 1 / (subsamples + 1);
41561             for (var i = 1; i <= subsamples; i++) {
41562                 var alpha = i * coeff;
41563                 var subsample = [
41564                     (1 - alpha) * p1[0] + alpha * p2[0],
41565                     (1 - alpha) * p1[1] + alpha * p2[1],
41566                 ];
41567                 subsampled.push(subsample);
41568             }
41569         }
41570         return subsampled;
41571     };
41572     /**
41573      * Triangulates a 2d polygon and returns the triangle
41574      * representation as a flattened array of 3d points.
41575      *
41576      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
41577      * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
41578      * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
41579      * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
41580      * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
41581      * @ignore
41582      */
41583     VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
41584         var data = [points2d.slice(0, -1)];
41585         for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
41586             var hole2d = _a[_i];
41587             data.push(hole2d.slice(0, -1));
41588         }
41589         var points = points3d.slice(0, -1);
41590         for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
41591             var hole3d = _c[_b];
41592             points = points.concat(hole3d.slice(0, -1));
41593         }
41594         var flattened = earcut_1.default.flatten(data);
41595         var indices = earcut_1.default(flattened.vertices, flattened.holes, flattened.dimensions);
41596         var triangles = [];
41597         for (var i = 0; i < indices.length; ++i) {
41598             var point = points[indices[i]];
41599             triangles.push(point[0]);
41600             triangles.push(point[1]);
41601             triangles.push(point[2]);
41602         }
41603         return triangles;
41604     };
41605     VertexGeometry.prototype._triangulatePano = function (points2d, holes2d, transform) {
41606         var triangles = [];
41607         var epsilon = 1e-9;
41608         var subareasX = 3;
41609         var subareasY = 3;
41610         for (var x = 0; x < subareasX; x++) {
41611             for (var y = 0; y < subareasY; y++) {
41612                 var epsilonX0 = x === 0 ? -epsilon : epsilon;
41613                 var epsilonY0 = y === 0 ? -epsilon : epsilon;
41614                 var x0 = x / subareasX + epsilonX0;
41615                 var y0 = y / subareasY + epsilonY0;
41616                 var x1 = (x + 1) / subareasX + epsilon;
41617                 var y1 = (y + 1) / subareasY + epsilon;
41618                 var bbox2d = [
41619                     [x0, y0],
41620                     [x0, y1],
41621                     [x1, y1],
41622                     [x1, y0],
41623                     [x0, y0],
41624                 ];
41625                 var lookat2d = [
41626                     (2 * x + 1) / (2 * subareasX),
41627                     (2 * y + 1) / (2 * subareasY),
41628                 ];
41629                 triangles.push.apply(triangles, this._triangulateSubarea(points2d, holes2d, bbox2d, lookat2d, transform));
41630             }
41631         }
41632         return triangles;
41633     };
41634     VertexGeometry.prototype._unproject = function (points2d, transform, distance) {
41635         if (distance === void 0) { distance = 200; }
41636         return points2d
41637             .map(function (point) {
41638             return transform.unprojectBasic(point, distance);
41639         });
41640     };
41641     VertexGeometry.prototype._createCamera = function (upVector, position, lookAt) {
41642         var camera = new THREE.Camera();
41643         camera.up.copy(new THREE.Vector3().fromArray(upVector));
41644         camera.position.copy(new THREE.Vector3().fromArray(position));
41645         camera.lookAt(new THREE.Vector3().fromArray(lookAt));
41646         camera.updateMatrix();
41647         camera.updateMatrixWorld(true);
41648         return camera;
41649     };
41650     VertexGeometry.prototype._deunproject = function (points2d, transform, camera) {
41651         return points2d
41652             .map(function (point2d) {
41653             var pointWorld = transform.unprojectBasic(point2d, 10000);
41654             var pointCamera = new THREE.Vector3(pointWorld[0], pointWorld[1], pointWorld[2])
41655                 .applyMatrix4(camera.matrixWorldInverse);
41656             return [pointCamera.x / pointCamera.z, pointCamera.y / pointCamera.z];
41657         });
41658     };
41659     VertexGeometry.prototype._triangulateSubarea = function (points2d, holes2d, bbox2d, lookat2d, transform) {
41660         var intersections = martinez.intersection([points2d].concat(holes2d), [bbox2d]);
41661         if (!intersections) {
41662             return [];
41663         }
41664         var triangles = [];
41665         var threshold = this._subsampleThreshold;
41666         var camera = this._createCamera(transform.upVector().toArray(), transform.unprojectSfM([0, 0], 0), transform.unprojectBasic(lookat2d, 10));
41667         for (var _i = 0, intersections_1 = intersections; _i < intersections_1.length; _i++) {
41668             var intersection = intersections_1[_i];
41669             var subsampledPolygon2d = this._subsample(intersection[0], threshold);
41670             var polygon2d = this._deunproject(subsampledPolygon2d, transform, camera);
41671             var polygon3d = this._unproject(subsampledPolygon2d, transform);
41672             var polygonHoles2d = [];
41673             var polygonHoles3d = [];
41674             for (var i = 1; i < intersection.length; i++) {
41675                 var subsampledHole2d = this._subsample(intersection[i], threshold);
41676                 var hole2d = this._deunproject(subsampledHole2d, transform, camera);
41677                 var hole3d = this._unproject(subsampledHole2d, transform);
41678                 polygonHoles2d.push(hole2d);
41679                 polygonHoles3d.push(hole3d);
41680             }
41681             triangles.push.apply(triangles, this._triangulate(polygon2d, polygon3d, polygonHoles2d, polygonHoles3d));
41682         }
41683         return triangles;
41684     };
41685     return VertexGeometry;
41686 }(Component_1.Geometry));
41687 exports.VertexGeometry = VertexGeometry;
41688 exports.default = VertexGeometry;
41689
41690 },{"../../../Component":291,"@mapbox/polylabel":1,"earcut":8,"martinez-polygon-clipping":22,"three":242}],376:[function(require,module,exports){
41691 "use strict";
41692 var __extends = (this && this.__extends) || (function () {
41693     var extendStatics = function (d, b) {
41694         extendStatics = Object.setPrototypeOf ||
41695             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41696             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
41697         return extendStatics(d, b);
41698     }
41699     return function (d, b) {
41700         extendStatics(d, b);
41701         function __() { this.constructor = d; }
41702         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
41703     };
41704 })();
41705 Object.defineProperty(exports, "__esModule", { value: true });
41706 var operators_1 = require("rxjs/operators");
41707 var rxjs_1 = require("rxjs");
41708 var Component_1 = require("../../../Component");
41709 var CreateHandlerBase = /** @class */ (function (_super) {
41710     __extends(CreateHandlerBase, _super);
41711     function CreateHandlerBase(component, container, navigator, viewportCoords, tagCreator) {
41712         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
41713         _this._tagCreator = tagCreator;
41714         _this._geometryCreated$ = new rxjs_1.Subject();
41715         return _this;
41716     }
41717     Object.defineProperty(CreateHandlerBase.prototype, "geometryCreated$", {
41718         get: function () {
41719             return this._geometryCreated$;
41720         },
41721         enumerable: true,
41722         configurable: true
41723     });
41724     CreateHandlerBase.prototype._enable = function () {
41725         this._enableCreate();
41726         this._container.element.classList.add("component-tag-create");
41727     };
41728     CreateHandlerBase.prototype._disable = function () {
41729         this._container.element.classList.remove("component-tag-create");
41730         this._disableCreate();
41731     };
41732     CreateHandlerBase.prototype._validateBasic = function (basic) {
41733         var x = basic[0];
41734         var y = basic[1];
41735         return 0 <= x && x <= 1 && 0 <= y && y <= 1;
41736     };
41737     CreateHandlerBase.prototype._mouseEventToBasic$ = function (mouseEvent$) {
41738         var _this = this;
41739         return mouseEvent$.pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$), operators_1.map(function (_a) {
41740             var event = _a[0], camera = _a[1], transform = _a[2];
41741             return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
41742         }));
41743     };
41744     return CreateHandlerBase;
41745 }(Component_1.TagHandlerBase));
41746 exports.CreateHandlerBase = CreateHandlerBase;
41747 exports.default = CreateHandlerBase;
41748
41749 },{"../../../Component":291,"rxjs":43,"rxjs/operators":241}],377:[function(require,module,exports){
41750 "use strict";
41751 var __extends = (this && this.__extends) || (function () {
41752     var extendStatics = function (d, b) {
41753         extendStatics = Object.setPrototypeOf ||
41754             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41755             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
41756         return extendStatics(d, b);
41757     }
41758     return function (d, b) {
41759         extendStatics(d, b);
41760         function __() { this.constructor = d; }
41761         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
41762     };
41763 })();
41764 Object.defineProperty(exports, "__esModule", { value: true });
41765 var operators_1 = require("rxjs/operators");
41766 var Component_1 = require("../../../Component");
41767 var CreatePointHandler = /** @class */ (function (_super) {
41768     __extends(CreatePointHandler, _super);
41769     function CreatePointHandler() {
41770         return _super !== null && _super.apply(this, arguments) || this;
41771     }
41772     CreatePointHandler.prototype._enableCreate = function () {
41773         this._container.mouseService.deferPixels(this._name, 4);
41774         this._geometryCreatedSubscription = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).pipe(operators_1.filter(this._validateBasic), operators_1.map(function (basic) {
41775             return new Component_1.PointGeometry(basic);
41776         }))
41777             .subscribe(this._geometryCreated$);
41778     };
41779     CreatePointHandler.prototype._disableCreate = function () {
41780         this._container.mouseService.undeferPixels(this._name);
41781         this._geometryCreatedSubscription.unsubscribe();
41782     };
41783     CreatePointHandler.prototype._getNameExtension = function () {
41784         return "create-point";
41785     };
41786     return CreatePointHandler;
41787 }(Component_1.CreateHandlerBase));
41788 exports.CreatePointHandler = CreatePointHandler;
41789 exports.default = CreatePointHandler;
41790
41791 },{"../../../Component":291,"rxjs/operators":241}],378:[function(require,module,exports){
41792 "use strict";
41793 var __extends = (this && this.__extends) || (function () {
41794     var extendStatics = function (d, b) {
41795         extendStatics = Object.setPrototypeOf ||
41796             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41797             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
41798         return extendStatics(d, b);
41799     }
41800     return function (d, b) {
41801         extendStatics(d, b);
41802         function __() { this.constructor = d; }
41803         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
41804     };
41805 })();
41806 Object.defineProperty(exports, "__esModule", { value: true });
41807 var Component_1 = require("../../../Component");
41808 var CreatePointsHandler = /** @class */ (function (_super) {
41809     __extends(CreatePointsHandler, _super);
41810     function CreatePointsHandler() {
41811         return _super !== null && _super.apply(this, arguments) || this;
41812     }
41813     CreatePointsHandler.prototype._addPoint = function (tag, basicPoint) {
41814         tag.geometry.addPoint2d(basicPoint);
41815     };
41816     Object.defineProperty(CreatePointsHandler.prototype, "_create$", {
41817         get: function () {
41818             return this._tagCreator.createPoints$;
41819         },
41820         enumerable: true,
41821         configurable: true
41822     });
41823     CreatePointsHandler.prototype._getNameExtension = function () {
41824         return "create-points";
41825     };
41826     CreatePointsHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
41827         tag.geometry.setPoint2d((tag.geometry).points.length - 1, basicPoint, transform);
41828     };
41829     return CreatePointsHandler;
41830 }(Component_1.CreateVertexHandler));
41831 exports.CreatePointsHandler = CreatePointsHandler;
41832 exports.default = CreatePointsHandler;
41833
41834 },{"../../../Component":291}],379:[function(require,module,exports){
41835 "use strict";
41836 var __extends = (this && this.__extends) || (function () {
41837     var extendStatics = function (d, b) {
41838         extendStatics = Object.setPrototypeOf ||
41839             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41840             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
41841         return extendStatics(d, b);
41842     }
41843     return function (d, b) {
41844         extendStatics(d, b);
41845         function __() { this.constructor = d; }
41846         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
41847     };
41848 })();
41849 Object.defineProperty(exports, "__esModule", { value: true });
41850 var Component_1 = require("../../../Component");
41851 var CreatePolygonHandler = /** @class */ (function (_super) {
41852     __extends(CreatePolygonHandler, _super);
41853     function CreatePolygonHandler() {
41854         return _super !== null && _super.apply(this, arguments) || this;
41855     }
41856     CreatePolygonHandler.prototype._addPoint = function (tag, basicPoint) {
41857         tag.addPoint(basicPoint);
41858     };
41859     Object.defineProperty(CreatePolygonHandler.prototype, "_create$", {
41860         get: function () {
41861             return this._tagCreator.createPolygon$;
41862         },
41863         enumerable: true,
41864         configurable: true
41865     });
41866     CreatePolygonHandler.prototype._getNameExtension = function () {
41867         return "create-polygon";
41868     };
41869     CreatePolygonHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
41870         tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basicPoint, transform);
41871     };
41872     return CreatePolygonHandler;
41873 }(Component_1.CreateVertexHandler));
41874 exports.CreatePolygonHandler = CreatePolygonHandler;
41875 exports.default = CreatePolygonHandler;
41876
41877 },{"../../../Component":291}],380:[function(require,module,exports){
41878 "use strict";
41879 var __extends = (this && this.__extends) || (function () {
41880     var extendStatics = function (d, b) {
41881         extendStatics = Object.setPrototypeOf ||
41882             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41883             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
41884         return extendStatics(d, b);
41885     }
41886     return function (d, b) {
41887         extendStatics(d, b);
41888         function __() { this.constructor = d; }
41889         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
41890     };
41891 })();
41892 Object.defineProperty(exports, "__esModule", { value: true });
41893 var rxjs_1 = require("rxjs");
41894 var operators_1 = require("rxjs/operators");
41895 var Component_1 = require("../../../Component");
41896 var CreateRectDragHandler = /** @class */ (function (_super) {
41897     __extends(CreateRectDragHandler, _super);
41898     function CreateRectDragHandler() {
41899         return _super !== null && _super.apply(this, arguments) || this;
41900     }
41901     CreateRectDragHandler.prototype._enableCreate = function () {
41902         var _this = this;
41903         this._container.mouseService.claimMouse(this._name, 2);
41904         this._deleteSubscription = this._navigator.stateService.currentTransform$.pipe(operators_1.map(function (transform) { return null; }), operators_1.skip(1))
41905             .subscribe(this._tagCreator.delete$);
41906         this._createSubscription = this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDragStart$)).pipe(operators_1.filter(this._validateBasic))
41907             .subscribe(this._tagCreator.createRect$);
41908         this._initializeAnchorIndexingSubscription = this._tagCreator.tag$.pipe(operators_1.filter(function (tag) {
41909             return !!tag;
41910         }))
41911             .subscribe(function (tag) {
41912             tag.geometry.initializeAnchorIndexing();
41913         });
41914         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) {
41915             var _b = _a[0], event = _b[0], camera = _b[1], transform = _a[1];
41916             return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
41917         }));
41918         this._setVertexSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
41919             return !!tag ?
41920                 rxjs_1.combineLatest(rxjs_1.of(tag), basicMouse$, _this._navigator.stateService.currentTransform$) :
41921                 rxjs_1.empty();
41922         }))
41923             .subscribe(function (_a) {
41924             var tag = _a[0], basicPoint = _a[1], transform = _a[2];
41925             tag.geometry.setOppositeVertex2d(basicPoint, transform);
41926         });
41927         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) {
41928             return basicPoint;
41929         }), operators_1.share());
41930         this._addPointSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
41931             return !!tag ?
41932                 rxjs_1.combineLatest(rxjs_1.of(tag), basicMouseDragEnd$) :
41933                 rxjs_1.empty();
41934         }))
41935             .subscribe(function (_a) {
41936             var tag = _a[0], basicPoint = _a[1];
41937             var rectGeometry = tag.geometry;
41938             if (!rectGeometry.validate(basicPoint)) {
41939                 basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
41940             }
41941             tag.addPoint(basicPoint);
41942         });
41943         this._geometryCreatedSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
41944             return !!tag ?
41945                 tag.created$.pipe(operators_1.map(function (t) {
41946                     return t.geometry;
41947                 })) :
41948                 rxjs_1.empty();
41949         }))
41950             .subscribe(this._geometryCreated$);
41951     };
41952     CreateRectDragHandler.prototype._disableCreate = function () {
41953         this._container.mouseService.unclaimMouse(this._name);
41954         this._tagCreator.delete$.next(null);
41955         this._addPointSubscription.unsubscribe();
41956         this._createSubscription.unsubscribe();
41957         this._deleteSubscription.unsubscribe();
41958         this._geometryCreatedSubscription.unsubscribe();
41959         this._initializeAnchorIndexingSubscription.unsubscribe();
41960         this._setVertexSubscription.unsubscribe();
41961     };
41962     CreateRectDragHandler.prototype._getNameExtension = function () {
41963         return "create-rect-drag";
41964     };
41965     return CreateRectDragHandler;
41966 }(Component_1.CreateHandlerBase));
41967 exports.CreateRectDragHandler = CreateRectDragHandler;
41968 exports.default = CreateRectDragHandler;
41969
41970 },{"../../../Component":291,"rxjs":43,"rxjs/operators":241}],381:[function(require,module,exports){
41971 "use strict";
41972 var __extends = (this && this.__extends) || (function () {
41973     var extendStatics = function (d, b) {
41974         extendStatics = Object.setPrototypeOf ||
41975             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41976             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
41977         return extendStatics(d, b);
41978     }
41979     return function (d, b) {
41980         extendStatics(d, b);
41981         function __() { this.constructor = d; }
41982         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
41983     };
41984 })();
41985 Object.defineProperty(exports, "__esModule", { value: true });
41986 var operators_1 = require("rxjs/operators");
41987 var Component_1 = require("../../../Component");
41988 var CreateRectHandler = /** @class */ (function (_super) {
41989     __extends(CreateRectHandler, _super);
41990     function CreateRectHandler() {
41991         return _super !== null && _super.apply(this, arguments) || this;
41992     }
41993     Object.defineProperty(CreateRectHandler.prototype, "_create$", {
41994         get: function () {
41995             return this._tagCreator.createRect$;
41996         },
41997         enumerable: true,
41998         configurable: true
41999     });
42000     CreateRectHandler.prototype._addPoint = function (tag, basicPoint) {
42001         var rectGeometry = tag.geometry;
42002         if (!rectGeometry.validate(basicPoint)) {
42003             basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
42004         }
42005         tag.addPoint(basicPoint);
42006     };
42007     CreateRectHandler.prototype._enable = function () {
42008         _super.prototype._enable.call(this);
42009         this._initializeAnchorIndexingSubscription = this._tagCreator.tag$.pipe(operators_1.filter(function (tag) {
42010             return !!tag;
42011         }))
42012             .subscribe(function (tag) {
42013             tag.geometry.initializeAnchorIndexing();
42014         });
42015     };
42016     CreateRectHandler.prototype._disable = function () {
42017         _super.prototype._disable.call(this);
42018         this._initializeAnchorIndexingSubscription.unsubscribe();
42019     };
42020     CreateRectHandler.prototype._getNameExtension = function () {
42021         return "create-rect";
42022     };
42023     CreateRectHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
42024         tag.geometry.setOppositeVertex2d(basicPoint, transform);
42025     };
42026     return CreateRectHandler;
42027 }(Component_1.CreateVertexHandler));
42028 exports.CreateRectHandler = CreateRectHandler;
42029 exports.default = CreateRectHandler;
42030
42031 },{"../../../Component":291,"rxjs/operators":241}],382:[function(require,module,exports){
42032 "use strict";
42033 var __extends = (this && this.__extends) || (function () {
42034     var extendStatics = function (d, b) {
42035         extendStatics = Object.setPrototypeOf ||
42036             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42037             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42038         return extendStatics(d, b);
42039     }
42040     return function (d, b) {
42041         extendStatics(d, b);
42042         function __() { this.constructor = d; }
42043         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42044     };
42045 })();
42046 Object.defineProperty(exports, "__esModule", { value: true });
42047 var rxjs_1 = require("rxjs");
42048 var operators_1 = require("rxjs/operators");
42049 var Component_1 = require("../../../Component");
42050 var CreateVertexHandler = /** @class */ (function (_super) {
42051     __extends(CreateVertexHandler, _super);
42052     function CreateVertexHandler() {
42053         return _super !== null && _super.apply(this, arguments) || this;
42054     }
42055     CreateVertexHandler.prototype._enableCreate = function () {
42056         var _this = this;
42057         this._container.mouseService.deferPixels(this._name, 4);
42058         var transformChanged$ = this._navigator.stateService.currentTransform$.pipe(operators_1.map(function () { }), operators_1.publishReplay(1), operators_1.refCount());
42059         this._deleteSubscription = transformChanged$.pipe(operators_1.skip(1))
42060             .subscribe(this._tagCreator.delete$);
42061         var basicClick$ = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).pipe(operators_1.share());
42062         this._createSubscription = transformChanged$.pipe(operators_1.switchMap(function () {
42063             return basicClick$.pipe(operators_1.filter(_this._validateBasic), operators_1.take(1));
42064         }))
42065             .subscribe(this._create$);
42066         this._setVertexSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
42067             return !!tag ?
42068                 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$) :
42069                 rxjs_1.empty();
42070         }))
42071             .subscribe(function (_a) {
42072             var tag = _a[0], event = _a[1], camera = _a[2], transform = _a[3];
42073             var basicPoint = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
42074             _this._setVertex2d(tag, basicPoint, transform);
42075         });
42076         this._addPointSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
42077             return !!tag ?
42078                 rxjs_1.combineLatest(rxjs_1.of(tag), basicClick$) :
42079                 rxjs_1.empty();
42080         }))
42081             .subscribe(function (_a) {
42082             var tag = _a[0], basicPoint = _a[1];
42083             _this._addPoint(tag, basicPoint);
42084         });
42085         this._geometryCreateSubscription = this._tagCreator.tag$.pipe(operators_1.switchMap(function (tag) {
42086             return !!tag ?
42087                 tag.created$.pipe(operators_1.map(function (t) {
42088                     return t.geometry;
42089                 })) :
42090                 rxjs_1.empty();
42091         }))
42092             .subscribe(this._geometryCreated$);
42093     };
42094     CreateVertexHandler.prototype._disableCreate = function () {
42095         this._container.mouseService.undeferPixels(this._name);
42096         this._tagCreator.delete$.next(null);
42097         this._addPointSubscription.unsubscribe();
42098         this._createSubscription.unsubscribe();
42099         this._deleteSubscription.unsubscribe();
42100         this._geometryCreateSubscription.unsubscribe();
42101         this._setVertexSubscription.unsubscribe();
42102     };
42103     return CreateVertexHandler;
42104 }(Component_1.CreateHandlerBase));
42105 exports.CreateVertexHandler = CreateVertexHandler;
42106 exports.default = CreateVertexHandler;
42107
42108 },{"../../../Component":291,"rxjs":43,"rxjs/operators":241}],383:[function(require,module,exports){
42109 "use strict";
42110 var __extends = (this && this.__extends) || (function () {
42111     var extendStatics = function (d, b) {
42112         extendStatics = Object.setPrototypeOf ||
42113             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42114             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42115         return extendStatics(d, b);
42116     }
42117     return function (d, b) {
42118         extendStatics(d, b);
42119         function __() { this.constructor = d; }
42120         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42121     };
42122 })();
42123 Object.defineProperty(exports, "__esModule", { value: true });
42124 var rxjs_1 = require("rxjs");
42125 var operators_1 = require("rxjs/operators");
42126 var Component_1 = require("../../../Component");
42127 var EditVertexHandler = /** @class */ (function (_super) {
42128     __extends(EditVertexHandler, _super);
42129     function EditVertexHandler(component, container, navigator, viewportCoords, tagSet) {
42130         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
42131         _this._tagSet = tagSet;
42132         return _this;
42133     }
42134     EditVertexHandler.prototype._enable = function () {
42135         var _this = this;
42136         var interaction$ = this._tagSet.changed$.pipe(operators_1.map(function (tagSet) {
42137             return tagSet.getAll();
42138         }), operators_1.switchMap(function (tags) {
42139             return rxjs_1.from(tags).pipe(operators_1.mergeMap(function (tag) {
42140                 return tag.interact$;
42141             }));
42142         }), operators_1.switchMap(function (interaction) {
42143             return rxjs_1.concat(rxjs_1.of(interaction), _this._container.mouseService.documentMouseUp$.pipe(operators_1.map(function () {
42144                 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
42145             }), operators_1.first()));
42146         }), operators_1.share());
42147         var mouseMove$ = rxjs_1.merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$).pipe(operators_1.share());
42148         this._claimMouseSubscription = interaction$.pipe(operators_1.switchMap(function (interaction) {
42149             return !!interaction.tag ? _this._container.mouseService.domMouseDragStart$ : rxjs_1.empty();
42150         }))
42151             .subscribe(function () {
42152             _this._container.mouseService.claimMouse(_this._name, 3);
42153         });
42154         this._cursorSubscription = interaction$.pipe(operators_1.map(function (interaction) {
42155             return interaction.cursor;
42156         }), operators_1.distinctUntilChanged())
42157             .subscribe(function (cursor) {
42158             var interactionCursors = ["crosshair", "move", "nesw-resize", "nwse-resize"];
42159             for (var _i = 0, interactionCursors_1 = interactionCursors; _i < interactionCursors_1.length; _i++) {
42160                 var interactionCursor = interactionCursors_1[_i];
42161                 _this._container.element.classList.remove("component-tag-edit-" + interactionCursor);
42162             }
42163             if (!!cursor) {
42164                 _this._container.element.classList.add("component-tag-edit-" + cursor);
42165             }
42166         });
42167         this._unclaimMouseSubscription = this._container.mouseService
42168             .filtered$(this._name, this._container.mouseService.domMouseDragEnd$)
42169             .subscribe(function (e) {
42170             _this._container.mouseService.unclaimMouse(_this._name);
42171         });
42172         this._preventDefaultSubscription = interaction$.pipe(operators_1.switchMap(function (interaction) {
42173             return !!interaction.tag ?
42174                 _this._container.mouseService.documentMouseMove$ :
42175                 rxjs_1.empty();
42176         }))
42177             .subscribe(function (event) {
42178             event.preventDefault(); // prevent selection of content outside the viewer
42179         });
42180         this._updateGeometrySubscription = interaction$.pipe(operators_1.switchMap(function (interaction) {
42181             if (interaction.operation === Component_1.TagOperation.None || !interaction.tag) {
42182                 return rxjs_1.empty();
42183             }
42184             var mouseDrag$ = _this._container.mouseService
42185                 .filtered$(_this._name, _this._container.mouseService.domMouseDrag$).pipe(operators_1.filter(function (event) {
42186                 return _this._viewportCoords.insideElement(event, _this._container.element);
42187             }));
42188             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) {
42189                 var event = _a[0], render = _a[1];
42190                 return [event, render, i, transform];
42191             }));
42192         }))
42193             .subscribe(function (_a) {
42194             var mouseEvent = _a[0], renderCamera = _a[1], interaction = _a[2], transform = _a[3];
42195             var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, interaction.offsetX, interaction.offsetY);
42196             var geometry = interaction.tag.geometry;
42197             if (interaction.operation === Component_1.TagOperation.Centroid) {
42198                 geometry.setCentroid2d(basic, transform);
42199             }
42200             else if (interaction.operation === Component_1.TagOperation.Vertex) {
42201                 geometry.setVertex2d(interaction.vertexIndex, basic, transform);
42202             }
42203         });
42204     };
42205     EditVertexHandler.prototype._disable = function () {
42206         this._claimMouseSubscription.unsubscribe();
42207         this._cursorSubscription.unsubscribe();
42208         this._preventDefaultSubscription.unsubscribe();
42209         this._unclaimMouseSubscription.unsubscribe();
42210         this._updateGeometrySubscription.unsubscribe();
42211     };
42212     EditVertexHandler.prototype._getNameExtension = function () {
42213         return "edit-vertex";
42214     };
42215     return EditVertexHandler;
42216 }(Component_1.TagHandlerBase));
42217 exports.EditVertexHandler = EditVertexHandler;
42218 exports.default = EditVertexHandler;
42219
42220
42221 },{"../../../Component":291,"rxjs":43,"rxjs/operators":241}],384:[function(require,module,exports){
42222 "use strict";
42223 var __extends = (this && this.__extends) || (function () {
42224     var extendStatics = function (d, b) {
42225         extendStatics = Object.setPrototypeOf ||
42226             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42227             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42228         return extendStatics(d, b);
42229     }
42230     return function (d, b) {
42231         extendStatics(d, b);
42232         function __() { this.constructor = d; }
42233         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42234     };
42235 })();
42236 Object.defineProperty(exports, "__esModule", { value: true });
42237 var Component_1 = require("../../../Component");
42238 var TagHandlerBase = /** @class */ (function (_super) {
42239     __extends(TagHandlerBase, _super);
42240     function TagHandlerBase(component, container, navigator, viewportCoords) {
42241         var _this = _super.call(this, component, container, navigator) || this;
42242         _this._name = _this._component.name + "-" + _this._getNameExtension();
42243         _this._viewportCoords = viewportCoords;
42244         return _this;
42245     }
42246     TagHandlerBase.prototype._getConfiguration = function (enable) {
42247         return {};
42248     };
42249     TagHandlerBase.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
42250         offsetX = offsetX != null ? offsetX : 0;
42251         offsetY = offsetY != null ? offsetY : 0;
42252         var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
42253         var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
42254         return basic;
42255     };
42256     return TagHandlerBase;
42257 }(Component_1.HandlerBase));
42258 exports.TagHandlerBase = TagHandlerBase;
42259 exports.default = TagHandlerBase;
42260
42261
42262 },{"../../../Component":291}],385:[function(require,module,exports){
42263 "use strict";
42264 Object.defineProperty(exports, "__esModule", { value: true });
42265 var operators_1 = require("rxjs/operators");
42266 var THREE = require("three");
42267 var rxjs_1 = require("rxjs");
42268 var Geo_1 = require("../../../Geo");
42269 var CreateTag = /** @class */ (function () {
42270     function CreateTag(geometry, transform, viewportCoords) {
42271         var _this = this;
42272         this._geometry = geometry;
42273         this._transform = transform;
42274         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
42275         this._aborted$ = new rxjs_1.Subject();
42276         this._created$ = new rxjs_1.Subject();
42277         this._glObjectsChanged$ = new rxjs_1.Subject();
42278         this._geometryChangedSubscription = this._geometry.changed$
42279             .subscribe(function () {
42280             _this._onGeometryChanged();
42281             _this._glObjectsChanged$.next(_this);
42282         });
42283     }
42284     Object.defineProperty(CreateTag.prototype, "geometry", {
42285         get: function () {
42286             return this._geometry;
42287         },
42288         enumerable: true,
42289         configurable: true
42290     });
42291     Object.defineProperty(CreateTag.prototype, "glObjects", {
42292         get: function () {
42293             return this._glObjects;
42294         },
42295         enumerable: true,
42296         configurable: true
42297     });
42298     Object.defineProperty(CreateTag.prototype, "aborted$", {
42299         get: function () {
42300             return this._aborted$;
42301         },
42302         enumerable: true,
42303         configurable: true
42304     });
42305     Object.defineProperty(CreateTag.prototype, "created$", {
42306         get: function () {
42307             return this._created$;
42308         },
42309         enumerable: true,
42310         configurable: true
42311     });
42312     Object.defineProperty(CreateTag.prototype, "glObjectsChanged$", {
42313         get: function () {
42314             return this._glObjectsChanged$;
42315         },
42316         enumerable: true,
42317         configurable: true
42318     });
42319     Object.defineProperty(CreateTag.prototype, "geometryChanged$", {
42320         get: function () {
42321             var _this = this;
42322             return this._geometry.changed$.pipe(operators_1.map(function () {
42323                 return _this;
42324             }));
42325         },
42326         enumerable: true,
42327         configurable: true
42328     });
42329     CreateTag.prototype.dispose = function () {
42330         this._geometryChangedSubscription.unsubscribe();
42331     };
42332     CreateTag.prototype._canvasToTransform = function (canvas) {
42333         var canvasX = Math.round(canvas[0]);
42334         var canvasY = Math.round(canvas[1]);
42335         var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
42336         return transform;
42337     };
42338     CreateTag.prototype._colorToBackground = function (color) {
42339         return "#" + ("000000" + color.toString(16)).substr(-6);
42340     };
42341     CreateTag.prototype._createOutine = function (polygon3d, color) {
42342         var positions = this._getLinePositions(polygon3d);
42343         var geometry = new THREE.BufferGeometry();
42344         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
42345         var material = new THREE.LineBasicMaterial({
42346             color: color,
42347             linewidth: 1,
42348         });
42349         return new THREE.Line(geometry, material);
42350     };
42351     CreateTag.prototype._disposeLine = function (line) {
42352         if (line == null) {
42353             return;
42354         }
42355         line.geometry.dispose();
42356         line.material.dispose();
42357     };
42358     CreateTag.prototype._getLinePositions = function (polygon3d) {
42359         var length = polygon3d.length;
42360         var positions = new Float32Array(length * 3);
42361         for (var i = 0; i < length; ++i) {
42362             var index = 3 * i;
42363             var position = polygon3d[i];
42364             positions[index] = position[0];
42365             positions[index + 1] = position[1];
42366             positions[index + 2] = position[2];
42367         }
42368         return positions;
42369     };
42370     return CreateTag;
42371 }());
42372 exports.CreateTag = CreateTag;
42373 exports.default = CreateTag;
42374
42375 },{"../../../Geo":294,"rxjs":43,"rxjs/operators":241,"three":242}],386:[function(require,module,exports){
42376 "use strict";
42377 var __extends = (this && this.__extends) || (function () {
42378     var extendStatics = function (d, b) {
42379         extendStatics = Object.setPrototypeOf ||
42380             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42381             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42382         return extendStatics(d, b);
42383     }
42384     return function (d, b) {
42385         extendStatics(d, b);
42386         function __() { this.constructor = d; }
42387         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42388     };
42389 })();
42390 Object.defineProperty(exports, "__esModule", { value: true });
42391 var vd = require("virtual-dom");
42392 var Tag_1 = require("../Tag");
42393 var Component_1 = require("../../../Component");
42394 var ExtremePointCreateTag = /** @class */ (function (_super) {
42395     __extends(ExtremePointCreateTag, _super);
42396     function ExtremePointCreateTag(geometry, options, transform, viewportCoords) {
42397         var _this = _super.call(this, geometry, transform, viewportCoords) || this;
42398         _this._options = {
42399             color: options.color == null ? 0xFFFFFF : options.color,
42400             indicateCompleter: options.indicateCompleter == null ? true : options.indicateCompleter,
42401         };
42402         _this._rectGeometry = new Tag_1.RectGeometry(_this._geometry.getRect2d(transform));
42403         _this._createGlObjects();
42404         return _this;
42405     }
42406     ExtremePointCreateTag.prototype.create = function () {
42407         if (this._geometry.points.length < 3) {
42408             return;
42409         }
42410         this._geometry.removePoint2d(this._geometry.points.length - 1);
42411         this._created$.next(this);
42412     };
42413     ExtremePointCreateTag.prototype.dispose = function () {
42414         _super.prototype.dispose.call(this);
42415         this._disposeObjects();
42416     };
42417     ExtremePointCreateTag.prototype.getDOMObjects = function (camera, size) {
42418         var _this = this;
42419         var container = {
42420             offsetHeight: size.height, offsetWidth: size.width,
42421         };
42422         var vNodes = [];
42423         var points2d = this._geometry.getPoints2d();
42424         var length = points2d.length;
42425         var _loop_1 = function (index) {
42426             var nonModifiedIndex = index;
42427             var _a = points2d[index], pointX = _a[0], pointY = _a[1];
42428             var pointCanvas = this_1._viewportCoords.basicToCanvasSafe(pointX, pointY, container, this_1._transform, camera);
42429             if (!pointCanvas) {
42430                 return "continue";
42431             }
42432             var abort = function (e) {
42433                 e.stopPropagation();
42434                 _this._aborted$.next(_this);
42435             };
42436             var remove = function (e) {
42437                 e.stopPropagation();
42438                 _this._geometry.removePoint2d(nonModifiedIndex);
42439             };
42440             var transform = this_1._canvasToTransform(pointCanvas);
42441             var completerProperties = {
42442                 onclick: index === 0 && length < 3 ? abort : remove,
42443                 style: { transform: transform },
42444             };
42445             vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
42446             var background = this_1._colorToBackground(this_1._options.color);
42447             var pointProperties = {
42448                 style: {
42449                     background: background,
42450                     transform: transform,
42451                 },
42452             };
42453             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
42454         };
42455         var this_1 = this;
42456         for (var index = 0; index < length - 1; index++) {
42457             _loop_1(index);
42458         }
42459         if (length > 2 && this._options.indicateCompleter === true) {
42460             var _a = this._geometry.getCentroid2d(this._transform), centroidX = _a[0], centroidY = _a[1];
42461             var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidX, centroidY, container, this._transform, camera);
42462             if (!!centroidCanvas) {
42463                 var complete = function (e) {
42464                     e.stopPropagation();
42465                     _this._geometry.removePoint2d(_this._geometry.points.length - 1);
42466                     _this._created$.next(_this);
42467                 };
42468                 var transform = this._canvasToTransform(centroidCanvas);
42469                 var completerProperties = {
42470                     onclick: complete,
42471                     style: { transform: transform },
42472                 };
42473                 vNodes.push(vd.h("div.TagCompleter.TagLarger", completerProperties, []));
42474                 var pointProperties = {
42475                     style: {
42476                         background: this._colorToBackground(this._options.color),
42477                         transform: transform,
42478                     },
42479                 };
42480                 vNodes.push(vd.h("div.TagVertex.TagLarger", pointProperties, []));
42481                 var dotProperties = {
42482                     style: {
42483                         transform: transform,
42484                     },
42485                 };
42486                 vNodes.push(vd.h("div.TagDot", dotProperties, []));
42487             }
42488         }
42489         return vNodes;
42490     };
42491     ExtremePointCreateTag.prototype._onGeometryChanged = function () {
42492         this._disposeObjects();
42493         this._rectGeometry = new Tag_1.RectGeometry(this._geometry.getRect2d(this._transform));
42494         this._createGlObjects();
42495     };
42496     ExtremePointCreateTag.prototype._createGlObjects = function () {
42497         this._glObjects = [];
42498         var polygon3d = this._rectGeometry.getPoints3d(this._transform);
42499         this._outline = this._createOutine(polygon3d, this._options.color);
42500         this._glObjects.push(this._outline);
42501     };
42502     ExtremePointCreateTag.prototype._disposeObjects = function () {
42503         this._disposeLine(this._outline);
42504         this._outline = null;
42505         this._glObjects = null;
42506     };
42507     return ExtremePointCreateTag;
42508 }(Component_1.CreateTag));
42509 exports.ExtremePointCreateTag = ExtremePointCreateTag;
42510
42511
42512 },{"../../../Component":291,"../Tag":361,"virtual-dom":247}],387:[function(require,module,exports){
42513 "use strict";
42514 var __extends = (this && this.__extends) || (function () {
42515     var extendStatics = function (d, b) {
42516         extendStatics = Object.setPrototypeOf ||
42517             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42518             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42519         return extendStatics(d, b);
42520     }
42521     return function (d, b) {
42522         extendStatics(d, b);
42523         function __() { this.constructor = d; }
42524         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42525     };
42526 })();
42527 Object.defineProperty(exports, "__esModule", { value: true });
42528 var THREE = require("three");
42529 var vd = require("virtual-dom");
42530 var Component_1 = require("../../../Component");
42531 /**
42532  * @class OutlineRenderTag
42533  * @classdesc Tag visualizing the properties of an OutlineTag.
42534  */
42535 var ExtremePointRenderTag = /** @class */ (function (_super) {
42536     __extends(ExtremePointRenderTag, _super);
42537     function ExtremePointRenderTag(tag, transform) {
42538         var _this = _super.call(this, tag, transform) || this;
42539         _this._rectGeometry = new Component_1.RectGeometry(_this._tag.geometry.getRect2d(transform));
42540         _this._fill = !transform.gpano ?
42541             _this._createFill() : null;
42542         _this._outline = _this._tag.lineWidth >= 1 ?
42543             _this._createOutline() :
42544             null;
42545         return _this;
42546     }
42547     ExtremePointRenderTag.prototype.dispose = function () {
42548         _super.prototype.dispose.call(this);
42549         this._disposeFill();
42550         this._disposeOutline();
42551     };
42552     ExtremePointRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
42553         var vNodes = [];
42554         var container = {
42555             offsetHeight: size.height, offsetWidth: size.width,
42556         };
42557         if (!this._tag.editable) {
42558             return vNodes;
42559         }
42560         var lineColor = this._colorToCss(this._tag.lineColor);
42561         var points2d = this._tag.geometry.getPoints2d();
42562         for (var i = 0; i < points2d.length; i++) {
42563             var _a = points2d[i], vertexBasicX = _a[0], vertexBasicY = _a[1];
42564             var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera);
42565             if (vertexCanvas == null) {
42566                 continue;
42567             }
42568             var cursor = "crosshair";
42569             var interact = this._interact(Component_1.TagOperation.Vertex, cursor, i);
42570             var vertexCanvasX = Math.round(vertexCanvas[0]);
42571             var vertexCanvasY = Math.round(vertexCanvas[1]);
42572             var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)";
42573             var properties = {
42574                 onmousedown: interact,
42575                 style: { background: lineColor, transform: transform, cursor: cursor },
42576             };
42577             vNodes.push(vd.h("div.TagResizer", properties, []));
42578             if (!this._tag.indicateVertices) {
42579                 continue;
42580             }
42581             var pointProperties = {
42582                 style: { background: lineColor, transform: transform },
42583             };
42584             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
42585         }
42586         return vNodes;
42587     };
42588     ExtremePointRenderTag.prototype.getGLObjects = function () {
42589         var glObjects = [];
42590         if (this._fill != null) {
42591             glObjects.push(this._fill);
42592         }
42593         if (this._outline != null) {
42594             glObjects.push(this._outline);
42595         }
42596         return glObjects;
42597     };
42598     ExtremePointRenderTag.prototype.getRetrievableObjects = function () {
42599         return this._fill != null ? [this._fill] : [];
42600     };
42601     ExtremePointRenderTag.prototype._onGeometryChanged = function () {
42602         this._rectGeometry = new Component_1.RectGeometry(this._tag.geometry.getRect2d(this._transform));
42603         if (this._fill != null) {
42604             this._updateFillGeometry();
42605         }
42606         if (this._outline != null) {
42607             this._updateOulineGeometry();
42608         }
42609     };
42610     ExtremePointRenderTag.prototype._onTagChanged = function () {
42611         var glObjectsChanged = false;
42612         if (this._fill != null) {
42613             this._updateFillMaterial(this._fill.material);
42614         }
42615         if (this._outline == null) {
42616             if (this._tag.lineWidth >= 1) {
42617                 this._outline = this._createOutline();
42618                 glObjectsChanged = true;
42619             }
42620         }
42621         else {
42622             this._updateOutlineMaterial();
42623         }
42624         return glObjectsChanged;
42625     };
42626     ExtremePointRenderTag.prototype._getPoints3d = function () {
42627         return this._rectGeometry.getPoints3d(this._transform);
42628     };
42629     ExtremePointRenderTag.prototype._getTriangles = function () {
42630         return this._rectGeometry.getTriangles3d(this._transform);
42631     };
42632     ExtremePointRenderTag.prototype._updateFillMaterial = function (material) {
42633         material.color = new THREE.Color(this._tag.fillColor);
42634         material.opacity = this._tag.fillOpacity;
42635         material.needsUpdate = true;
42636     };
42637     ExtremePointRenderTag.prototype._updateLineBasicMaterial = function (material) {
42638         material.color = new THREE.Color(this._tag.lineColor);
42639         material.linewidth = Math.max(this._tag.lineWidth, 1);
42640         material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0;
42641         material.opacity = this._tag.lineOpacity;
42642         material.transparent = this._tag.lineOpacity < 1;
42643         material.needsUpdate = true;
42644     };
42645     ExtremePointRenderTag.prototype._updateOutlineMaterial = function () {
42646         var material = this._outline.material;
42647         this._updateLineBasicMaterial(material);
42648     };
42649     return ExtremePointRenderTag;
42650 }(Component_1.OutlineRenderTagBase));
42651 exports.ExtremePointRenderTag = ExtremePointRenderTag;
42652 exports.default = ExtremePointRenderTag;
42653
42654
42655 },{"../../../Component":291,"three":242,"virtual-dom":247}],388:[function(require,module,exports){
42656 "use strict";
42657 var __extends = (this && this.__extends) || (function () {
42658     var extendStatics = function (d, b) {
42659         extendStatics = Object.setPrototypeOf ||
42660             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42661             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42662         return extendStatics(d, b);
42663     }
42664     return function (d, b) {
42665         extendStatics(d, b);
42666         function __() { this.constructor = d; }
42667         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42668     };
42669 })();
42670 Object.defineProperty(exports, "__esModule", { value: true });
42671 var Component_1 = require("../../../Component");
42672 /**
42673  * @class ExtremePointTag
42674  *
42675  * @classdesc Tag holding properties for visualizing a extreme points
42676  * and their outline.
42677  *
42678  * @example
42679  * ```
42680  * var geometry = new Mapillary.TagComponent.PointsGeometry([[0.3, 0.3], [0.5, 0.4]]);
42681  * var tag = new Mapillary.TagComponent.ExtremePointTag(
42682  *     "id-1",
42683  *     geometry
42684  *     { editable: true, lineColor: 0xff0000 });
42685  *
42686  * tagComponent.add([tag]);
42687  * ```
42688  */
42689 var ExtremePointTag = /** @class */ (function (_super) {
42690     __extends(ExtremePointTag, _super);
42691     /**
42692      * Create an extreme point tag.
42693      *
42694      * @override
42695      * @constructor
42696      * @param {string} id - Unique identifier of the tag.
42697      * @param {PointsGeometry} geometry - Geometry defining points of tag.
42698      * @param {IExtremePointTagOptions} options - Options defining the visual appearance and
42699      * behavior of the extreme point tag.
42700      */
42701     function ExtremePointTag(id, geometry, options) {
42702         var _this = _super.call(this, id, geometry) || this;
42703         options = !!options ? options : {};
42704         _this._editable = options.editable == null ? false : options.editable;
42705         _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
42706         _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
42707         _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
42708         _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
42709         _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
42710         _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
42711         return _this;
42712     }
42713     Object.defineProperty(ExtremePointTag.prototype, "editable", {
42714         /**
42715          * Get editable property.
42716          * @returns {boolean} Value indicating if tag is editable.
42717          */
42718         get: function () {
42719             return this._editable;
42720         },
42721         /**
42722          * Set editable property.
42723          * @param {boolean}
42724          *
42725          * @fires Tag#changed
42726          */
42727         set: function (value) {
42728             this._editable = value;
42729             this._notifyChanged$.next(this);
42730         },
42731         enumerable: true,
42732         configurable: true
42733     });
42734     Object.defineProperty(ExtremePointTag.prototype, "fillColor", {
42735         /**
42736          * Get fill color property.
42737          * @returns {number}
42738          */
42739         get: function () {
42740             return this._fillColor;
42741         },
42742         /**
42743          * Set fill color property.
42744          * @param {number}
42745          *
42746          * @fires Tag#changed
42747          */
42748         set: function (value) {
42749             this._fillColor = value;
42750             this._notifyChanged$.next(this);
42751         },
42752         enumerable: true,
42753         configurable: true
42754     });
42755     Object.defineProperty(ExtremePointTag.prototype, "fillOpacity", {
42756         /**
42757          * Get fill opacity property.
42758          * @returns {number}
42759          */
42760         get: function () {
42761             return this._fillOpacity;
42762         },
42763         /**
42764          * Set fill opacity property.
42765          * @param {number}
42766          *
42767          * @fires Tag#changed
42768          */
42769         set: function (value) {
42770             this._fillOpacity = value;
42771             this._notifyChanged$.next(this);
42772         },
42773         enumerable: true,
42774         configurable: true
42775     });
42776     Object.defineProperty(ExtremePointTag.prototype, "geometry", {
42777         /** @inheritdoc */
42778         get: function () {
42779             return this._geometry;
42780         },
42781         enumerable: true,
42782         configurable: true
42783     });
42784     Object.defineProperty(ExtremePointTag.prototype, "indicateVertices", {
42785         /**
42786          * Get indicate vertices property.
42787          * @returns {boolean} Value indicating if vertices should be indicated
42788          * when tag is editable.
42789          */
42790         get: function () {
42791             return this._indicateVertices;
42792         },
42793         /**
42794          * Set indicate vertices property.
42795          * @param {boolean}
42796          *
42797          * @fires Tag#changed
42798          */
42799         set: function (value) {
42800             this._indicateVertices = value;
42801             this._notifyChanged$.next(this);
42802         },
42803         enumerable: true,
42804         configurable: true
42805     });
42806     Object.defineProperty(ExtremePointTag.prototype, "lineColor", {
42807         /**
42808          * Get line color property.
42809          * @returns {number}
42810          */
42811         get: function () {
42812             return this._lineColor;
42813         },
42814         /**
42815          * Set line color property.
42816          * @param {number}
42817          *
42818          * @fires Tag#changed
42819          */
42820         set: function (value) {
42821             this._lineColor = value;
42822             this._notifyChanged$.next(this);
42823         },
42824         enumerable: true,
42825         configurable: true
42826     });
42827     Object.defineProperty(ExtremePointTag.prototype, "lineOpacity", {
42828         /**
42829          * Get line opacity property.
42830          * @returns {number}
42831          */
42832         get: function () {
42833             return this._lineOpacity;
42834         },
42835         /**
42836          * Set line opacity property.
42837          * @param {number}
42838          *
42839          * @fires Tag#changed
42840          */
42841         set: function (value) {
42842             this._lineOpacity = value;
42843             this._notifyChanged$.next(this);
42844         },
42845         enumerable: true,
42846         configurable: true
42847     });
42848     Object.defineProperty(ExtremePointTag.prototype, "lineWidth", {
42849         /**
42850          * Get line width property.
42851          * @returns {number}
42852          */
42853         get: function () {
42854             return this._lineWidth;
42855         },
42856         /**
42857          * Set line width property.
42858          * @param {number}
42859          *
42860          * @fires Tag#changed
42861          */
42862         set: function (value) {
42863             this._lineWidth = value;
42864             this._notifyChanged$.next(this);
42865         },
42866         enumerable: true,
42867         configurable: true
42868     });
42869     /**
42870      * Set options for tag.
42871      *
42872      * @description Sets all the option properties provided and keeps
42873      * the rest of the values as is.
42874      *
42875      * @param {IExtremePointTagOptions} options - Extreme point tag options
42876      *
42877      * @fires {Tag#changed}
42878      */
42879     ExtremePointTag.prototype.setOptions = function (options) {
42880         this._editable = options.editable == null ? this._editable : options.editable;
42881         this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
42882         this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
42883         this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
42884         this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
42885         this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
42886         this._notifyChanged$.next(this);
42887     };
42888     return ExtremePointTag;
42889 }(Component_1.Tag));
42890 exports.ExtremePointTag = ExtremePointTag;
42891 exports.default = ExtremePointTag;
42892
42893 },{"../../../Component":291}],389:[function(require,module,exports){
42894 "use strict";
42895 var __extends = (this && this.__extends) || (function () {
42896     var extendStatics = function (d, b) {
42897         extendStatics = Object.setPrototypeOf ||
42898             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42899             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42900         return extendStatics(d, b);
42901     }
42902     return function (d, b) {
42903         extendStatics(d, b);
42904         function __() { this.constructor = d; }
42905         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42906     };
42907 })();
42908 Object.defineProperty(exports, "__esModule", { value: true });
42909 var vd = require("virtual-dom");
42910 var Component_1 = require("../../../Component");
42911 var OutlineCreateTag = /** @class */ (function (_super) {
42912     __extends(OutlineCreateTag, _super);
42913     function OutlineCreateTag(geometry, options, transform, viewportCoords) {
42914         var _this = _super.call(this, geometry, transform, viewportCoords) || this;
42915         _this._options = { color: options.color == null ? 0xFFFFFF : options.color };
42916         _this._createGlObjects();
42917         return _this;
42918     }
42919     OutlineCreateTag.prototype.create = function () {
42920         if (this._geometry instanceof Component_1.RectGeometry) {
42921             this._created$.next(this);
42922         }
42923         else if (this._geometry instanceof Component_1.PolygonGeometry) {
42924             var polygonGeometry = this._geometry;
42925             polygonGeometry.removeVertex2d(polygonGeometry.polygon.length - 2);
42926             this._created$.next(this);
42927         }
42928     };
42929     OutlineCreateTag.prototype.dispose = function () {
42930         _super.prototype.dispose.call(this);
42931         this._disposeLine(this._outline);
42932         this._disposeObjects();
42933     };
42934     OutlineCreateTag.prototype.getDOMObjects = function (camera, size) {
42935         var _this = this;
42936         var vNodes = [];
42937         var container = {
42938             offsetHeight: size.height, offsetWidth: size.width,
42939         };
42940         var abort = function (e) {
42941             e.stopPropagation();
42942             _this._aborted$.next(_this);
42943         };
42944         if (this._geometry instanceof Component_1.RectGeometry) {
42945             var anchorIndex = this._geometry.anchorIndex;
42946             var vertexIndex = anchorIndex === undefined ? 1 : anchorIndex;
42947             var _a = this._geometry.getVertex2d(vertexIndex), basicX = _a[0], basicY = _a[1];
42948             var canvasPoint = this._viewportCoords.basicToCanvasSafe(basicX, basicY, container, this._transform, camera);
42949             if (canvasPoint != null) {
42950                 var background = this._colorToBackground(this._options.color);
42951                 var transform = this._canvasToTransform(canvasPoint);
42952                 var pointProperties = {
42953                     style: { background: background, transform: transform },
42954                 };
42955                 var completerProperties = {
42956                     onclick: abort,
42957                     style: { transform: transform },
42958                 };
42959                 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
42960                 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
42961             }
42962         }
42963         else if (this._geometry instanceof Component_1.PolygonGeometry) {
42964             var polygonGeometry_1 = this._geometry;
42965             var _b = polygonGeometry_1.getVertex2d(0), firstVertexBasicX = _b[0], firstVertexBasicY = _b[1];
42966             var firstVertexCanvas = this._viewportCoords.basicToCanvasSafe(firstVertexBasicX, firstVertexBasicY, container, this._transform, camera);
42967             if (firstVertexCanvas != null) {
42968                 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
42969                     function (e) {
42970                         e.stopPropagation();
42971                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
42972                         _this._created$.next(_this);
42973                     } :
42974                     abort;
42975                 var transform = this._canvasToTransform(firstVertexCanvas);
42976                 var completerProperties = {
42977                     onclick: firstOnclick,
42978                     style: { transform: transform },
42979                 };
42980                 var firstClass = polygonGeometry_1.polygon.length > 4 ?
42981                     "TagCompleter" :
42982                     "TagInteractor";
42983                 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
42984             }
42985             if (polygonGeometry_1.polygon.length > 3) {
42986                 var _c = polygonGeometry_1.getVertex2d(polygonGeometry_1.polygon.length - 3), lastVertexBasicX = _c[0], lastVertexBasicY = _c[1];
42987                 var lastVertexCanvas = this._viewportCoords.basicToCanvasSafe(lastVertexBasicX, lastVertexBasicY, container, this._transform, camera);
42988                 if (lastVertexCanvas != null) {
42989                     var remove = function (e) {
42990                         e.stopPropagation();
42991                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
42992                     };
42993                     var transform = this._canvasToTransform(lastVertexCanvas);
42994                     var completerProperties = {
42995                         onclick: remove,
42996                         style: { transform: transform },
42997                     };
42998                     vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
42999                 }
43000             }
43001             var verticesBasic = polygonGeometry_1.polygon.slice();
43002             verticesBasic.splice(-2, 2);
43003             for (var _i = 0, verticesBasic_1 = verticesBasic; _i < verticesBasic_1.length; _i++) {
43004                 var vertexBasic = verticesBasic_1[_i];
43005                 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasic[0], vertexBasic[1], container, this._transform, camera);
43006                 if (vertexCanvas != null) {
43007                     var background = this._colorToBackground(this._options.color);
43008                     var transform = this._canvasToTransform(vertexCanvas);
43009                     var pointProperties = {
43010                         style: {
43011                             background: background,
43012                             transform: transform,
43013                         },
43014                     };
43015                     vNodes.push(vd.h("div.TagVertex", pointProperties, []));
43016                 }
43017             }
43018         }
43019         return vNodes;
43020     };
43021     OutlineCreateTag.prototype.addPoint = function (point) {
43022         if (this._geometry instanceof Component_1.RectGeometry) {
43023             var rectGeometry = this._geometry;
43024             if (!rectGeometry.validate(point)) {
43025                 return;
43026             }
43027             this._created$.next(this);
43028         }
43029         else if (this._geometry instanceof Component_1.PolygonGeometry) {
43030             var polygonGeometry = this._geometry;
43031             polygonGeometry.addVertex2d(point);
43032         }
43033     };
43034     OutlineCreateTag.prototype._onGeometryChanged = function () {
43035         this._disposeLine(this._outline);
43036         this._disposeObjects();
43037         this._createGlObjects();
43038     };
43039     OutlineCreateTag.prototype._disposeObjects = function () {
43040         this._outline = null;
43041         this._glObjects = [];
43042     };
43043     OutlineCreateTag.prototype._createGlObjects = function () {
43044         var polygon3d = this._geometry instanceof Component_1.RectGeometry ?
43045             this._geometry.getPoints3d(this._transform) :
43046             this._geometry.getVertices3d(this._transform);
43047         this._outline = this._createOutine(polygon3d, this._options.color);
43048         this._glObjects = [this._outline];
43049     };
43050     return OutlineCreateTag;
43051 }(Component_1.CreateTag));
43052 exports.OutlineCreateTag = OutlineCreateTag;
43053 exports.default = OutlineCreateTag;
43054
43055
43056 },{"../../../Component":291,"virtual-dom":247}],390:[function(require,module,exports){
43057 "use strict";
43058 var __extends = (this && this.__extends) || (function () {
43059     var extendStatics = function (d, b) {
43060         extendStatics = Object.setPrototypeOf ||
43061             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43062             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
43063         return extendStatics(d, b);
43064     }
43065     return function (d, b) {
43066         extendStatics(d, b);
43067         function __() { this.constructor = d; }
43068         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43069     };
43070 })();
43071 Object.defineProperty(exports, "__esModule", { value: true });
43072 var THREE = require("three");
43073 var vd = require("virtual-dom");
43074 var Component_1 = require("../../../Component");
43075 /**
43076  * @class OutlineRenderTag
43077  * @classdesc Tag visualizing the properties of an OutlineTag.
43078  */
43079 var OutlineRenderTag = /** @class */ (function (_super) {
43080     __extends(OutlineRenderTag, _super);
43081     function OutlineRenderTag(tag, transform) {
43082         var _this = _super.call(this, tag, transform) || this;
43083         _this._fill = !transform.gpano ?
43084             _this._createFill() :
43085             transform.fullPano &&
43086                 tag.domain === Component_1.TagDomain.TwoDimensional &&
43087                 tag.geometry instanceof Component_1.PolygonGeometry ?
43088                 _this._createFill() :
43089                 null;
43090         _this._holes = _this._tag.lineWidth >= 1 ?
43091             _this._createHoles() :
43092             [];
43093         _this._outline = _this._tag.lineWidth >= 1 ?
43094             _this._createOutline() :
43095             null;
43096         return _this;
43097     }
43098     OutlineRenderTag.prototype.dispose = function () {
43099         _super.prototype.dispose.call(this);
43100         this._disposeFill();
43101         this._disposeHoles();
43102         this._disposeOutline();
43103     };
43104     OutlineRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
43105         var _this = this;
43106         var vNodes = [];
43107         var isRect = this._tag.geometry instanceof Component_1.RectGeometry;
43108         var isPerspective = !this._transform.gpano;
43109         var container = {
43110             offsetHeight: size.height, offsetWidth: size.width,
43111         };
43112         if (this._tag.icon != null && (isRect || isPerspective)) {
43113             var _a = this._tag.geometry instanceof Component_1.RectGeometry ?
43114                 this._tag.geometry.getVertex2d(this._tag.iconIndex) :
43115                 this._tag.geometry.getPoleOfInaccessibility2d(), iconBasicX = _a[0], iconBasicY = _a[1];
43116             var iconCanvas = this._viewportCoords.basicToCanvasSafe(iconBasicX, iconBasicY, container, this._transform, camera);
43117             if (iconCanvas != null) {
43118                 var interact = function () {
43119                     _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
43120                 };
43121                 if (atlas.loaded) {
43122                     var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat);
43123                     var iconCanvasX = Math.round(iconCanvas[0]);
43124                     var iconCanvasY = Math.round(iconCanvas[1]);
43125                     var transform = "translate(" + iconCanvasX + "px," + iconCanvasY + "px)";
43126                     var click = function (e) {
43127                         e.stopPropagation();
43128                         _this._tag.click$.next(_this._tag);
43129                     };
43130                     var properties = {
43131                         onclick: click,
43132                         onmousedown: interact,
43133                         style: { transform: transform },
43134                     };
43135                     vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
43136                 }
43137             }
43138         }
43139         else if (this._tag.text != null && (isRect || isPerspective)) {
43140             var _b = this._tag.geometry instanceof Component_1.RectGeometry ?
43141                 this._tag.geometry.getVertex2d(3) :
43142                 this._tag.geometry.getPoleOfInaccessibility2d(), textBasicX = _b[0], textBasicY = _b[1];
43143             var textCanvas = this._viewportCoords.basicToCanvasSafe(textBasicX, textBasicY, container, this._transform, camera);
43144             if (textCanvas != null) {
43145                 var textCanvasX = Math.round(textCanvas[0]);
43146                 var textCanvasY = Math.round(textCanvas[1]);
43147                 var transform = this._tag.geometry instanceof Component_1.RectGeometry ?
43148                     "translate(" + textCanvasX + "px," + textCanvasY + "px)" :
43149                     "translate(-50%, -50%) translate(" + textCanvasX + "px," + textCanvasY + "px)";
43150                 var interact = function () {
43151                     _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
43152                 };
43153                 var properties = {
43154                     onmousedown: interact,
43155                     style: {
43156                         color: this._colorToCss(this._tag.textColor),
43157                         transform: transform,
43158                     },
43159                     textContent: this._tag.text,
43160                 };
43161                 vNodes.push(vd.h("span.TagSymbol", properties, []));
43162             }
43163         }
43164         if (!this._tag.editable) {
43165             return vNodes;
43166         }
43167         var lineColor = this._colorToCss(this._tag.lineColor);
43168         if (this._tag.geometry instanceof Component_1.RectGeometry) {
43169             var _c = this._tag.geometry.getCentroid2d(), centroidBasicX = _c[0], centroidBasicY = _c[1];
43170             var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
43171             if (centroidCanvas != null) {
43172                 var interact = this._interact(Component_1.TagOperation.Centroid, "move");
43173                 var centroidCanvasX = Math.round(centroidCanvas[0]);
43174                 var centroidCanvasY = Math.round(centroidCanvas[1]);
43175                 var transform = "translate(-50%, -50%) translate(" + centroidCanvasX + "px," + centroidCanvasY + "px)";
43176                 var properties = {
43177                     onmousedown: interact,
43178                     style: { background: lineColor, transform: transform },
43179                 };
43180                 vNodes.push(vd.h("div.TagMover", properties, []));
43181             }
43182         }
43183         var vertices2d = this._tag.geometry.getVertices2d();
43184         for (var i = 0; i < vertices2d.length - 1; i++) {
43185             if (isRect &&
43186                 ((this._tag.icon != null && i === this._tag.iconIndex) ||
43187                     (this._tag.icon == null && this._tag.text != null && i === 3))) {
43188                 continue;
43189             }
43190             var _d = vertices2d[i], vertexBasicX = _d[0], vertexBasicY = _d[1];
43191             var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera);
43192             if (vertexCanvas == null) {
43193                 continue;
43194             }
43195             var cursor = isRect ?
43196                 i % 2 === 0 ? "nesw-resize" : "nwse-resize" :
43197                 "crosshair";
43198             var interact = this._interact(Component_1.TagOperation.Vertex, cursor, i);
43199             var vertexCanvasX = Math.round(vertexCanvas[0]);
43200             var vertexCanvasY = Math.round(vertexCanvas[1]);
43201             var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)";
43202             var properties = {
43203                 onmousedown: interact,
43204                 style: { background: lineColor, transform: transform, cursor: cursor },
43205             };
43206             vNodes.push(vd.h("div.TagResizer", properties, []));
43207             if (!this._tag.indicateVertices) {
43208                 continue;
43209             }
43210             var pointProperties = {
43211                 style: { background: lineColor, transform: transform },
43212             };
43213             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
43214         }
43215         return vNodes;
43216     };
43217     OutlineRenderTag.prototype.getGLObjects = function () {
43218         var glObjects = [];
43219         if (this._fill != null) {
43220             glObjects.push(this._fill);
43221         }
43222         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
43223             var hole = _a[_i];
43224             glObjects.push(hole);
43225         }
43226         if (this._outline != null) {
43227             glObjects.push(this._outline);
43228         }
43229         return glObjects;
43230     };
43231     OutlineRenderTag.prototype.getRetrievableObjects = function () {
43232         return this._fill != null ? [this._fill] : [];
43233     };
43234     OutlineRenderTag.prototype._onGeometryChanged = function () {
43235         if (this._fill != null) {
43236             this._updateFillGeometry();
43237         }
43238         if (this._holes.length > 0) {
43239             this._updateHoleGeometries();
43240         }
43241         if (this._outline != null) {
43242             this._updateOulineGeometry();
43243         }
43244     };
43245     OutlineRenderTag.prototype._onTagChanged = function () {
43246         var glObjectsChanged = false;
43247         if (this._fill != null) {
43248             this._updateFillMaterial(this._fill.material);
43249         }
43250         if (this._outline == null) {
43251             if (this._tag.lineWidth >= 1) {
43252                 this._holes = this._createHoles();
43253                 this._outline = this._createOutline();
43254                 glObjectsChanged = true;
43255             }
43256         }
43257         else {
43258             this._updateHoleMaterials();
43259             this._updateOutlineMaterial();
43260         }
43261         return glObjectsChanged;
43262     };
43263     OutlineRenderTag.prototype._getPoints3d = function () {
43264         return this._in3dDomain() ?
43265             this._tag.geometry.getVertices3d(this._transform) :
43266             this._tag.geometry.getPoints3d(this._transform);
43267     };
43268     OutlineRenderTag.prototype._getTriangles = function () {
43269         return this._in3dDomain() ?
43270             this._tag.geometry.get3dDomainTriangles3d(this._transform) :
43271             this._tag.geometry.getTriangles3d(this._transform);
43272     };
43273     OutlineRenderTag.prototype._updateFillMaterial = function (material) {
43274         material.color = new THREE.Color(this._tag.fillColor);
43275         material.opacity = this._tag.fillOpacity;
43276         material.needsUpdate = true;
43277     };
43278     OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
43279         material.color = new THREE.Color(this._tag.lineColor);
43280         material.linewidth = Math.max(this._tag.lineWidth, 1);
43281         material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0;
43282         material.opacity = this._tag.lineOpacity;
43283         material.transparent = this._tag.lineOpacity < 1;
43284         material.needsUpdate = true;
43285     };
43286     OutlineRenderTag.prototype._createHoles = function () {
43287         var holes = [];
43288         if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
43289             var holes3d = this._getHoles3d();
43290             for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
43291                 var holePoints3d = holes3d_1[_i];
43292                 var hole = this._createLine(holePoints3d);
43293                 holes.push(hole);
43294             }
43295         }
43296         return holes;
43297     };
43298     OutlineRenderTag.prototype._disposeHoles = function () {
43299         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
43300             var hole = _a[_i];
43301             hole.geometry.dispose();
43302             hole.material.dispose();
43303         }
43304         this._holes = [];
43305     };
43306     OutlineRenderTag.prototype._getHoles3d = function () {
43307         var polygonGeometry = this._tag.geometry;
43308         return this._in3dDomain() ?
43309             polygonGeometry.getHoleVertices3d(this._transform) :
43310             polygonGeometry.getHolePoints3d(this._transform);
43311     };
43312     OutlineRenderTag.prototype._in3dDomain = function () {
43313         return this._tag.geometry instanceof Component_1.PolygonGeometry && this._tag.domain === Component_1.TagDomain.ThreeDimensional;
43314     };
43315     OutlineRenderTag.prototype._updateHoleGeometries = function () {
43316         var holes3d = this._getHoles3d();
43317         if (holes3d.length !== this._holes.length) {
43318             throw new Error("Changing the number of holes is not supported.");
43319         }
43320         for (var i = 0; i < this._holes.length; i++) {
43321             var holePoints3d = holes3d[i];
43322             var hole = this._holes[i];
43323             this._updateLine(hole, holePoints3d);
43324         }
43325     };
43326     OutlineRenderTag.prototype._updateHoleMaterials = function () {
43327         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
43328             var hole = _a[_i];
43329             this._updateLineBasicMaterial(hole.material);
43330         }
43331     };
43332     OutlineRenderTag.prototype._updateOutlineMaterial = function () {
43333         this._updateLineBasicMaterial(this._outline.material);
43334     };
43335     return OutlineRenderTag;
43336 }(Component_1.OutlineRenderTagBase));
43337 exports.OutlineRenderTag = OutlineRenderTag;
43338
43339
43340 },{"../../../Component":291,"three":242,"virtual-dom":247}],391:[function(require,module,exports){
43341 "use strict";
43342 var __extends = (this && this.__extends) || (function () {
43343     var extendStatics = function (d, b) {
43344         extendStatics = Object.setPrototypeOf ||
43345             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43346             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
43347         return extendStatics(d, b);
43348     }
43349     return function (d, b) {
43350         extendStatics(d, b);
43351         function __() { this.constructor = d; }
43352         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43353     };
43354 })();
43355 Object.defineProperty(exports, "__esModule", { value: true });
43356 var THREE = require("three");
43357 var Component_1 = require("../../../Component");
43358 var OutlineRenderTagBase = /** @class */ (function (_super) {
43359     __extends(OutlineRenderTagBase, _super);
43360     function OutlineRenderTagBase(tag, transform) {
43361         var _this = _super.call(this, tag, transform) || this;
43362         _this._geometryChangedSubscription = _this._tag.geometry.changed$
43363             .subscribe(function () {
43364             _this._onGeometryChanged();
43365         });
43366         _this._changedSubscription = _this._tag.changed$
43367             .subscribe(function () {
43368             var glObjectsChanged = _this._onTagChanged();
43369             if (glObjectsChanged) {
43370                 _this._glObjectsChanged$.next(_this);
43371             }
43372         });
43373         return _this;
43374     }
43375     OutlineRenderTagBase.prototype.dispose = function () {
43376         this._changedSubscription.unsubscribe();
43377         this._geometryChangedSubscription.unsubscribe();
43378     };
43379     OutlineRenderTagBase.prototype._colorToCss = function (color) {
43380         return "#" + ("000000" + color.toString(16)).substr(-6);
43381     };
43382     OutlineRenderTagBase.prototype._createFill = function () {
43383         var triangles = this._getTriangles();
43384         var positions = new Float32Array(triangles);
43385         var geometry = new THREE.BufferGeometry();
43386         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
43387         geometry.computeBoundingSphere();
43388         var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true });
43389         this._updateFillMaterial(material);
43390         return new THREE.Mesh(geometry, material);
43391     };
43392     OutlineRenderTagBase.prototype._createLine = function (points3d) {
43393         var positions = this._getLinePositions(points3d);
43394         var geometry = new THREE.BufferGeometry();
43395         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
43396         geometry.computeBoundingSphere();
43397         var material = new THREE.LineBasicMaterial();
43398         this._updateLineBasicMaterial(material);
43399         var line = new THREE.Line(geometry, material);
43400         line.renderOrder = 1;
43401         return line;
43402     };
43403     OutlineRenderTagBase.prototype._createOutline = function () {
43404         return this._createLine(this._getPoints3d());
43405     };
43406     OutlineRenderTagBase.prototype._disposeFill = function () {
43407         if (this._fill == null) {
43408             return;
43409         }
43410         this._fill.geometry.dispose();
43411         this._fill.material.dispose();
43412         this._fill = null;
43413     };
43414     OutlineRenderTagBase.prototype._disposeOutline = function () {
43415         if (this._outline == null) {
43416             return;
43417         }
43418         this._outline.geometry.dispose();
43419         this._outline.material.dispose();
43420         this._outline = null;
43421     };
43422     OutlineRenderTagBase.prototype._getLinePositions = function (points3d) {
43423         var length = points3d.length;
43424         var positions = new Float32Array(length * 3);
43425         for (var i = 0; i < length; ++i) {
43426             var index = 3 * i;
43427             var position = points3d[i];
43428             positions[index + 0] = position[0];
43429             positions[index + 1] = position[1];
43430             positions[index + 2] = position[2];
43431         }
43432         return positions;
43433     };
43434     OutlineRenderTagBase.prototype._interact = function (operation, cursor, vertexIndex) {
43435         var _this = this;
43436         return function (e) {
43437             var offsetX = e.offsetX - e.target.offsetWidth / 2;
43438             var offsetY = e.offsetY - e.target.offsetHeight / 2;
43439             _this._interact$.next({
43440                 cursor: cursor,
43441                 offsetX: offsetX,
43442                 offsetY: offsetY,
43443                 operation: operation,
43444                 tag: _this._tag,
43445                 vertexIndex: vertexIndex,
43446             });
43447         };
43448     };
43449     OutlineRenderTagBase.prototype._updateFillGeometry = function () {
43450         var triangles = this._getTriangles();
43451         var positions = new Float32Array(triangles);
43452         var geometry = this._fill.geometry;
43453         var attribute = geometry.getAttribute("position");
43454         if (attribute.array.length === positions.length) {
43455             attribute.set(positions);
43456             attribute.needsUpdate = true;
43457         }
43458         else {
43459             geometry.removeAttribute("position");
43460             geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
43461         }
43462         geometry.computeBoundingSphere();
43463     };
43464     OutlineRenderTagBase.prototype._updateLine = function (line, points3d) {
43465         var positions = this._getLinePositions(points3d);
43466         var geometry = line.geometry;
43467         var attribute = geometry.getAttribute("position");
43468         attribute.set(positions);
43469         attribute.needsUpdate = true;
43470         geometry.computeBoundingSphere();
43471     };
43472     OutlineRenderTagBase.prototype._updateOulineGeometry = function () {
43473         this._updateLine(this._outline, this._getPoints3d());
43474     };
43475     return OutlineRenderTagBase;
43476 }(Component_1.RenderTag));
43477 exports.OutlineRenderTagBase = OutlineRenderTagBase;
43478 exports.default = OutlineRenderTagBase;
43479
43480
43481 },{"../../../Component":291,"three":242}],392:[function(require,module,exports){
43482 "use strict";
43483 var __extends = (this && this.__extends) || (function () {
43484     var extendStatics = function (d, b) {
43485         extendStatics = Object.setPrototypeOf ||
43486             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43487             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
43488         return extendStatics(d, b);
43489     }
43490     return function (d, b) {
43491         extendStatics(d, b);
43492         function __() { this.constructor = d; }
43493         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43494     };
43495 })();
43496 Object.defineProperty(exports, "__esModule", { value: true });
43497 var rxjs_1 = require("rxjs");
43498 var Component_1 = require("../../../Component");
43499 var Viewer_1 = require("../../../Viewer");
43500 /**
43501  * @class OutlineTag
43502  *
43503  * @classdesc Tag holding properties for visualizing a geometry outline.
43504  *
43505  * @example
43506  * ```
43507  * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]);
43508  * var tag = new Mapillary.TagComponent.OutlineTag(
43509  *     "id-1",
43510  *     geometry
43511  *     { editable: true, lineColor: 0xff0000 });
43512  *
43513  * tagComponent.add([tag]);
43514  * ```
43515  */
43516 var OutlineTag = /** @class */ (function (_super) {
43517     __extends(OutlineTag, _super);
43518     /**
43519      * Create an outline tag.
43520      *
43521      * @override
43522      * @constructor
43523      * @param {string} id - Unique identifier of the tag.
43524      * @param {VertexGeometry} geometry - Geometry defining vertices of tag.
43525      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
43526      * behavior of the outline tag.
43527      */
43528     function OutlineTag(id, geometry, options) {
43529         var _this = _super.call(this, id, geometry) || this;
43530         options = !!options ? options : {};
43531         var domain = options.domain != null && geometry instanceof Component_1.PolygonGeometry ?
43532             options.domain : Component_1.TagDomain.TwoDimensional;
43533         var twoDimensionalPolygon = _this._twoDimensionalPolygon(domain, geometry);
43534         _this._domain = domain;
43535         _this._editable = options.editable == null || twoDimensionalPolygon ? false : options.editable;
43536         _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
43537         _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
43538         _this._icon = options.icon === undefined ? null : options.icon;
43539         _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat;
43540         _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
43541         _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
43542         _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
43543         _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
43544         _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
43545         _this._text = options.text === undefined ? null : options.text;
43546         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
43547         _this._click$ = new rxjs_1.Subject();
43548         _this._click$
43549             .subscribe(function (t) {
43550             _this.fire(OutlineTag.click, _this);
43551         });
43552         return _this;
43553     }
43554     Object.defineProperty(OutlineTag.prototype, "click$", {
43555         /**
43556          * Click observable.
43557          *
43558          * @description An observable emitting the tag when the icon of the
43559          * tag has been clicked.
43560          *
43561          * @returns {Observable<Tag>}
43562          */
43563         get: function () {
43564             return this._click$;
43565         },
43566         enumerable: true,
43567         configurable: true
43568     });
43569     Object.defineProperty(OutlineTag.prototype, "domain", {
43570         /**
43571          * Get domain property.
43572          *
43573          * @description Readonly property that can only be set in constructor.
43574          *
43575          * @returns Value indicating the domain of the tag.
43576          */
43577         get: function () {
43578             return this._domain;
43579         },
43580         enumerable: true,
43581         configurable: true
43582     });
43583     Object.defineProperty(OutlineTag.prototype, "editable", {
43584         /**
43585          * Get editable property.
43586          * @returns {boolean} Value indicating if tag is editable.
43587          */
43588         get: function () {
43589             return this._editable;
43590         },
43591         /**
43592          * Set editable property.
43593          * @param {boolean}
43594          *
43595          * @fires Tag#changed
43596          */
43597         set: function (value) {
43598             if (this._twoDimensionalPolygon(this._domain, this._geometry)) {
43599                 return;
43600             }
43601             this._editable = value;
43602             this._notifyChanged$.next(this);
43603         },
43604         enumerable: true,
43605         configurable: true
43606     });
43607     Object.defineProperty(OutlineTag.prototype, "fillColor", {
43608         /**
43609          * Get fill color property.
43610          * @returns {number}
43611          */
43612         get: function () {
43613             return this._fillColor;
43614         },
43615         /**
43616          * Set fill color property.
43617          * @param {number}
43618          *
43619          * @fires Tag#changed
43620          */
43621         set: function (value) {
43622             this._fillColor = value;
43623             this._notifyChanged$.next(this);
43624         },
43625         enumerable: true,
43626         configurable: true
43627     });
43628     Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
43629         /**
43630          * Get fill opacity property.
43631          * @returns {number}
43632          */
43633         get: function () {
43634             return this._fillOpacity;
43635         },
43636         /**
43637          * Set fill opacity property.
43638          * @param {number}
43639          *
43640          * @fires Tag#changed
43641          */
43642         set: function (value) {
43643             this._fillOpacity = value;
43644             this._notifyChanged$.next(this);
43645         },
43646         enumerable: true,
43647         configurable: true
43648     });
43649     Object.defineProperty(OutlineTag.prototype, "geometry", {
43650         /** @inheritdoc */
43651         get: function () {
43652             return this._geometry;
43653         },
43654         enumerable: true,
43655         configurable: true
43656     });
43657     Object.defineProperty(OutlineTag.prototype, "icon", {
43658         /**
43659          * Get icon property.
43660          * @returns {string}
43661          */
43662         get: function () {
43663             return this._icon;
43664         },
43665         /**
43666          * Set icon property.
43667          * @param {string}
43668          *
43669          * @fires Tag#changed
43670          */
43671         set: function (value) {
43672             this._icon = value;
43673             this._notifyChanged$.next(this);
43674         },
43675         enumerable: true,
43676         configurable: true
43677     });
43678     Object.defineProperty(OutlineTag.prototype, "iconFloat", {
43679         /**
43680          * Get icon float property.
43681          * @returns {Alignment}
43682          */
43683         get: function () {
43684             return this._iconFloat;
43685         },
43686         /**
43687          * Set icon float property.
43688          * @param {Alignment}
43689          *
43690          * @fires Tag#changed
43691          */
43692         set: function (value) {
43693             this._iconFloat = value;
43694             this._notifyChanged$.next(this);
43695         },
43696         enumerable: true,
43697         configurable: true
43698     });
43699     Object.defineProperty(OutlineTag.prototype, "iconIndex", {
43700         /**
43701          * Get icon index property.
43702          * @returns {number}
43703          */
43704         get: function () {
43705             return this._iconIndex;
43706         },
43707         /**
43708          * Set icon index property.
43709          * @param {number}
43710          *
43711          * @fires Tag#changed
43712          */
43713         set: function (value) {
43714             this._iconIndex = value;
43715             this._notifyChanged$.next(this);
43716         },
43717         enumerable: true,
43718         configurable: true
43719     });
43720     Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
43721         /**
43722          * Get indicate vertices property.
43723          * @returns {boolean} Value indicating if vertices should be indicated
43724          * when tag is editable.
43725          */
43726         get: function () {
43727             return this._indicateVertices;
43728         },
43729         /**
43730          * Set indicate vertices property.
43731          * @param {boolean}
43732          *
43733          * @fires Tag#changed
43734          */
43735         set: function (value) {
43736             this._indicateVertices = value;
43737             this._notifyChanged$.next(this);
43738         },
43739         enumerable: true,
43740         configurable: true
43741     });
43742     Object.defineProperty(OutlineTag.prototype, "lineColor", {
43743         /**
43744          * Get line color property.
43745          * @returns {number}
43746          */
43747         get: function () {
43748             return this._lineColor;
43749         },
43750         /**
43751          * Set line color property.
43752          * @param {number}
43753          *
43754          * @fires Tag#changed
43755          */
43756         set: function (value) {
43757             this._lineColor = value;
43758             this._notifyChanged$.next(this);
43759         },
43760         enumerable: true,
43761         configurable: true
43762     });
43763     Object.defineProperty(OutlineTag.prototype, "lineOpacity", {
43764         /**
43765          * Get line opacity property.
43766          * @returns {number}
43767          */
43768         get: function () {
43769             return this._lineOpacity;
43770         },
43771         /**
43772          * Set line opacity property.
43773          * @param {number}
43774          *
43775          * @fires Tag#changed
43776          */
43777         set: function (value) {
43778             this._lineOpacity = value;
43779             this._notifyChanged$.next(this);
43780         },
43781         enumerable: true,
43782         configurable: true
43783     });
43784     Object.defineProperty(OutlineTag.prototype, "lineWidth", {
43785         /**
43786          * Get line width property.
43787          * @returns {number}
43788          */
43789         get: function () {
43790             return this._lineWidth;
43791         },
43792         /**
43793          * Set line width property.
43794          * @param {number}
43795          *
43796          * @fires Tag#changed
43797          */
43798         set: function (value) {
43799             this._lineWidth = value;
43800             this._notifyChanged$.next(this);
43801         },
43802         enumerable: true,
43803         configurable: true
43804     });
43805     Object.defineProperty(OutlineTag.prototype, "text", {
43806         /**
43807          * Get text property.
43808          * @returns {string}
43809          */
43810         get: function () {
43811             return this._text;
43812         },
43813         /**
43814          * Set text property.
43815          * @param {string}
43816          *
43817          * @fires Tag#changed
43818          */
43819         set: function (value) {
43820             this._text = value;
43821             this._notifyChanged$.next(this);
43822         },
43823         enumerable: true,
43824         configurable: true
43825     });
43826     Object.defineProperty(OutlineTag.prototype, "textColor", {
43827         /**
43828          * Get text color property.
43829          * @returns {number}
43830          */
43831         get: function () {
43832             return this._textColor;
43833         },
43834         /**
43835          * Set text color property.
43836          * @param {number}
43837          *
43838          * @fires Tag#changed
43839          */
43840         set: function (value) {
43841             this._textColor = value;
43842             this._notifyChanged$.next(this);
43843         },
43844         enumerable: true,
43845         configurable: true
43846     });
43847     /**
43848      * Set options for tag.
43849      *
43850      * @description Sets all the option properties provided and keeps
43851      * the rest of the values as is.
43852      *
43853      * @param {IOutlineTagOptions} options - Outline tag options
43854      *
43855      * @fires {Tag#changed}
43856      */
43857     OutlineTag.prototype.setOptions = function (options) {
43858         var twoDimensionalPolygon = this._twoDimensionalPolygon(this._domain, this._geometry);
43859         this._editable = twoDimensionalPolygon || options.editable == null ? this._editable : options.editable;
43860         this._icon = options.icon === undefined ? this._icon : options.icon;
43861         this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
43862         this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
43863         this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
43864         this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
43865         this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
43866         this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
43867         this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
43868         this._text = options.text === undefined ? this._text : options.text;
43869         this._textColor = options.textColor == null ? this._textColor : options.textColor;
43870         this._notifyChanged$.next(this);
43871     };
43872     OutlineTag.prototype._twoDimensionalPolygon = function (domain, geometry) {
43873         return domain !== Component_1.TagDomain.ThreeDimensional && geometry instanceof Component_1.PolygonGeometry;
43874     };
43875     /**
43876      * Event fired when the icon of the outline tag is clicked.
43877      *
43878      * @event OutlineTag#click
43879      * @type {OutlineTag} The tag instance that was clicked.
43880      */
43881     OutlineTag.click = "click";
43882     return OutlineTag;
43883 }(Component_1.Tag));
43884 exports.OutlineTag = OutlineTag;
43885 exports.default = OutlineTag;
43886
43887 },{"../../../Component":291,"../../../Viewer":302,"rxjs":43}],393:[function(require,module,exports){
43888 "use strict";
43889 Object.defineProperty(exports, "__esModule", { value: true });
43890 var rxjs_1 = require("rxjs");
43891 var Geo_1 = require("../../../Geo");
43892 var RenderTag = /** @class */ (function () {
43893     function RenderTag(tag, transform, viewportCoords) {
43894         this._tag = tag;
43895         this._transform = transform;
43896         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
43897         this._glObjectsChanged$ = new rxjs_1.Subject();
43898         this._interact$ = new rxjs_1.Subject();
43899     }
43900     Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
43901         get: function () {
43902             return this._glObjectsChanged$;
43903         },
43904         enumerable: true,
43905         configurable: true
43906     });
43907     Object.defineProperty(RenderTag.prototype, "interact$", {
43908         get: function () {
43909             return this._interact$;
43910         },
43911         enumerable: true,
43912         configurable: true
43913     });
43914     Object.defineProperty(RenderTag.prototype, "tag", {
43915         get: function () {
43916             return this._tag;
43917         },
43918         enumerable: true,
43919         configurable: true
43920     });
43921     return RenderTag;
43922 }());
43923 exports.RenderTag = RenderTag;
43924 exports.default = RenderTag;
43925
43926 },{"../../../Geo":294,"rxjs":43}],394:[function(require,module,exports){
43927 "use strict";
43928 var __extends = (this && this.__extends) || (function () {
43929     var extendStatics = function (d, b) {
43930         extendStatics = Object.setPrototypeOf ||
43931             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43932             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
43933         return extendStatics(d, b);
43934     }
43935     return function (d, b) {
43936         extendStatics(d, b);
43937         function __() { this.constructor = d; }
43938         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43939     };
43940 })();
43941 Object.defineProperty(exports, "__esModule", { value: true });
43942 var vd = require("virtual-dom");
43943 var Component_1 = require("../../../Component");
43944 var Viewer_1 = require("../../../Viewer");
43945 /**
43946  * @class SpotRenderTag
43947  * @classdesc Tag visualizing the properties of a SpotTag.
43948  */
43949 var SpotRenderTag = /** @class */ (function (_super) {
43950     __extends(SpotRenderTag, _super);
43951     function SpotRenderTag() {
43952         return _super !== null && _super.apply(this, arguments) || this;
43953     }
43954     SpotRenderTag.prototype.dispose = function () { };
43955     SpotRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
43956         var _this = this;
43957         var tag = this._tag;
43958         var container = {
43959             offsetHeight: size.height, offsetWidth: size.width,
43960         };
43961         var vNodes = [];
43962         var _a = tag.geometry.getCentroid2d(), centroidBasicX = _a[0], centroidBasicY = _a[1];
43963         var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
43964         if (centroidCanvas != null) {
43965             var interactNone = function (e) {
43966                 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: tag });
43967             };
43968             var canvasX = Math.round(centroidCanvas[0]);
43969             var canvasY = Math.round(centroidCanvas[1]);
43970             if (tag.icon != null) {
43971                 if (atlas.loaded) {
43972                     var sprite = atlas.getDOMSprite(tag.icon, Viewer_1.Alignment.Bottom);
43973                     var iconTransform = "translate(" + canvasX + "px," + (canvasY + 8) + "px)";
43974                     var properties = {
43975                         onmousedown: interactNone,
43976                         style: {
43977                             pointerEvents: "all",
43978                             transform: iconTransform,
43979                         },
43980                     };
43981                     vNodes.push(vd.h("div", properties, [sprite]));
43982                 }
43983             }
43984             else if (tag.text != null) {
43985                 var textTransform = "translate(-50%,0%) translate(" + canvasX + "px," + (canvasY + 8) + "px)";
43986                 var properties = {
43987                     onmousedown: interactNone,
43988                     style: {
43989                         color: this._colorToCss(tag.textColor),
43990                         transform: textTransform,
43991                     },
43992                     textContent: tag.text,
43993                 };
43994                 vNodes.push(vd.h("span.TagSymbol", properties, []));
43995             }
43996             var interact = this._interact(Component_1.TagOperation.Centroid, tag, "move");
43997             var background = this._colorToCss(tag.color);
43998             var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
43999             if (tag.editable) {
44000                 var interactorProperties = {
44001                     onmousedown: interact,
44002                     style: {
44003                         background: background,
44004                         transform: transform,
44005                     },
44006                 };
44007                 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
44008             }
44009             var pointProperties = {
44010                 style: {
44011                     background: background,
44012                     transform: transform,
44013                 },
44014             };
44015             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
44016         }
44017         return vNodes;
44018     };
44019     SpotRenderTag.prototype.getGLObjects = function () { return []; };
44020     SpotRenderTag.prototype.getRetrievableObjects = function () { return []; };
44021     SpotRenderTag.prototype._colorToCss = function (color) {
44022         return "#" + ("000000" + color.toString(16)).substr(-6);
44023     };
44024     SpotRenderTag.prototype._interact = function (operation, tag, cursor, vertexIndex) {
44025         var _this = this;
44026         return function (e) {
44027             var offsetX = e.offsetX - e.target.offsetWidth / 2;
44028             var offsetY = e.offsetY - e.target.offsetHeight / 2;
44029             _this._interact$.next({
44030                 cursor: cursor,
44031                 offsetX: offsetX,
44032                 offsetY: offsetY,
44033                 operation: operation,
44034                 tag: tag,
44035                 vertexIndex: vertexIndex,
44036             });
44037         };
44038     };
44039     return SpotRenderTag;
44040 }(Component_1.RenderTag));
44041 exports.SpotRenderTag = SpotRenderTag;
44042
44043
44044 },{"../../../Component":291,"../../../Viewer":302,"virtual-dom":247}],395:[function(require,module,exports){
44045 "use strict";
44046 var __extends = (this && this.__extends) || (function () {
44047     var extendStatics = function (d, b) {
44048         extendStatics = Object.setPrototypeOf ||
44049             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
44050             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
44051         return extendStatics(d, b);
44052     }
44053     return function (d, b) {
44054         extendStatics(d, b);
44055         function __() { this.constructor = d; }
44056         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
44057     };
44058 })();
44059 Object.defineProperty(exports, "__esModule", { value: true });
44060 var Component_1 = require("../../../Component");
44061 /**
44062  * @class SpotTag
44063  *
44064  * @classdesc Tag holding properties for visualizing the centroid of a geometry.
44065  *
44066  * @example
44067  * ```
44068  * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]);
44069  * var tag = new Mapillary.TagComponent.SpotTag(
44070  *     "id-1",
44071  *     geometry
44072  *     { editable: true, color: 0xff0000 });
44073  *
44074  * tagComponent.add([tag]);
44075  * ```
44076  */
44077 var SpotTag = /** @class */ (function (_super) {
44078     __extends(SpotTag, _super);
44079     /**
44080      * Create a spot tag.
44081      *
44082      * @override
44083      * @constructor
44084      * @param {string} id
44085      * @param {Geometry} geometry
44086      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
44087      * behavior of the spot tag.
44088      */
44089     function SpotTag(id, geometry, options) {
44090         var _this = _super.call(this, id, geometry) || this;
44091         options = !!options ? options : {};
44092         _this._color = options.color == null ? 0xFFFFFF : options.color;
44093         _this._editable = options.editable == null ? false : options.editable;
44094         _this._icon = options.icon === undefined ? null : options.icon;
44095         _this._text = options.text === undefined ? null : options.text;
44096         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
44097         return _this;
44098     }
44099     Object.defineProperty(SpotTag.prototype, "color", {
44100         /**
44101          * Get color property.
44102          * @returns {number} The color of the spot as a hexagonal number;
44103          */
44104         get: function () {
44105             return this._color;
44106         },
44107         /**
44108          * Set color property.
44109          * @param {number}
44110          *
44111          * @fires Tag#changed
44112          */
44113         set: function (value) {
44114             this._color = value;
44115             this._notifyChanged$.next(this);
44116         },
44117         enumerable: true,
44118         configurable: true
44119     });
44120     Object.defineProperty(SpotTag.prototype, "editable", {
44121         /**
44122          * Get editable property.
44123          * @returns {boolean} Value indicating if tag is editable.
44124          */
44125         get: function () {
44126             return this._editable;
44127         },
44128         /**
44129          * Set editable property.
44130          * @param {boolean}
44131          *
44132          * @fires Tag#changed
44133          */
44134         set: function (value) {
44135             this._editable = value;
44136             this._notifyChanged$.next(this);
44137         },
44138         enumerable: true,
44139         configurable: true
44140     });
44141     Object.defineProperty(SpotTag.prototype, "icon", {
44142         /**
44143          * Get icon property.
44144          * @returns {string}
44145          */
44146         get: function () {
44147             return this._icon;
44148         },
44149         /**
44150          * Set icon property.
44151          * @param {string}
44152          *
44153          * @fires Tag#changed
44154          */
44155         set: function (value) {
44156             this._icon = value;
44157             this._notifyChanged$.next(this);
44158         },
44159         enumerable: true,
44160         configurable: true
44161     });
44162     Object.defineProperty(SpotTag.prototype, "text", {
44163         /**
44164          * Get text property.
44165          * @returns {string}
44166          */
44167         get: function () {
44168             return this._text;
44169         },
44170         /**
44171          * Set text property.
44172          * @param {string}
44173          *
44174          * @fires Tag#changed
44175          */
44176         set: function (value) {
44177             this._text = value;
44178             this._notifyChanged$.next(this);
44179         },
44180         enumerable: true,
44181         configurable: true
44182     });
44183     Object.defineProperty(SpotTag.prototype, "textColor", {
44184         /**
44185          * Get text color property.
44186          * @returns {number}
44187          */
44188         get: function () {
44189             return this._textColor;
44190         },
44191         /**
44192          * Set text color property.
44193          * @param {number}
44194          *
44195          * @fires Tag#changed
44196          */
44197         set: function (value) {
44198             this._textColor = value;
44199             this._notifyChanged$.next(this);
44200         },
44201         enumerable: true,
44202         configurable: true
44203     });
44204     /**
44205      * Set options for tag.
44206      *
44207      * @description Sets all the option properties provided and keps
44208      * the rest of the values as is.
44209      *
44210      * @param {ISpotTagOptions} options - Spot tag options
44211      *
44212      * @fires {Tag#changed}
44213      */
44214     SpotTag.prototype.setOptions = function (options) {
44215         this._color = options.color == null ? this._color : options.color;
44216         this._editable = options.editable == null ? this._editable : options.editable;
44217         this._icon = options.icon === undefined ? this._icon : options.icon;
44218         this._text = options.text === undefined ? this._text : options.text;
44219         this._textColor = options.textColor == null ? this._textColor : options.textColor;
44220         this._notifyChanged$.next(this);
44221     };
44222     return SpotTag;
44223 }(Component_1.Tag));
44224 exports.SpotTag = SpotTag;
44225 exports.default = SpotTag;
44226
44227 },{"../../../Component":291}],396:[function(require,module,exports){
44228 "use strict";
44229 var __extends = (this && this.__extends) || (function () {
44230     var extendStatics = function (d, b) {
44231         extendStatics = Object.setPrototypeOf ||
44232             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
44233             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
44234         return extendStatics(d, b);
44235     }
44236     return function (d, b) {
44237         extendStatics(d, b);
44238         function __() { this.constructor = d; }
44239         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
44240     };
44241 })();
44242 Object.defineProperty(exports, "__esModule", { value: true });
44243 var operators_1 = require("rxjs/operators");
44244 var rxjs_1 = require("rxjs");
44245 var Utils_1 = require("../../../Utils");
44246 /**
44247  * @class Tag
44248  * @abstract
44249  * @classdesc Abstract class representing the basic functionality of for a tag.
44250  */
44251 var Tag = /** @class */ (function (_super) {
44252     __extends(Tag, _super);
44253     /**
44254      * Create a tag.
44255      *
44256      * @constructor
44257      * @param {string} id
44258      * @param {Geometry} geometry
44259      */
44260     function Tag(id, geometry) {
44261         var _this = _super.call(this) || this;
44262         _this._id = id;
44263         _this._geometry = geometry;
44264         _this._notifyChanged$ = new rxjs_1.Subject();
44265         _this._notifyChanged$
44266             .subscribe(function (t) {
44267             _this.fire(Tag.changed, _this);
44268         });
44269         _this._geometry.changed$
44270             .subscribe(function (g) {
44271             _this.fire(Tag.geometrychanged, _this);
44272         });
44273         return _this;
44274     }
44275     Object.defineProperty(Tag.prototype, "id", {
44276         /**
44277          * Get id property.
44278          * @returns {string}
44279          */
44280         get: function () {
44281             return this._id;
44282         },
44283         enumerable: true,
44284         configurable: true
44285     });
44286     Object.defineProperty(Tag.prototype, "geometry", {
44287         /**
44288          * Get geometry property.
44289          * @returns {Geometry} The geometry of the tag.
44290          */
44291         get: function () {
44292             return this._geometry;
44293         },
44294         enumerable: true,
44295         configurable: true
44296     });
44297     Object.defineProperty(Tag.prototype, "changed$", {
44298         /**
44299          * Get changed observable.
44300          * @returns {Observable<Tag>}
44301          * @ignore
44302          */
44303         get: function () {
44304             return this._notifyChanged$;
44305         },
44306         enumerable: true,
44307         configurable: true
44308     });
44309     Object.defineProperty(Tag.prototype, "geometryChanged$", {
44310         /**
44311          * Get geometry changed observable.
44312          * @returns {Observable<Tag>}
44313          * @ignore
44314          */
44315         get: function () {
44316             var _this = this;
44317             return this._geometry.changed$.pipe(operators_1.map(function (geometry) {
44318                 return _this;
44319             }), operators_1.share());
44320         },
44321         enumerable: true,
44322         configurable: true
44323     });
44324     /**
44325      * Event fired when a property related to the visual appearance of the
44326      * tag has changed.
44327      *
44328      * @event Tag#changed
44329      * @type {Tag} The tag instance that has changed.
44330      */
44331     Tag.changed = "changed";
44332     /**
44333      * Event fired when the geometry of the tag has changed.
44334      *
44335      * @event Tag#geometrychanged
44336      * @type {Tag} The tag instance whose geometry has changed.
44337      */
44338     Tag.geometrychanged = "geometrychanged";
44339     return Tag;
44340 }(Utils_1.EventEmitter));
44341 exports.Tag = Tag;
44342 exports.default = Tag;
44343
44344 },{"../../../Utils":301,"rxjs":43,"rxjs/operators":241}],397:[function(require,module,exports){
44345 "use strict";
44346 Object.defineProperty(exports, "__esModule", { value: true });
44347 /**
44348  * Enumeration for tag domains.
44349  * @enum {number}
44350  * @readonly
44351  * @description Defines where lines between two vertices are treated
44352  * as straight.
44353  *
44354  * Only applicable for polygons. For rectangles lines between
44355  * vertices are always treated as straight in the distorted 2D
44356  * projection and bended in the undistorted 3D space.
44357  */
44358 var TagDomain;
44359 (function (TagDomain) {
44360     /**
44361      * Treats lines between two vertices as straight in the
44362      * distorted 2D projection, i.e. on the image. If the image
44363      * is distorted this will result in bended lines when rendered
44364      * in the undistorted 3D space.
44365      */
44366     TagDomain[TagDomain["TwoDimensional"] = 0] = "TwoDimensional";
44367     /**
44368      * Treats lines as straight in the undistorted 3D space. If the
44369      * image is distorted this will result in bended lines when rendered
44370      * on the distorted 2D projection of the image.
44371      */
44372     TagDomain[TagDomain["ThreeDimensional"] = 1] = "ThreeDimensional";
44373 })(TagDomain = exports.TagDomain || (exports.TagDomain = {}));
44374 exports.default = TagDomain;
44375
44376 },{}],398:[function(require,module,exports){
44377 "use strict";
44378 Object.defineProperty(exports, "__esModule", { value: true });
44379 /**
44380  * Enumeration for component size.
44381  * @enum {number}
44382  * @readonly
44383  * @description May be used by a component to allow for resizing
44384  * of the UI elements rendered by the component.
44385  */
44386 var ComponentSize;
44387 (function (ComponentSize) {
44388     /**
44389      * Automatic size. The size of the elements will automatically
44390      * change at a predefined threshold.
44391      */
44392     ComponentSize[ComponentSize["Automatic"] = 0] = "Automatic";
44393     /**
44394      * Large size. The size of the elements will be fixed until another
44395      * component size is configured.
44396      */
44397     ComponentSize[ComponentSize["Large"] = 1] = "Large";
44398     /**
44399      * Small size. The size of the elements will be fixed until another
44400      * component size is configured.
44401      */
44402     ComponentSize[ComponentSize["Small"] = 2] = "Small";
44403 })(ComponentSize = exports.ComponentSize || (exports.ComponentSize = {}));
44404 exports.default = ComponentSize;
44405
44406 },{}],399:[function(require,module,exports){
44407 "use strict";
44408 Object.defineProperty(exports, "__esModule", { value: true });
44409 var HandlerBase = /** @class */ (function () {
44410     /** @ignore */
44411     function HandlerBase(component, container, navigator) {
44412         this._component = component;
44413         this._container = container;
44414         this._navigator = navigator;
44415         this._enabled = false;
44416     }
44417     Object.defineProperty(HandlerBase.prototype, "isEnabled", {
44418         /**
44419          * Returns a Boolean indicating whether the interaction is enabled.
44420          *
44421          * @returns {boolean} `true` if the interaction is enabled.
44422          */
44423         get: function () {
44424             return this._enabled;
44425         },
44426         enumerable: true,
44427         configurable: true
44428     });
44429     /**
44430      * Enables the interaction.
44431      *
44432      * @example ```<component-name>.<handler-name>.enable();```
44433      */
44434     HandlerBase.prototype.enable = function () {
44435         if (this._enabled || !this._component.activated) {
44436             return;
44437         }
44438         this._enable();
44439         this._enabled = true;
44440         this._component.configure(this._getConfiguration(true));
44441     };
44442     /**
44443      * Disables the interaction.
44444      *
44445      * @example ```<component-name>.<handler-name>.disable();```
44446      */
44447     HandlerBase.prototype.disable = function () {
44448         if (!this._enabled) {
44449             return;
44450         }
44451         this._disable();
44452         this._enabled = false;
44453         if (this._component.activated) {
44454             this._component.configure(this._getConfiguration(false));
44455         }
44456     };
44457     return HandlerBase;
44458 }());
44459 exports.HandlerBase = HandlerBase;
44460 exports.default = HandlerBase;
44461
44462 },{}],400:[function(require,module,exports){
44463 "use strict";
44464 Object.defineProperty(exports, "__esModule", { value: true });
44465 var THREE = require("three");
44466 var Component_1 = require("../../Component");
44467 var MeshFactory = /** @class */ (function () {
44468     function MeshFactory(imagePlaneDepth, imageSphereRadius) {
44469         this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
44470         this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
44471     }
44472     MeshFactory.prototype.createMesh = function (node, transform) {
44473         if (node.pano) {
44474             return this._createImageSphere(node, transform);
44475         }
44476         else if (transform.cameraProjection === "fisheye") {
44477             return this._createImagePlaneFisheye(node, transform);
44478         }
44479         else {
44480             return this._createImagePlane(node, transform);
44481         }
44482     };
44483     MeshFactory.prototype.createFlatMesh = function (node, transform, basicX0, basicX1, basicY0, basicY1) {
44484         var texture = this._createTexture(node.image);
44485         var materialParameters = this._createDistortedPlaneMaterialParameters(transform, texture);
44486         var material = new THREE.ShaderMaterial(materialParameters);
44487         var geometry = this._getFlatImagePlaneGeoFromBasic(transform, basicX0, basicX1, basicY0, basicY1);
44488         return new THREE.Mesh(geometry, material);
44489     };
44490     MeshFactory.prototype.createCurtainMesh = function (node, transform) {
44491         if (node.pano && !node.fullPano) {
44492             throw new Error("Cropped panoramas cannot have curtain.");
44493         }
44494         if (node.pano) {
44495             return this._createSphereCurtainMesh(node, transform);
44496         }
44497         else if (transform.cameraProjection === "fisheye") {
44498             return this._createCurtainMeshFisheye(node, transform);
44499         }
44500         else {
44501             return this._createCurtainMesh(node, transform);
44502         }
44503     };
44504     MeshFactory.prototype.createDistortedCurtainMesh = function (node, transform) {
44505         if (node.pano) {
44506             throw new Error("Cropped panoramas cannot have curtain.");
44507         }
44508         return this._createDistortedCurtainMesh(node, transform);
44509     };
44510     MeshFactory.prototype._createCurtainMesh = function (node, transform) {
44511         var texture = this._createTexture(node.image);
44512         var materialParameters = this._createCurtainPlaneMaterialParameters(transform, texture);
44513         var material = new THREE.ShaderMaterial(materialParameters);
44514         var geometry = this._useMesh(transform, node) ?
44515             this._getImagePlaneGeo(transform, node) :
44516             this._getRegularFlatImagePlaneGeo(transform);
44517         return new THREE.Mesh(geometry, material);
44518     };
44519     MeshFactory.prototype._createCurtainMeshFisheye = function (node, transform) {
44520         var texture = this._createTexture(node.image);
44521         var materialParameters = this._createCurtainPlaneMaterialParametersFisheye(transform, texture);
44522         var material = new THREE.ShaderMaterial(materialParameters);
44523         var geometry = this._useMesh(transform, node) ?
44524             this._getImagePlaneGeoFisheye(transform, node) :
44525             this._getRegularFlatImagePlaneGeo(transform);
44526         return new THREE.Mesh(geometry, material);
44527     };
44528     MeshFactory.prototype._createDistortedCurtainMesh = function (node, transform) {
44529         var texture = this._createTexture(node.image);
44530         var materialParameters = this._createDistortedCurtainPlaneMaterialParameters(transform, texture);
44531         var material = new THREE.ShaderMaterial(materialParameters);
44532         var geometry = this._getRegularFlatImagePlaneGeo(transform);
44533         return new THREE.Mesh(geometry, material);
44534     };
44535     MeshFactory.prototype._createSphereCurtainMesh = function (node, transform) {
44536         var texture = this._createTexture(node.image);
44537         var materialParameters = this._createCurtainSphereMaterialParameters(transform, texture);
44538         var material = new THREE.ShaderMaterial(materialParameters);
44539         return this._useMesh(transform, node) ?
44540             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
44541             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
44542     };
44543     MeshFactory.prototype._createImageSphere = function (node, transform) {
44544         var texture = this._createTexture(node.image);
44545         var materialParameters = this._createSphereMaterialParameters(transform, texture);
44546         var material = new THREE.ShaderMaterial(materialParameters);
44547         var mesh = this._useMesh(transform, node) ?
44548             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
44549             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
44550         return mesh;
44551     };
44552     MeshFactory.prototype._createImagePlane = function (node, transform) {
44553         var texture = this._createTexture(node.image);
44554         var materialParameters = this._createPlaneMaterialParameters(transform, texture);
44555         var material = new THREE.ShaderMaterial(materialParameters);
44556         var geometry = this._useMesh(transform, node) ?
44557             this._getImagePlaneGeo(transform, node) :
44558             this._getRegularFlatImagePlaneGeo(transform);
44559         return new THREE.Mesh(geometry, material);
44560     };
44561     MeshFactory.prototype._createImagePlaneFisheye = function (node, transform) {
44562         var texture = this._createTexture(node.image);
44563         var materialParameters = this._createPlaneMaterialParametersFisheye(transform, texture);
44564         var material = new THREE.ShaderMaterial(materialParameters);
44565         var geometry = this._useMesh(transform, node) ?
44566             this._getImagePlaneGeoFisheye(transform, node) :
44567             this._getRegularFlatImagePlaneGeoFisheye(transform);
44568         return new THREE.Mesh(geometry, material);
44569     };
44570     MeshFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
44571         var gpano = transform.gpano;
44572         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
44573         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
44574         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
44575         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
44576         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
44577         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
44578         var materialParameters = {
44579             depthWrite: false,
44580             fragmentShader: Component_1.Shaders.equirectangular.fragment,
44581             side: THREE.DoubleSide,
44582             transparent: true,
44583             uniforms: {
44584                 opacity: {
44585                     type: "f",
44586                     value: 1,
44587                 },
44588                 phiLength: {
44589                     type: "f",
44590                     value: phiLength,
44591                 },
44592                 phiShift: {
44593                     type: "f",
44594                     value: phiShift,
44595                 },
44596                 projectorMat: {
44597                     type: "m4",
44598                     value: transform.rt,
44599                 },
44600                 projectorTex: {
44601                     type: "t",
44602                     value: texture,
44603                 },
44604                 thetaLength: {
44605                     type: "f",
44606                     value: thetaLength,
44607                 },
44608                 thetaShift: {
44609                     type: "f",
44610                     value: thetaShift,
44611                 },
44612             },
44613             vertexShader: Component_1.Shaders.equirectangular.vertex,
44614         };
44615         return materialParameters;
44616     };
44617     MeshFactory.prototype._createCurtainSphereMaterialParameters = function (transform, texture) {
44618         var gpano = transform.gpano;
44619         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
44620         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
44621         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
44622         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
44623         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
44624         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
44625         var materialParameters = {
44626             depthWrite: false,
44627             fragmentShader: Component_1.Shaders.equirectangularCurtain.fragment,
44628             side: THREE.DoubleSide,
44629             transparent: true,
44630             uniforms: {
44631                 curtain: {
44632                     type: "f",
44633                     value: 1,
44634                 },
44635                 opacity: {
44636                     type: "f",
44637                     value: 1,
44638                 },
44639                 phiLength: {
44640                     type: "f",
44641                     value: phiLength,
44642                 },
44643                 phiShift: {
44644                     type: "f",
44645                     value: phiShift,
44646                 },
44647                 projectorMat: {
44648                     type: "m4",
44649                     value: transform.rt,
44650                 },
44651                 projectorTex: {
44652                     type: "t",
44653                     value: texture,
44654                 },
44655                 thetaLength: {
44656                     type: "f",
44657                     value: thetaLength,
44658                 },
44659                 thetaShift: {
44660                     type: "f",
44661                     value: thetaShift,
44662                 },
44663             },
44664             vertexShader: Component_1.Shaders.equirectangularCurtain.vertex,
44665         };
44666         return materialParameters;
44667     };
44668     MeshFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
44669         var materialParameters = {
44670             depthWrite: false,
44671             fragmentShader: Component_1.Shaders.perspective.fragment,
44672             side: THREE.DoubleSide,
44673             transparent: true,
44674             uniforms: {
44675                 focal: {
44676                     type: "f",
44677                     value: transform.focal,
44678                 },
44679                 k1: {
44680                     type: "f",
44681                     value: transform.ck1,
44682                 },
44683                 k2: {
44684                     type: "f",
44685                     value: transform.ck2,
44686                 },
44687                 opacity: {
44688                     type: "f",
44689                     value: 1,
44690                 },
44691                 projectorMat: {
44692                     type: "m4",
44693                     value: transform.basicRt,
44694                 },
44695                 projectorTex: {
44696                     type: "t",
44697                     value: texture,
44698                 },
44699                 radial_peak: {
44700                     type: "f",
44701                     value: !!transform.radialPeak ? transform.radialPeak : 0,
44702                 },
44703                 scale_x: {
44704                     type: "f",
44705                     value: Math.max(transform.basicHeight, transform.basicWidth) / transform.basicWidth,
44706                 },
44707                 scale_y: {
44708                     type: "f",
44709                     value: Math.max(transform.basicWidth, transform.basicHeight) / transform.basicHeight,
44710                 },
44711             },
44712             vertexShader: Component_1.Shaders.perspective.vertex,
44713         };
44714         return materialParameters;
44715     };
44716     MeshFactory.prototype._createPlaneMaterialParametersFisheye = function (transform, texture) {
44717         var materialParameters = {
44718             depthWrite: false,
44719             fragmentShader: Component_1.Shaders.fisheye.fragment,
44720             side: THREE.DoubleSide,
44721             transparent: true,
44722             uniforms: {
44723                 focal: {
44724                     type: "f",
44725                     value: transform.focal,
44726                 },
44727                 k1: {
44728                     type: "f",
44729                     value: transform.ck1,
44730                 },
44731                 k2: {
44732                     type: "f",
44733                     value: transform.ck2,
44734                 },
44735                 opacity: {
44736                     type: "f",
44737                     value: 1,
44738                 },
44739                 projectorMat: {
44740                     type: "m4",
44741                     value: transform.basicRt,
44742                 },
44743                 projectorTex: {
44744                     type: "t",
44745                     value: texture,
44746                 },
44747                 radial_peak: {
44748                     type: "f",
44749                     value: !!transform.radialPeak ? transform.radialPeak : 0,
44750                 },
44751                 scale_x: {
44752                     type: "f",
44753                     value: Math.max(transform.basicHeight, transform.basicWidth) / transform.basicWidth,
44754                 },
44755                 scale_y: {
44756                     type: "f",
44757                     value: Math.max(transform.basicWidth, transform.basicHeight) / transform.basicHeight,
44758                 },
44759             },
44760             vertexShader: Component_1.Shaders.fisheye.vertex,
44761         };
44762         return materialParameters;
44763     };
44764     MeshFactory.prototype._createCurtainPlaneMaterialParametersFisheye = function (transform, texture) {
44765         var materialParameters = {
44766             depthWrite: false,
44767             fragmentShader: Component_1.Shaders.fisheyeCurtain.fragment,
44768             side: THREE.DoubleSide,
44769             transparent: true,
44770             uniforms: {
44771                 curtain: {
44772                     type: "f",
44773                     value: 1,
44774                 },
44775                 focal: {
44776                     type: "f",
44777                     value: transform.focal,
44778                 },
44779                 k1: {
44780                     type: "f",
44781                     value: transform.ck1,
44782                 },
44783                 k2: {
44784                     type: "f",
44785                     value: transform.ck2,
44786                 },
44787                 opacity: {
44788                     type: "f",
44789                     value: 1,
44790                 },
44791                 projectorMat: {
44792                     type: "m4",
44793                     value: transform.basicRt,
44794                 },
44795                 projectorTex: {
44796                     type: "t",
44797                     value: texture,
44798                 },
44799                 radial_peak: {
44800                     type: "f",
44801                     value: !!transform.radialPeak ? transform.radialPeak : 0,
44802                 },
44803                 scale_x: {
44804                     type: "f",
44805                     value: Math.max(transform.basicHeight, transform.basicWidth) / transform.basicWidth,
44806                 },
44807                 scale_y: {
44808                     type: "f",
44809                     value: Math.max(transform.basicWidth, transform.basicHeight) / transform.basicHeight,
44810                 },
44811             },
44812             vertexShader: Component_1.Shaders.fisheyeCurtain.vertex,
44813         };
44814         return materialParameters;
44815     };
44816     MeshFactory.prototype._createCurtainPlaneMaterialParameters = function (transform, texture) {
44817         var materialParameters = {
44818             depthWrite: false,
44819             fragmentShader: Component_1.Shaders.perspectiveCurtain.fragment,
44820             side: THREE.DoubleSide,
44821             transparent: true,
44822             uniforms: {
44823                 curtain: {
44824                     type: "f",
44825                     value: 1,
44826                 },
44827                 focal: {
44828                     type: "f",
44829                     value: transform.focal,
44830                 },
44831                 k1: {
44832                     type: "f",
44833                     value: transform.ck1,
44834                 },
44835                 k2: {
44836                     type: "f",
44837                     value: transform.ck2,
44838                 },
44839                 opacity: {
44840                     type: "f",
44841                     value: 1,
44842                 },
44843                 projectorMat: {
44844                     type: "m4",
44845                     value: transform.basicRt,
44846                 },
44847                 projectorTex: {
44848                     type: "t",
44849                     value: texture,
44850                 },
44851                 radial_peak: {
44852                     type: "f",
44853                     value: !!transform.radialPeak ? transform.radialPeak : 0,
44854                 },
44855                 scale_x: {
44856                     type: "f",
44857                     value: Math.max(transform.basicHeight, transform.basicWidth) / transform.basicWidth,
44858                 },
44859                 scale_y: {
44860                     type: "f",
44861                     value: Math.max(transform.basicWidth, transform.basicHeight) / transform.basicHeight,
44862                 },
44863             },
44864             vertexShader: Component_1.Shaders.perspectiveCurtain.vertex,
44865         };
44866         return materialParameters;
44867     };
44868     MeshFactory.prototype._createDistortedCurtainPlaneMaterialParameters = function (transform, texture) {
44869         var materialParameters = {
44870             depthWrite: false,
44871             fragmentShader: Component_1.Shaders.perspectiveDistortedCurtain.fragment,
44872             side: THREE.DoubleSide,
44873             transparent: true,
44874             uniforms: {
44875                 curtain: {
44876                     type: "f",
44877                     value: 1,
44878                 },
44879                 opacity: {
44880                     type: "f",
44881                     value: 1,
44882                 },
44883                 projectorMat: {
44884                     type: "m4",
44885                     value: transform.projectorMatrix(),
44886                 },
44887                 projectorTex: {
44888                     type: "t",
44889                     value: texture,
44890                 },
44891             },
44892             vertexShader: Component_1.Shaders.perspectiveDistortedCurtain.vertex,
44893         };
44894         return materialParameters;
44895     };
44896     MeshFactory.prototype._createDistortedPlaneMaterialParameters = function (transform, texture) {
44897         var materialParameters = {
44898             depthWrite: false,
44899             fragmentShader: Component_1.Shaders.perspectiveDistorted.fragment,
44900             side: THREE.DoubleSide,
44901             transparent: true,
44902             uniforms: {
44903                 opacity: {
44904                     type: "f",
44905                     value: 1,
44906                 },
44907                 projectorMat: {
44908                     type: "m4",
44909                     value: transform.projectorMatrix(),
44910                 },
44911                 projectorTex: {
44912                     type: "t",
44913                     value: texture,
44914                 },
44915             },
44916             vertexShader: Component_1.Shaders.perspectiveDistorted.vertex,
44917         };
44918         return materialParameters;
44919     };
44920     MeshFactory.prototype._createTexture = function (image) {
44921         var texture = new THREE.Texture(image);
44922         texture.minFilter = THREE.LinearFilter;
44923         texture.needsUpdate = true;
44924         return texture;
44925     };
44926     MeshFactory.prototype._useMesh = function (transform, node) {
44927         return node.mesh.vertices.length && transform.hasValidScale;
44928     };
44929     MeshFactory.prototype._getImageSphereGeo = function (transform, node) {
44930         var t = new THREE.Matrix4().getInverse(transform.srt);
44931         // push everything at least 5 meters in front of the camera
44932         var minZ = 5.0 * transform.scale;
44933         var maxZ = this._imageSphereRadius * transform.scale;
44934         var vertices = node.mesh.vertices;
44935         var numVertices = vertices.length / 3;
44936         var positions = new Float32Array(vertices.length);
44937         for (var i = 0; i < numVertices; ++i) {
44938             var index = 3 * i;
44939             var x = vertices[index + 0];
44940             var y = vertices[index + 1];
44941             var z = vertices[index + 2];
44942             var l = Math.sqrt(x * x + y * y + z * z);
44943             var boundedL = Math.max(minZ, Math.min(l, maxZ));
44944             var factor = boundedL / l;
44945             var p = new THREE.Vector3(x * factor, y * factor, z * factor);
44946             p.applyMatrix4(t);
44947             positions[index + 0] = p.x;
44948             positions[index + 1] = p.y;
44949             positions[index + 2] = p.z;
44950         }
44951         var faces = node.mesh.faces;
44952         var indices = new Uint16Array(faces.length);
44953         for (var i = 0; i < faces.length; ++i) {
44954             indices[i] = faces[i];
44955         }
44956         var geometry = new THREE.BufferGeometry();
44957         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
44958         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
44959         return geometry;
44960     };
44961     MeshFactory.prototype._getImagePlaneGeo = function (transform, node) {
44962         var undistortionMarginFactor = 3;
44963         var t = new THREE.Matrix4().getInverse(transform.srt);
44964         // push everything at least 5 meters in front of the camera
44965         var minZ = 5.0 * transform.scale;
44966         var maxZ = this._imagePlaneDepth * transform.scale;
44967         var vertices = node.mesh.vertices;
44968         var numVertices = vertices.length / 3;
44969         var positions = new Float32Array(vertices.length);
44970         for (var i = 0; i < numVertices; ++i) {
44971             var index = 3 * i;
44972             var x = vertices[index + 0];
44973             var y = vertices[index + 1];
44974             var z = vertices[index + 2];
44975             if (i < 4) {
44976                 x *= undistortionMarginFactor;
44977                 y *= undistortionMarginFactor;
44978             }
44979             var boundedZ = Math.max(minZ, Math.min(z, maxZ));
44980             var factor = boundedZ / z;
44981             var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
44982             p.applyMatrix4(t);
44983             positions[index + 0] = p.x;
44984             positions[index + 1] = p.y;
44985             positions[index + 2] = p.z;
44986         }
44987         var faces = node.mesh.faces;
44988         var indices = new Uint16Array(faces.length);
44989         for (var i = 0; i < faces.length; ++i) {
44990             indices[i] = faces[i];
44991         }
44992         var geometry = new THREE.BufferGeometry();
44993         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
44994         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
44995         return geometry;
44996     };
44997     MeshFactory.prototype._getImagePlaneGeoFisheye = function (transform, node) {
44998         var t = new THREE.Matrix4().getInverse(transform.srt);
44999         // push everything at least 5 meters in front of the camera
45000         var minZ = 5.0 * transform.scale;
45001         var maxZ = this._imagePlaneDepth * transform.scale;
45002         var vertices = node.mesh.vertices;
45003         var numVertices = vertices.length / 3;
45004         var positions = new Float32Array(vertices.length);
45005         for (var i = 0; i < numVertices; ++i) {
45006             var index = 3 * i;
45007             var x = vertices[index + 0];
45008             var y = vertices[index + 1];
45009             var z = vertices[index + 2];
45010             var l = Math.sqrt(x * x + y * y + z * z);
45011             var boundedL = Math.max(minZ, Math.min(l, maxZ));
45012             var factor = boundedL / l;
45013             var p = new THREE.Vector3(x * factor, y * factor, z * factor);
45014             p.applyMatrix4(t);
45015             positions[index + 0] = p.x;
45016             positions[index + 1] = p.y;
45017             positions[index + 2] = p.z;
45018         }
45019         var faces = node.mesh.faces;
45020         var indices = new Uint16Array(faces.length);
45021         for (var i = 0; i < faces.length; ++i) {
45022             indices[i] = faces[i];
45023         }
45024         var geometry = new THREE.BufferGeometry();
45025         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
45026         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
45027         return geometry;
45028     };
45029     MeshFactory.prototype._getFlatImageSphereGeo = function (transform) {
45030         var gpano = transform.gpano;
45031         var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
45032         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
45033         var thetaStart = Math.PI *
45034             (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
45035             gpano.FullPanoHeightPixels;
45036         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
45037         var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
45038         geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
45039         return geometry;
45040     };
45041     MeshFactory.prototype._getRegularFlatImagePlaneGeo = function (transform) {
45042         var width = transform.width;
45043         var height = transform.height;
45044         var size = Math.max(width, height);
45045         var dx = width / 2.0 / size;
45046         var dy = height / 2.0 / size;
45047         return this._getFlatImagePlaneGeo(transform, dx, dy);
45048     };
45049     MeshFactory.prototype._getFlatImagePlaneGeo = function (transform, dx, dy) {
45050         var vertices = [];
45051         vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
45052         vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
45053         vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
45054         vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
45055         return this._createFlatGeometry(vertices);
45056     };
45057     MeshFactory.prototype._getRegularFlatImagePlaneGeoFisheye = function (transform) {
45058         var width = transform.width;
45059         var height = transform.height;
45060         var size = Math.max(width, height);
45061         var dx = width / 2.0 / size;
45062         var dy = height / 2.0 / size;
45063         return this._getFlatImagePlaneGeoFisheye(transform, dx, dy);
45064     };
45065     MeshFactory.prototype._getFlatImagePlaneGeoFisheye = function (transform, dx, dy) {
45066         var vertices = [];
45067         vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
45068         vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
45069         vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
45070         vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
45071         return this._createFlatGeometry(vertices);
45072     };
45073     MeshFactory.prototype._getFlatImagePlaneGeoFromBasic = function (transform, basicX0, basicX1, basicY0, basicY1) {
45074         var vertices = [];
45075         vertices.push(transform.unprojectBasic([basicX0, basicY0], this._imagePlaneDepth));
45076         vertices.push(transform.unprojectBasic([basicX1, basicY0], this._imagePlaneDepth));
45077         vertices.push(transform.unprojectBasic([basicX1, basicY1], this._imagePlaneDepth));
45078         vertices.push(transform.unprojectBasic([basicX0, basicY1], this._imagePlaneDepth));
45079         return this._createFlatGeometry(vertices);
45080     };
45081     MeshFactory.prototype._createFlatGeometry = function (vertices) {
45082         var positions = new Float32Array(12);
45083         for (var i = 0; i < vertices.length; i++) {
45084             var index = 3 * i;
45085             positions[index + 0] = vertices[i][0];
45086             positions[index + 1] = vertices[i][1];
45087             positions[index + 2] = vertices[i][2];
45088         }
45089         var indices = new Uint16Array(6);
45090         indices[0] = 0;
45091         indices[1] = 1;
45092         indices[2] = 3;
45093         indices[3] = 1;
45094         indices[4] = 2;
45095         indices[5] = 3;
45096         var geometry = new THREE.BufferGeometry();
45097         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
45098         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
45099         return geometry;
45100     };
45101     return MeshFactory;
45102 }());
45103 exports.MeshFactory = MeshFactory;
45104 exports.default = MeshFactory;
45105
45106 },{"../../Component":291,"three":242}],401:[function(require,module,exports){
45107 "use strict";
45108 Object.defineProperty(exports, "__esModule", { value: true });
45109 var THREE = require("three");
45110 var MeshScene = /** @class */ (function () {
45111     function MeshScene() {
45112         this._planes = {};
45113         this._planesOld = {};
45114         this._planesPeriphery = {};
45115         this._scene = new THREE.Scene();
45116         this._sceneOld = new THREE.Scene();
45117         this._scenePeriphery = new THREE.Scene();
45118     }
45119     Object.defineProperty(MeshScene.prototype, "planes", {
45120         get: function () {
45121             return this._planes;
45122         },
45123         enumerable: true,
45124         configurable: true
45125     });
45126     Object.defineProperty(MeshScene.prototype, "planesOld", {
45127         get: function () {
45128             return this._planesOld;
45129         },
45130         enumerable: true,
45131         configurable: true
45132     });
45133     Object.defineProperty(MeshScene.prototype, "planesPeriphery", {
45134         get: function () {
45135             return this._planesPeriphery;
45136         },
45137         enumerable: true,
45138         configurable: true
45139     });
45140     Object.defineProperty(MeshScene.prototype, "scene", {
45141         get: function () {
45142             return this._scene;
45143         },
45144         enumerable: true,
45145         configurable: true
45146     });
45147     Object.defineProperty(MeshScene.prototype, "sceneOld", {
45148         get: function () {
45149             return this._sceneOld;
45150         },
45151         enumerable: true,
45152         configurable: true
45153     });
45154     Object.defineProperty(MeshScene.prototype, "scenePeriphery", {
45155         get: function () {
45156             return this._scenePeriphery;
45157         },
45158         enumerable: true,
45159         configurable: true
45160     });
45161     MeshScene.prototype.updateImagePlanes = function (planes) {
45162         this._dispose(this._planesOld, this.sceneOld);
45163         for (var key in this._planes) {
45164             if (!this._planes.hasOwnProperty(key)) {
45165                 continue;
45166             }
45167             var plane = this._planes[key];
45168             this._scene.remove(plane);
45169             this._sceneOld.add(plane);
45170         }
45171         for (var key in planes) {
45172             if (!planes.hasOwnProperty(key)) {
45173                 continue;
45174             }
45175             this._scene.add(planes[key]);
45176         }
45177         this._planesOld = this._planes;
45178         this._planes = planes;
45179     };
45180     MeshScene.prototype.addImagePlanes = function (planes) {
45181         for (var key in planes) {
45182             if (!planes.hasOwnProperty(key)) {
45183                 continue;
45184             }
45185             var plane = planes[key];
45186             this._scene.add(plane);
45187             this._planes[key] = plane;
45188         }
45189     };
45190     MeshScene.prototype.addImagePlanesOld = function (planes) {
45191         for (var key in planes) {
45192             if (!planes.hasOwnProperty(key)) {
45193                 continue;
45194             }
45195             var plane = planes[key];
45196             this._sceneOld.add(plane);
45197             this._planesOld[key] = plane;
45198         }
45199     };
45200     MeshScene.prototype.setImagePlanes = function (planes) {
45201         this._clear();
45202         this.addImagePlanes(planes);
45203     };
45204     MeshScene.prototype.addPeripheryPlanes = function (planes) {
45205         for (var key in planes) {
45206             if (!planes.hasOwnProperty(key)) {
45207                 continue;
45208             }
45209             var plane = planes[key];
45210             this._scenePeriphery.add(plane);
45211             this._planesPeriphery[key] = plane;
45212         }
45213     };
45214     MeshScene.prototype.setPeripheryPlanes = function (planes) {
45215         this._clearPeriphery();
45216         this.addPeripheryPlanes(planes);
45217     };
45218     MeshScene.prototype.setImagePlanesOld = function (planes) {
45219         this._clearOld();
45220         this.addImagePlanesOld(planes);
45221     };
45222     MeshScene.prototype.clear = function () {
45223         this._clear();
45224         this._clearOld();
45225     };
45226     MeshScene.prototype._clear = function () {
45227         this._dispose(this._planes, this._scene);
45228         this._planes = {};
45229     };
45230     MeshScene.prototype._clearOld = function () {
45231         this._dispose(this._planesOld, this._sceneOld);
45232         this._planesOld = {};
45233     };
45234     MeshScene.prototype._clearPeriphery = function () {
45235         this._dispose(this._planesPeriphery, this._scenePeriphery);
45236         this._planesPeriphery = {};
45237     };
45238     MeshScene.prototype._dispose = function (planes, scene) {
45239         for (var key in planes) {
45240             if (!planes.hasOwnProperty(key)) {
45241                 continue;
45242             }
45243             var plane = planes[key];
45244             scene.remove(plane);
45245             plane.geometry.dispose();
45246             plane.material.dispose();
45247             var texture = plane.material.uniforms.projectorTex.value;
45248             if (texture != null) {
45249                 texture.dispose();
45250             }
45251         }
45252     };
45253     return MeshScene;
45254 }());
45255 exports.MeshScene = MeshScene;
45256 exports.default = MeshScene;
45257
45258 },{"three":242}],402:[function(require,module,exports){
45259 "use strict";
45260 Object.defineProperty(exports, "__esModule", { value: true });
45261 var rxjs_1 = require("rxjs");
45262 var operators_1 = require("rxjs/operators");
45263 var MouseOperator = /** @class */ (function () {
45264     function MouseOperator() {
45265     }
45266     MouseOperator.filteredPairwiseMouseDrag$ = function (name, mouseService) {
45267         return mouseService
45268             .filtered$(name, mouseService.mouseDragStart$).pipe(operators_1.switchMap(function (mouseDragStart) {
45269             var mouseDragging$ = rxjs_1.concat(rxjs_1.of(mouseDragStart), mouseService
45270                 .filtered$(name, mouseService.mouseDrag$));
45271             var mouseDragEnd$ = mouseService
45272                 .filtered$(name, mouseService.mouseDragEnd$).pipe(operators_1.map(function () {
45273                 return null;
45274             }));
45275             return rxjs_1.merge(mouseDragging$, mouseDragEnd$).pipe(operators_1.takeWhile(function (e) {
45276                 return !!e;
45277             }), operators_1.startWith(null));
45278         }), operators_1.pairwise(), operators_1.filter(function (pair) {
45279             return pair[0] != null && pair[1] != null;
45280         }));
45281     };
45282     return MouseOperator;
45283 }());
45284 exports.MouseOperator = MouseOperator;
45285 exports.default = MouseOperator;
45286
45287 },{"rxjs":43,"rxjs/operators":241}],403:[function(require,module,exports){
45288 "use strict";
45289 var __extends = (this && this.__extends) || (function () {
45290     var extendStatics = function (d, b) {
45291         extendStatics = Object.setPrototypeOf ||
45292             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
45293             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
45294         return extendStatics(d, b);
45295     }
45296     return function (d, b) {
45297         extendStatics(d, b);
45298         function __() { this.constructor = d; }
45299         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
45300     };
45301 })();
45302 Object.defineProperty(exports, "__esModule", { value: true });
45303 var rxjs_1 = require("rxjs");
45304 var operators_1 = require("rxjs/operators");
45305 var vd = require("virtual-dom");
45306 var Component_1 = require("../../Component");
45307 var Geo_1 = require("../../Geo");
45308 var State_1 = require("../../State");
45309 var ComponentSize_1 = require("../utils/ComponentSize");
45310 /**
45311  * @class ZoomComponent
45312  *
45313  * @classdesc Component rendering UI elements used for zooming.
45314  *
45315  * @example
45316  * ```
45317  * var viewer = new Mapillary.Viewer(
45318  *     "<element-id>",
45319  *     "<client-id>",
45320  *     "<my key>");
45321  *
45322  * var zoomComponent = viewer.getComponent("zoom");
45323  * zoomComponent.configure({ size: Mapillary.ComponentSize.Small });
45324  * ```
45325  */
45326 var ZoomComponent = /** @class */ (function (_super) {
45327     __extends(ZoomComponent, _super);
45328     function ZoomComponent(name, container, navigator) {
45329         var _this = _super.call(this, name, container, navigator) || this;
45330         _this._viewportCoords = new Geo_1.ViewportCoords();
45331         _this._zoomDelta$ = new rxjs_1.Subject();
45332         return _this;
45333     }
45334     ZoomComponent.prototype._activate = function () {
45335         var _this = this;
45336         this._renderSubscription = rxjs_1.combineLatest(this._navigator.stateService.currentState$, this._navigator.stateService.state$, this._configuration$, this._container.renderService.size$).pipe(operators_1.map(function (_a) {
45337             var frame = _a[0], state = _a[1], configuration = _a[2], size = _a[3];
45338             var zoom = frame.state.zoom;
45339             var zoomInIcon = vd.h("div.ZoomInIcon", []);
45340             var zoomInButton = zoom >= 3 || state === State_1.State.Waiting ?
45341                 vd.h("div.ZoomInButtonDisabled", [zoomInIcon]) :
45342                 vd.h("div.ZoomInButton", { onclick: function () { _this._zoomDelta$.next(1); } }, [zoomInIcon]);
45343             var zoomOutIcon = vd.h("div.ZoomOutIcon", []);
45344             var zoomOutButton = zoom <= 0 || state === State_1.State.Waiting ?
45345                 vd.h("div.ZoomOutButtonDisabled", [zoomOutIcon]) :
45346                 vd.h("div.ZoomOutButton", { onclick: function () { _this._zoomDelta$.next(-1); } }, [zoomOutIcon]);
45347             var compact = configuration.size === ComponentSize_1.default.Small ||
45348                 configuration.size === ComponentSize_1.default.Automatic && size.width < 640 ?
45349                 ".ZoomCompact" : "";
45350             return {
45351                 name: _this._name,
45352                 vnode: vd.h("div.ZoomContainer" + compact, { oncontextmenu: function (event) { event.preventDefault(); } }, [zoomInButton, zoomOutButton]),
45353             };
45354         }))
45355             .subscribe(this._container.domRenderer.render$);
45356         this._zoomSubscription = this._zoomDelta$.pipe(operators_1.withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$))
45357             .subscribe(function (_a) {
45358             var zoomDelta = _a[0], render = _a[1], transform = _a[2];
45359             var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
45360             var reference = transform.projectBasic(unprojected.toArray());
45361             _this._navigator.stateService.zoomIn(zoomDelta, reference);
45362         });
45363     };
45364     ZoomComponent.prototype._deactivate = function () {
45365         this._renderSubscription.unsubscribe();
45366         this._zoomSubscription.unsubscribe();
45367     };
45368     ZoomComponent.prototype._getDefaultConfiguration = function () {
45369         return { size: ComponentSize_1.default.Automatic };
45370     };
45371     ZoomComponent.componentName = "zoom";
45372     return ZoomComponent;
45373 }(Component_1.Component));
45374 exports.ZoomComponent = ZoomComponent;
45375 Component_1.ComponentService.register(ZoomComponent);
45376 exports.default = ZoomComponent;
45377
45378 },{"../../Component":291,"../../Geo":294,"../../State":298,"../utils/ComponentSize":398,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],404:[function(require,module,exports){
45379 "use strict";
45380 var __extends = (this && this.__extends) || (function () {
45381     var extendStatics = function (d, b) {
45382         extendStatics = Object.setPrototypeOf ||
45383             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
45384             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
45385         return extendStatics(d, b);
45386     }
45387     return function (d, b) {
45388         extendStatics(d, b);
45389         function __() { this.constructor = d; }
45390         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
45391     };
45392 })();
45393 Object.defineProperty(exports, "__esModule", { value: true });
45394 var MapillaryError_1 = require("./MapillaryError");
45395 /**
45396  * @class AbortMapillaryError
45397  *
45398  * @classdesc Error thrown when a move to request has been
45399  * aborted before completing because of a subsequent request.
45400  */
45401 var AbortMapillaryError = /** @class */ (function (_super) {
45402     __extends(AbortMapillaryError, _super);
45403     function AbortMapillaryError(message) {
45404         var _this = _super.call(this, message != null ? message : "The request was aborted.") || this;
45405         Object.setPrototypeOf(_this, AbortMapillaryError.prototype);
45406         _this.name = "AbortMapillaryError";
45407         return _this;
45408     }
45409     return AbortMapillaryError;
45410 }(MapillaryError_1.MapillaryError));
45411 exports.AbortMapillaryError = AbortMapillaryError;
45412 exports.default = AbortMapillaryError;
45413
45414 },{"./MapillaryError":407}],405:[function(require,module,exports){
45415 "use strict";
45416 var __extends = (this && this.__extends) || (function () {
45417     var extendStatics = function (d, b) {
45418         extendStatics = Object.setPrototypeOf ||
45419             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
45420             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
45421         return extendStatics(d, b);
45422     }
45423     return function (d, b) {
45424         extendStatics(d, b);
45425         function __() { this.constructor = d; }
45426         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
45427     };
45428 })();
45429 Object.defineProperty(exports, "__esModule", { value: true });
45430 var MapillaryError_1 = require("./MapillaryError");
45431 var ArgumentMapillaryError = /** @class */ (function (_super) {
45432     __extends(ArgumentMapillaryError, _super);
45433     function ArgumentMapillaryError(message) {
45434         var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
45435         Object.setPrototypeOf(_this, ArgumentMapillaryError.prototype);
45436         _this.name = "ArgumentMapillaryError";
45437         return _this;
45438     }
45439     return ArgumentMapillaryError;
45440 }(MapillaryError_1.MapillaryError));
45441 exports.ArgumentMapillaryError = ArgumentMapillaryError;
45442 exports.default = ArgumentMapillaryError;
45443
45444 },{"./MapillaryError":407}],406:[function(require,module,exports){
45445 "use strict";
45446 var __extends = (this && this.__extends) || (function () {
45447     var extendStatics = function (d, b) {
45448         extendStatics = Object.setPrototypeOf ||
45449             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
45450             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
45451         return extendStatics(d, b);
45452     }
45453     return function (d, b) {
45454         extendStatics(d, b);
45455         function __() { this.constructor = d; }
45456         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
45457     };
45458 })();
45459 Object.defineProperty(exports, "__esModule", { value: true });
45460 var MapillaryError_1 = require("./MapillaryError");
45461 var GraphMapillaryError = /** @class */ (function (_super) {
45462     __extends(GraphMapillaryError, _super);
45463     function GraphMapillaryError(message) {
45464         var _this = _super.call(this, message) || this;
45465         Object.setPrototypeOf(_this, GraphMapillaryError.prototype);
45466         _this.name = "GraphMapillaryError";
45467         return _this;
45468     }
45469     return GraphMapillaryError;
45470 }(MapillaryError_1.MapillaryError));
45471 exports.GraphMapillaryError = GraphMapillaryError;
45472 exports.default = GraphMapillaryError;
45473
45474 },{"./MapillaryError":407}],407:[function(require,module,exports){
45475 "use strict";
45476 var __extends = (this && this.__extends) || (function () {
45477     var extendStatics = function (d, b) {
45478         extendStatics = Object.setPrototypeOf ||
45479             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
45480             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
45481         return extendStatics(d, b);
45482     }
45483     return function (d, b) {
45484         extendStatics(d, b);
45485         function __() { this.constructor = d; }
45486         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
45487     };
45488 })();
45489 Object.defineProperty(exports, "__esModule", { value: true });
45490 var MapillaryError = /** @class */ (function (_super) {
45491     __extends(MapillaryError, _super);
45492     function MapillaryError(message) {
45493         var _this = _super.call(this, message) || this;
45494         Object.setPrototypeOf(_this, MapillaryError.prototype);
45495         _this.name = "MapillaryError";
45496         return _this;
45497     }
45498     return MapillaryError;
45499 }(Error));
45500 exports.MapillaryError = MapillaryError;
45501 exports.default = MapillaryError;
45502
45503 },{}],408:[function(require,module,exports){
45504 "use strict";
45505 Object.defineProperty(exports, "__esModule", { value: true });
45506 var THREE = require("three");
45507 /**
45508  * @class Camera
45509  *
45510  * @classdesc Holds information about a camera.
45511  */
45512 var Camera = /** @class */ (function () {
45513     /**
45514      * Create a new camera instance.
45515      * @param {Transform} [transform] - Optional transform instance.
45516      */
45517     function Camera(transform) {
45518         if (transform != null) {
45519             this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
45520             this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
45521             this._up = transform.upVector();
45522             this._focal = this._getFocal(transform);
45523         }
45524         else {
45525             this._position = new THREE.Vector3(0, 0, 0);
45526             this._lookat = new THREE.Vector3(0, 0, 1);
45527             this._up = new THREE.Vector3(0, -1, 0);
45528             this._focal = 1;
45529         }
45530     }
45531     Object.defineProperty(Camera.prototype, "position", {
45532         /**
45533          * Get position.
45534          * @returns {THREE.Vector3} The position vector.
45535          */
45536         get: function () {
45537             return this._position;
45538         },
45539         enumerable: true,
45540         configurable: true
45541     });
45542     Object.defineProperty(Camera.prototype, "lookat", {
45543         /**
45544          * Get lookat.
45545          * @returns {THREE.Vector3} The lookat vector.
45546          */
45547         get: function () {
45548             return this._lookat;
45549         },
45550         enumerable: true,
45551         configurable: true
45552     });
45553     Object.defineProperty(Camera.prototype, "up", {
45554         /**
45555          * Get up.
45556          * @returns {THREE.Vector3} The up vector.
45557          */
45558         get: function () {
45559             return this._up;
45560         },
45561         enumerable: true,
45562         configurable: true
45563     });
45564     Object.defineProperty(Camera.prototype, "focal", {
45565         /**
45566          * Get focal.
45567          * @returns {number} The focal length.
45568          */
45569         get: function () {
45570             return this._focal;
45571         },
45572         /**
45573          * Set focal.
45574          */
45575         set: function (value) {
45576             this._focal = value;
45577         },
45578         enumerable: true,
45579         configurable: true
45580     });
45581     /**
45582      * Update this camera to the linearly interpolated value of two other cameras.
45583      *
45584      * @param {Camera} a - First camera.
45585      * @param {Camera} b - Second camera.
45586      * @param {number} alpha - Interpolation value on the interval [0, 1].
45587      */
45588     Camera.prototype.lerpCameras = function (a, b, alpha) {
45589         this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
45590         this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
45591         this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
45592         this._focal = (1 - alpha) * a.focal + alpha * b.focal;
45593     };
45594     /**
45595      * Copy the properties of another camera to this camera.
45596      *
45597      * @param {Camera} other - Another camera.
45598      */
45599     Camera.prototype.copy = function (other) {
45600         this._position.copy(other.position);
45601         this._lookat.copy(other.lookat);
45602         this._up.copy(other.up);
45603         this._focal = other.focal;
45604     };
45605     /**
45606      * Clone this camera.
45607      *
45608      * @returns {Camera} A camera with cloned properties equal to this camera.
45609      */
45610     Camera.prototype.clone = function () {
45611         var camera = new Camera();
45612         camera.position.copy(this._position);
45613         camera.lookat.copy(this._lookat);
45614         camera.up.copy(this._up);
45615         camera.focal = this._focal;
45616         return camera;
45617     };
45618     /**
45619      * Determine the distance between this camera and another camera.
45620      *
45621      * @param {Camera} other - Another camera.
45622      * @returns {number} The distance between the cameras.
45623      */
45624     Camera.prototype.diff = function (other) {
45625         var pd = this._position.distanceToSquared(other.position);
45626         var ld = this._lookat.distanceToSquared(other.lookat);
45627         var ud = this._up.distanceToSquared(other.up);
45628         var fd = 100 * Math.abs(this._focal - other.focal);
45629         return Math.max(pd, ld, ud, fd);
45630     };
45631     /**
45632      * Get the focal length based on the transform.
45633      *
45634      * @description Returns the focal length of the transform if gpano info is not available.
45635      * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
45636      * the gpano information if available.
45637      *
45638      * @returns {number} Focal length.
45639      */
45640     Camera.prototype._getFocal = function (transform) {
45641         if (transform.gpano == null) {
45642             return transform.focal;
45643         }
45644         var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
45645         var focal = 0.5 / Math.tan(vFov / 2);
45646         return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
45647     };
45648     return Camera;
45649 }());
45650 exports.Camera = Camera;
45651
45652 },{"three":242}],409:[function(require,module,exports){
45653 "use strict";
45654 Object.defineProperty(exports, "__esModule", { value: true });
45655 var THREE = require("three");
45656 var Geo_1 = require("../Geo");
45657 var geoCoords = new Geo_1.GeoCoords();
45658 var spatial = new Geo_1.Spatial();
45659 function computeTranslation(position, rotation, reference) {
45660     var C = geoCoords.geodeticToEnu(position.lat, position.lon, position.alt, reference.lat, reference.lon, reference.alt);
45661     var RC = spatial.rotate(C, rotation);
45662     var translation = [-RC.x, -RC.y, -RC.z];
45663     return translation;
45664 }
45665 exports.computeTranslation = computeTranslation;
45666 function computeProjectedPoints(transform, basicVertices, basicDirections, pointsPerLine, viewportCoords) {
45667     var basicPoints = [];
45668     for (var side = 0; side < basicVertices.length; ++side) {
45669         var v = basicVertices[side];
45670         var d = basicDirections[side];
45671         for (var i = 0; i <= pointsPerLine; ++i) {
45672             basicPoints.push([v[0] + d[0] * i / pointsPerLine,
45673                 v[1] + d[1] * i / pointsPerLine]);
45674         }
45675     }
45676     var camera = new THREE.Camera();
45677     camera.up.copy(transform.upVector());
45678     camera.position.copy(new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0)));
45679     camera.lookAt(new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10)));
45680     camera.updateMatrix();
45681     camera.updateMatrixWorld(true);
45682     var projectedPoints = basicPoints
45683         .map(function (basicPoint) {
45684         var worldPoint = transform.unprojectBasic(basicPoint, 10000);
45685         var cameraPoint = viewportCoords.worldToCamera(worldPoint, camera);
45686         return [
45687             Math.abs(cameraPoint[0] / cameraPoint[2]),
45688             Math.abs(cameraPoint[1] / cameraPoint[2]),
45689         ];
45690     });
45691     return projectedPoints;
45692 }
45693 exports.computeProjectedPoints = computeProjectedPoints;
45694
45695 },{"../Geo":294,"three":242}],410:[function(require,module,exports){
45696 "use strict";
45697 Object.defineProperty(exports, "__esModule", { value: true });
45698 /**
45699  * @class GeoCoords
45700  *
45701  * @classdesc Converts coordinates between the geodetic (WGS84),
45702  * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
45703  * East, North, Up (ENU) reference frames.
45704  *
45705  * The WGS84 has latitude (degrees), longitude (degrees) and
45706  * altitude (meters) values.
45707  *
45708  * The ECEF Z-axis pierces the north pole and the
45709  * XY-axis defines the equatorial plane. The X-axis extends
45710  * from the geocenter to the intersection of the Equator and
45711  * the Greenwich Meridian. All values in meters.
45712  *
45713  * The WGS84 parameters are:
45714  *
45715  * a = 6378137
45716  * b = a * (1 - f)
45717  * f = 1 / 298.257223563
45718  * e = Math.sqrt((a^2 - b^2) / a^2)
45719  * e' = Math.sqrt((a^2 - b^2) / b^2)
45720  *
45721  * The WGS84 to ECEF conversion is performed using the following:
45722  *
45723  * X = (N - h) * cos(phi) * cos(lambda)
45724  * Y = (N + h) * cos(phi) * sin(lambda)
45725  * Z = (b^2 * N / a^2 + h) * sin(phi)
45726  *
45727  * where
45728  *
45729  * phi = latitude
45730  * lambda = longitude
45731  * h = height above ellipsoid (altitude)
45732  * N = Radius of curvature (meters)
45733  *   = a / Math.sqrt(1 - e^2 * sin(phi)^2)
45734  *
45735  * The ECEF to WGS84 conversion is performed using the following:
45736  *
45737  * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
45738  * lambda = arctan(Y / X)
45739  * h = p / cos(phi) - N
45740  *
45741  * where
45742  *
45743  * p = Math.sqrt(X^2 + Y^2)
45744  * theta = arctan(Z * a / p * b)
45745  *
45746  * In the ENU reference frame the x-axis points to the
45747  * East, the y-axis to the North and the z-axis Up. All values
45748  * in meters.
45749  *
45750  * The ECEF to ENU conversion is performed using the following:
45751  *
45752  * | x |   |       -sin(lambda_r)                cos(lambda_r)             0      | | X - X_r |
45753  * | y | = | -sin(phi_r) * cos(lambda_r)  -sin(phi_r) * sin(lambda_r)  cos(phi_r) | | Y - Y_r |
45754  * | z |   |  cos(phi_r) * cos(lambda_r)   cos(phi_r) * sin(lambda_r)  sin(phi_r) | | Z - Z_r |
45755  *
45756  * where
45757  *
45758  * phi_r = latitude of reference
45759  * lambda_r = longitude of reference
45760  * X_r, Y_r, Z_r = ECEF coordinates of reference
45761  *
45762  * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
45763  *
45764  * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
45765  * the first step for both conversions.
45766  */
45767 var GeoCoords = /** @class */ (function () {
45768     function GeoCoords() {
45769         this._wgs84a = 6378137.0;
45770         this._wgs84b = 6356752.31424518;
45771     }
45772     /**
45773      * Convert coordinates from geodetic (WGS84) reference to local topocentric
45774      * (ENU) reference.
45775      *
45776      * @param {number} lat Latitude in degrees.
45777      * @param {number} lon Longitude in degrees.
45778      * @param {number} alt Altitude in meters.
45779      * @param {number} refLat Reference latitude in degrees.
45780      * @param {number} refLon Reference longitude in degrees.
45781      * @param {number} refAlt Reference altitude in meters.
45782      * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
45783      */
45784     GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
45785         var ecef = this.geodeticToEcef(lat, lon, alt);
45786         return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
45787     };
45788     /**
45789      * Convert coordinates from local topocentric (ENU) reference to
45790      * geodetic (WGS84) reference.
45791      *
45792      * @param {number} x Topocentric ENU coordinate in East direction.
45793      * @param {number} y Topocentric ENU coordinate in North direction.
45794      * @param {number} z Topocentric ENU coordinate in Up direction.
45795      * @param {number} refLat Reference latitude in degrees.
45796      * @param {number} refLon Reference longitude in degrees.
45797      * @param {number} refAlt Reference altitude in meters.
45798      * @returns {Array<number>} The latitude and longitude in degrees
45799      *                          as well as altitude in meters.
45800      */
45801     GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
45802         var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
45803         return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
45804     };
45805     /**
45806      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
45807      * to local topocentric (ENU) reference.
45808      *
45809      * @param {number} X ECEF X-value.
45810      * @param {number} Y ECEF Y-value.
45811      * @param {number} Z ECEF Z-value.
45812      * @param {number} refLat Reference latitude in degrees.
45813      * @param {number} refLon Reference longitude in degrees.
45814      * @param {number} refAlt Reference altitude in meters.
45815      * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
45816      * and Up directions respectively.
45817      */
45818     GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
45819         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
45820         var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
45821         refLat = refLat * Math.PI / 180.0;
45822         refLon = refLon * Math.PI / 180.0;
45823         var cosLat = Math.cos(refLat);
45824         var sinLat = Math.sin(refLat);
45825         var cosLon = Math.cos(refLon);
45826         var sinLon = Math.sin(refLon);
45827         var x = -sinLon * V[0] + cosLon * V[1];
45828         var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
45829         var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
45830         return [x, y, z];
45831     };
45832     /**
45833      * Convert coordinates from local topocentric (ENU) reference
45834      * to Earth-Centered, Earth-Fixed (ECEF) reference.
45835      *
45836      * @param {number} x Topocentric ENU coordinate in East direction.
45837      * @param {number} y Topocentric ENU coordinate in North direction.
45838      * @param {number} z Topocentric ENU coordinate in Up direction.
45839      * @param {number} refLat Reference latitude in degrees.
45840      * @param {number} refLon Reference longitude in degrees.
45841      * @param {number} refAlt Reference altitude in meters.
45842      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
45843      */
45844     GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
45845         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
45846         refLat = refLat * Math.PI / 180.0;
45847         refLon = refLon * Math.PI / 180.0;
45848         var cosLat = Math.cos(refLat);
45849         var sinLat = Math.sin(refLat);
45850         var cosLon = Math.cos(refLon);
45851         var sinLon = Math.sin(refLon);
45852         var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
45853         var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
45854         var Z = cosLat * y + sinLat * z + refEcef[2];
45855         return [X, Y, Z];
45856     };
45857     /**
45858      * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
45859      * Earth-Fixed (ECEF) reference.
45860      *
45861      * @param {number} lat Latitude in degrees.
45862      * @param {number} lon Longitude in degrees.
45863      * @param {number} alt Altitude in meters.
45864      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
45865      */
45866     GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
45867         var a = this._wgs84a;
45868         var b = this._wgs84b;
45869         lat = lat * Math.PI / 180.0;
45870         lon = lon * Math.PI / 180.0;
45871         var cosLat = Math.cos(lat);
45872         var sinLat = Math.sin(lat);
45873         var cosLon = Math.cos(lon);
45874         var sinLon = Math.sin(lon);
45875         var a2 = a * a;
45876         var b2 = b * b;
45877         var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
45878         var nhcl = (a2 * L + alt) * cosLat;
45879         var X = nhcl * cosLon;
45880         var Y = nhcl * sinLon;
45881         var Z = (b2 * L + alt) * sinLat;
45882         return [X, Y, Z];
45883     };
45884     /**
45885      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
45886      * to geodetic reference (WGS84).
45887      *
45888      * @param {number} X ECEF X-value.
45889      * @param {number} Y ECEF Y-value.
45890      * @param {number} Z ECEF Z-value.
45891      * @returns {Array<number>} The latitude and longitude in degrees
45892      *                          as well as altitude in meters.
45893      */
45894     GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
45895         var a = this._wgs84a;
45896         var b = this._wgs84b;
45897         var a2 = a * a;
45898         var b2 = b * b;
45899         var a2mb2 = a2 - b2;
45900         var ea = Math.sqrt(a2mb2 / a2);
45901         var eb = Math.sqrt(a2mb2 / b2);
45902         var p = Math.sqrt(X * X + Y * Y);
45903         var theta = Math.atan2(Z * a, p * b);
45904         var sinTheta = Math.sin(theta);
45905         var cosTheta = Math.cos(theta);
45906         var lon = Math.atan2(Y, X);
45907         var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
45908         var sinLat = Math.sin(lat);
45909         var cosLat = Math.cos(lat);
45910         var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
45911         var alt = p / cosLat - N;
45912         return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
45913     };
45914     return GeoCoords;
45915 }());
45916 exports.GeoCoords = GeoCoords;
45917 exports.default = GeoCoords;
45918
45919 },{}],411:[function(require,module,exports){
45920 "use strict";
45921 Object.defineProperty(exports, "__esModule", { value: true });
45922 function sign(n) {
45923     return n > 0 ? 1 : n < 0 ? -1 : 0;
45924 }
45925 function colinearPointOnSegment(p, s) {
45926     return p.x <= Math.max(s.p1.x, s.p2.x) &&
45927         p.x >= Math.min(s.p1.x, s.p2.x) &&
45928         p.y >= Math.max(s.p1.y, s.p2.y) &&
45929         p.y >= Math.min(s.p1.y, s.p2.y);
45930 }
45931 function parallel(s1, s2) {
45932     var ux = s1.p2.x - s1.p1.x;
45933     var uy = s1.p2.y - s1.p1.y;
45934     var vx = s2.p2.x - s2.p1.x;
45935     var vy = s2.p2.y - s2.p1.y;
45936     var cross = ux * vy - uy * vx;
45937     var u2 = ux * ux + uy * uy;
45938     var v2 = vx * vx + vy * vy;
45939     var epsilon2 = 1e-10;
45940     return cross * cross < epsilon2 * u2 * v2;
45941 }
45942 function tripletOrientation(p1, p2, p3) {
45943     var orientation = (p2.y - p1.y) * (p3.x - p2.x) -
45944         (p3.y - p2.y) * (p2.x - p1.x);
45945     return sign(orientation);
45946 }
45947 function segmentsIntersect(s1, s2) {
45948     if (parallel(s1, s2)) {
45949         return false;
45950     }
45951     var o1 = tripletOrientation(s1.p1, s1.p2, s2.p1);
45952     var o2 = tripletOrientation(s1.p1, s1.p2, s2.p2);
45953     var o3 = tripletOrientation(s2.p1, s2.p2, s1.p1);
45954     var o4 = tripletOrientation(s2.p1, s2.p2, s1.p2);
45955     if (o1 !== o2 && o3 !== o4) {
45956         return true;
45957     }
45958     if (o1 === 0 && colinearPointOnSegment(s2.p1, s1)) {
45959         return true;
45960     }
45961     if (o2 === 0 && colinearPointOnSegment(s2.p2, s1)) {
45962         return true;
45963     }
45964     if (o3 === 0 && colinearPointOnSegment(s1.p1, s2)) {
45965         return true;
45966     }
45967     if (o4 === 0 && colinearPointOnSegment(s1.p2, s2)) {
45968         return true;
45969     }
45970     return false;
45971 }
45972 exports.segmentsIntersect = segmentsIntersect;
45973 function segmentIntersection(s1, s2) {
45974     if (parallel(s1, s2)) {
45975         return undefined;
45976     }
45977     var x1 = s1.p1.x;
45978     var x2 = s1.p2.x;
45979     var y1 = s1.p1.y;
45980     var y2 = s1.p2.y;
45981     var x3 = s2.p1.x;
45982     var x4 = s2.p2.x;
45983     var y3 = s2.p1.y;
45984     var y4 = s2.p2.y;
45985     var den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
45986     var xNum = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4);
45987     var yNum = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4);
45988     return { x: xNum / den, y: yNum / den };
45989 }
45990 exports.segmentIntersection = segmentIntersection;
45991
45992 },{}],412:[function(require,module,exports){
45993 "use strict";
45994 Object.defineProperty(exports, "__esModule", { value: true });
45995 var THREE = require("three");
45996 /**
45997  * @class Spatial
45998  *
45999  * @classdesc Provides methods for scalar, vector and matrix calculations.
46000  */
46001 var Spatial = /** @class */ (function () {
46002     function Spatial() {
46003         this._epsilon = 1e-9;
46004     }
46005     /**
46006      * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
46007      * bearing (clockwise with origin at north or Y-axis).
46008      *
46009      * @param {number} phi - Azimuthal phi angle in radians.
46010      * @returns {number} Bearing in radians.
46011      */
46012     Spatial.prototype.azimuthalToBearing = function (phi) {
46013         return -phi + Math.PI / 2;
46014     };
46015     /**
46016      * Converts degrees to radians.
46017      *
46018      * @param {number} deg - Degrees.
46019      * @returns {number} Radians.
46020      */
46021     Spatial.prototype.degToRad = function (deg) {
46022         return Math.PI * deg / 180;
46023     };
46024     /**
46025      * Converts radians to degrees.
46026      *
46027      * @param {number} rad - Radians.
46028      * @returns {number} Degrees.
46029      */
46030     Spatial.prototype.radToDeg = function (rad) {
46031         return 180 * rad / Math.PI;
46032     };
46033     /**
46034      * Creates a rotation matrix from an angle-axis vector.
46035      *
46036      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
46037      * @returns {THREE.Matrix4} Rotation matrix.
46038      */
46039     Spatial.prototype.rotationMatrix = function (angleAxis) {
46040         var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
46041         var angle = axis.length();
46042         if (angle > 0) {
46043             axis.normalize();
46044         }
46045         return new THREE.Matrix4().makeRotationAxis(axis, angle);
46046     };
46047     /**
46048      * Rotates a vector according to a angle-axis rotation vector.
46049      *
46050      * @param {Array<number>} vector - Vector to rotate.
46051      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
46052      * @returns {THREE.Vector3} Rotated vector.
46053      */
46054     Spatial.prototype.rotate = function (vector, angleAxis) {
46055         var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
46056         var rotationMatrix = this.rotationMatrix(angleAxis);
46057         v.applyMatrix4(rotationMatrix);
46058         return v;
46059     };
46060     /**
46061      * Calculates the optical center from a rotation vector
46062      * on the angle-axis representation and a translation vector
46063      * according to C = -R^T t.
46064      *
46065      * @param {Array<number>} rotation - Angle-axis representation of a rotation.
46066      * @param {Array<number>} translation - Translation vector.
46067      * @returns {THREE.Vector3} Optical center.
46068      */
46069     Spatial.prototype.opticalCenter = function (rotation, translation) {
46070         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
46071         var vector = [-translation[0], -translation[1], -translation[2]];
46072         return this.rotate(vector, angleAxis);
46073     };
46074     /**
46075      * Calculates the viewing direction from a rotation vector
46076      * on the angle-axis representation.
46077      *
46078      * @param {number[]} rotation - Angle-axis representation of a rotation.
46079      * @returns {THREE.Vector3} Viewing direction.
46080      */
46081     Spatial.prototype.viewingDirection = function (rotation) {
46082         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
46083         return this.rotate([0, 0, 1], angleAxis);
46084     };
46085     /**
46086      * Wrap a number on the interval [min, max].
46087      *
46088      * @param {number} value - Value to wrap.
46089      * @param {number} min - Lower endpoint of interval.
46090      * @param {number} max - Upper endpoint of interval.
46091      * @returns {number} The wrapped number.
46092      */
46093     Spatial.prototype.wrap = function (value, min, max) {
46094         if (max < min) {
46095             throw new Error("Invalid arguments: max must be larger than min.");
46096         }
46097         var interval = (max - min);
46098         while (value > max || value < min) {
46099             if (value > max) {
46100                 value = value - interval;
46101             }
46102             else if (value < min) {
46103                 value = value + interval;
46104             }
46105         }
46106         return value;
46107     };
46108     /**
46109      * Wrap an angle on the interval [-Pi, Pi].
46110      *
46111      * @param {number} angle - Value to wrap.
46112      * @returns {number} Wrapped angle.
46113      */
46114     Spatial.prototype.wrapAngle = function (angle) {
46115         return this.wrap(angle, -Math.PI, Math.PI);
46116     };
46117     /**
46118      * Limit the value to the interval [min, max] by changing the value to
46119      * the nearest available one when it is outside the interval.
46120      *
46121      * @param {number} value - Value to clamp.
46122      * @param {number} min - Minimum of the interval.
46123      * @param {number} max - Maximum of the interval.
46124      * @returns {number} Clamped value.
46125      */
46126     Spatial.prototype.clamp = function (value, min, max) {
46127         if (value < min) {
46128             return min;
46129         }
46130         if (value > max) {
46131             return max;
46132         }
46133         return value;
46134     };
46135     /**
46136      * Calculates the counter-clockwise angle from the first
46137      * vector (x1, y1)^T to the second (x2, y2)^T.
46138      *
46139      * @param {number} x1 - X coordinate of first vector.
46140      * @param {number} y1 - Y coordinate of first vector.
46141      * @param {number} x2 - X coordinate of second vector.
46142      * @param {number} y2 - Y coordinate of second vector.
46143      * @returns {number} Counter clockwise angle between the vectors.
46144      */
46145     Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
46146         var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
46147         return this.wrapAngle(angle);
46148     };
46149     /**
46150      * Calculates the minimum (absolute) angle change for rotation
46151      * from one angle to another on the [-Pi, Pi] interval.
46152      *
46153      * @param {number} angle1 - Start angle.
46154      * @param {number} angle2 - Destination angle.
46155      * @returns {number} Absolute angle change between angles.
46156      */
46157     Spatial.prototype.angleDifference = function (angle1, angle2) {
46158         var angle = angle2 - angle1;
46159         return this.wrapAngle(angle);
46160     };
46161     /**
46162      * Calculates the relative rotation angle between two
46163      * angle-axis vectors.
46164      *
46165      * @param {number} rotation1 - First angle-axis vector.
46166      * @param {number} rotation2 - Second angle-axis vector.
46167      * @returns {number} Relative rotation angle.
46168      */
46169     Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
46170         var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
46171         var R2 = this.rotationMatrix(rotation2);
46172         var R = R1T.multiply(R2);
46173         var elements = R.elements;
46174         // from Tr(R) = 1 + 2 * cos(theta)
46175         var tr = elements[0] + elements[5] + elements[10];
46176         var theta = Math.acos(Math.max(Math.min((tr - 1) / 2, 1), -1));
46177         return theta;
46178     };
46179     /**
46180      * Calculates the angle from a vector to a plane.
46181      *
46182      * @param {Array<number>} vector - The vector.
46183      * @param {Array<number>} planeNormal - Normal of the plane.
46184      * @returns {number} Angle from between plane and vector.
46185      */
46186     Spatial.prototype.angleToPlane = function (vector, planeNormal) {
46187         var v = new THREE.Vector3().fromArray(vector);
46188         var norm = v.length();
46189         if (norm < this._epsilon) {
46190             return 0;
46191         }
46192         var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
46193         return Math.asin(projection / norm);
46194     };
46195     Spatial.prototype.azimuthal = function (direction, up) {
46196         var directionVector = new THREE.Vector3().fromArray(direction);
46197         var upVector = new THREE.Vector3().fromArray(up);
46198         var upProjection = directionVector.clone().dot(upVector);
46199         var planeProjection = directionVector.clone().sub(upVector.clone().multiplyScalar(upProjection));
46200         return Math.atan2(planeProjection.y, planeProjection.x);
46201     };
46202     /**
46203      * Calculates the distance between two coordinates
46204      * (latitude longitude pairs) in meters according to
46205      * the haversine formula.
46206      *
46207      * @param {number} lat1 - Latitude of the first coordinate in degrees.
46208      * @param {number} lon1 - Longitude of the first coordinate in degrees.
46209      * @param {number} lat2 - Latitude of the second coordinate in degrees.
46210      * @param {number} lon2 - Longitude of the second coordinate in degrees.
46211      * @returns {number} Distance between lat lon positions in meters.
46212      */
46213     Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
46214         var r = 6371000;
46215         var dLat = this.degToRad(lat2 - lat1);
46216         var dLon = this.degToRad(lon2 - lon1);
46217         var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
46218             Math.cos(this.degToRad(lat1)) * Math.cos(this.degToRad(lat2)) *
46219                 Math.sin(dLon / 2) * Math.sin(dLon / 2);
46220         var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
46221         return d;
46222     };
46223     return Spatial;
46224 }());
46225 exports.Spatial = Spatial;
46226 exports.default = Spatial;
46227
46228 },{"three":242}],413:[function(require,module,exports){
46229 "use strict";
46230 Object.defineProperty(exports, "__esModule", { value: true });
46231 var THREE = require("three");
46232 /**
46233  * @class Transform
46234  *
46235  * @classdesc Class used for calculating coordinate transformations
46236  * and projections.
46237  */
46238 var Transform = /** @class */ (function () {
46239     /**
46240      * Create a new transform instance.
46241      * @param {number} orientation - Image orientation.
46242      * @param {number} width - Image height.
46243      * @param {number} height - Image width.
46244      * @param {number} focal - Focal length.
46245      * @param {number} scale - Atomic scale.
46246      * @param {IGPano} gpano - Panorama properties.
46247      * @param {Array<number>} rotation - Rotation vector in three dimensions.
46248      * @param {Array<number>} translation - Translation vector in three dimensions.
46249      * @param {HTMLImageElement} image - Image for fallback size calculations.
46250      */
46251     function Transform(orientation, width, height, focal, scale, gpano, rotation, translation, image, textureScale, ck1, ck2, cameraProjection) {
46252         this._orientation = this._getValue(orientation, 1);
46253         var imageWidth = image != null ? image.width : 4;
46254         var imageHeight = image != null ? image.height : 3;
46255         var keepOrientation = this._orientation < 5;
46256         this._width = this._getValue(width, keepOrientation ? imageWidth : imageHeight);
46257         this._height = this._getValue(height, keepOrientation ? imageHeight : imageWidth);
46258         this._basicAspect = keepOrientation ?
46259             this._width / this._height :
46260             this._height / this._width;
46261         this._basicWidth = keepOrientation ? width : height;
46262         this._basicHeight = keepOrientation ? height : width;
46263         this._focal = this._getValue(focal, 1);
46264         this._scale = this._getValue(scale, 0);
46265         this._gpano = gpano != null ? gpano : null;
46266         this._rt = this._getRt(rotation, translation);
46267         this._srt = this._getSrt(this._rt, this._scale);
46268         this._basicRt = this._getBasicRt(this._rt, orientation);
46269         this._textureScale = !!textureScale ? textureScale : [1, 1];
46270         this._ck1 = !!ck1 ? ck1 : 0;
46271         this._ck2 = !!ck2 ? ck2 : 0;
46272         this._cameraProjection = !!cameraProjection ?
46273             cameraProjection :
46274             !!gpano ?
46275                 "equirectangular" :
46276                 "perspective";
46277         this._radialPeak = this._getRadialPeak(this._ck1, this._ck2);
46278     }
46279     Object.defineProperty(Transform.prototype, "ck1", {
46280         get: function () {
46281             return this._ck1;
46282         },
46283         enumerable: true,
46284         configurable: true
46285     });
46286     Object.defineProperty(Transform.prototype, "ck2", {
46287         get: function () {
46288             return this._ck2;
46289         },
46290         enumerable: true,
46291         configurable: true
46292     });
46293     Object.defineProperty(Transform.prototype, "cameraProjection", {
46294         get: function () {
46295             return this._cameraProjection;
46296         },
46297         enumerable: true,
46298         configurable: true
46299     });
46300     Object.defineProperty(Transform.prototype, "basicAspect", {
46301         /**
46302          * Get basic aspect.
46303          * @returns {number} The orientation adjusted aspect ratio.
46304          */
46305         get: function () {
46306             return this._basicAspect;
46307         },
46308         enumerable: true,
46309         configurable: true
46310     });
46311     Object.defineProperty(Transform.prototype, "basicHeight", {
46312         /**
46313          * Get basic height.
46314          *
46315          * @description Does not fall back to node image height but
46316          * uses original value from API so can be faulty.
46317          *
46318          * @returns {number} The height of the basic version image
46319          * (adjusted for orientation).
46320          */
46321         get: function () {
46322             return this._basicHeight;
46323         },
46324         enumerable: true,
46325         configurable: true
46326     });
46327     Object.defineProperty(Transform.prototype, "basicRt", {
46328         get: function () {
46329             return this._basicRt;
46330         },
46331         enumerable: true,
46332         configurable: true
46333     });
46334     Object.defineProperty(Transform.prototype, "basicWidth", {
46335         /**
46336          * Get basic width.
46337          *
46338          * @description Does not fall back to node image width but
46339          * uses original value from API so can be faulty.
46340          *
46341          * @returns {number} The width of the basic version image
46342          * (adjusted for orientation).
46343          */
46344         get: function () {
46345             return this._basicWidth;
46346         },
46347         enumerable: true,
46348         configurable: true
46349     });
46350     Object.defineProperty(Transform.prototype, "focal", {
46351         /**
46352          * Get focal.
46353          * @returns {number} The node focal length.
46354          */
46355         get: function () {
46356             return this._focal;
46357         },
46358         enumerable: true,
46359         configurable: true
46360     });
46361     Object.defineProperty(Transform.prototype, "fullPano", {
46362         /**
46363          * Get fullPano.
46364          *
46365          * @returns {boolean} Value indicating whether the node is a complete
46366          * 360 panorama.
46367          */
46368         get: function () {
46369             return this._gpano != null &&
46370                 this._gpano.CroppedAreaLeftPixels === 0 &&
46371                 this._gpano.CroppedAreaTopPixels === 0 &&
46372                 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
46373                 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
46374         },
46375         enumerable: true,
46376         configurable: true
46377     });
46378     Object.defineProperty(Transform.prototype, "gpano", {
46379         /**
46380          * Get gpano.
46381          * @returns {number} The node gpano information.
46382          */
46383         get: function () {
46384             return this._gpano;
46385         },
46386         enumerable: true,
46387         configurable: true
46388     });
46389     Object.defineProperty(Transform.prototype, "height", {
46390         /**
46391          * Get height.
46392          *
46393          * @description Falls back to the node image height if
46394          * the API data is faulty.
46395          *
46396          * @returns {number} The orientation adjusted image height.
46397          */
46398         get: function () {
46399             return this._height;
46400         },
46401         enumerable: true,
46402         configurable: true
46403     });
46404     Object.defineProperty(Transform.prototype, "orientation", {
46405         /**
46406          * Get orientation.
46407          * @returns {number} The image orientation.
46408          */
46409         get: function () {
46410             return this._orientation;
46411         },
46412         enumerable: true,
46413         configurable: true
46414     });
46415     Object.defineProperty(Transform.prototype, "rt", {
46416         /**
46417          * Get rt.
46418          * @returns {THREE.Matrix4} The extrinsic camera matrix.
46419          */
46420         get: function () {
46421             return this._rt;
46422         },
46423         enumerable: true,
46424         configurable: true
46425     });
46426     Object.defineProperty(Transform.prototype, "srt", {
46427         /**
46428          * Get srt.
46429          * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
46430          */
46431         get: function () {
46432             return this._srt;
46433         },
46434         enumerable: true,
46435         configurable: true
46436     });
46437     Object.defineProperty(Transform.prototype, "scale", {
46438         /**
46439          * Get scale.
46440          * @returns {number} The node atomic reconstruction scale.
46441          */
46442         get: function () {
46443             return this._scale;
46444         },
46445         enumerable: true,
46446         configurable: true
46447     });
46448     Object.defineProperty(Transform.prototype, "hasValidScale", {
46449         /**
46450          * Get has valid scale.
46451          * @returns {boolean} Value indicating if the scale of the transform is valid.
46452          */
46453         get: function () {
46454             return this._scale > 1e-2 && this._scale < 50;
46455         },
46456         enumerable: true,
46457         configurable: true
46458     });
46459     Object.defineProperty(Transform.prototype, "radialPeak", {
46460         /**
46461          * Get radial peak.
46462          * @returns {number} Value indicating the radius where the radial
46463          * undistortion function peaks.
46464          */
46465         get: function () {
46466             return this._radialPeak;
46467         },
46468         enumerable: true,
46469         configurable: true
46470     });
46471     Object.defineProperty(Transform.prototype, "width", {
46472         /**
46473          * Get width.
46474          *
46475          * @description Falls back to the node image width if
46476          * the API data is faulty.
46477          *
46478          * @returns {number} The orientation adjusted image width.
46479          */
46480         get: function () {
46481             return this._width;
46482         },
46483         enumerable: true,
46484         configurable: true
46485     });
46486     /**
46487      * Calculate the up vector for the node transform.
46488      *
46489      * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
46490      */
46491     Transform.prototype.upVector = function () {
46492         var rte = this._rt.elements;
46493         switch (this._orientation) {
46494             case 1:
46495                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
46496             case 3:
46497                 return new THREE.Vector3(rte[1], rte[5], rte[9]);
46498             case 6:
46499                 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
46500             case 8:
46501                 return new THREE.Vector3(rte[0], rte[4], rte[8]);
46502             default:
46503                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
46504         }
46505     };
46506     /**
46507      * Calculate projector matrix for projecting 3D points to texture map
46508      * coordinates (u and v).
46509      *
46510      * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
46511      * map coordinate calculations.
46512      */
46513     Transform.prototype.projectorMatrix = function () {
46514         var projector = this._normalizedToTextureMatrix();
46515         var f = this._focal;
46516         var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
46517         projector.multiply(projection);
46518         projector.multiply(this._rt);
46519         return projector;
46520     };
46521     /**
46522      * Project 3D world coordinates to basic coordinates.
46523      *
46524      * @param {Array<number>} point3d - 3D world coordinates.
46525      * @return {Array<number>} 2D basic coordinates.
46526      */
46527     Transform.prototype.projectBasic = function (point3d) {
46528         var sfm = this.projectSfM(point3d);
46529         return this._sfmToBasic(sfm);
46530     };
46531     /**
46532      * Unproject basic coordinates to 3D world coordinates.
46533      *
46534      * @param {Array<number>} basic - 2D basic coordinates.
46535      * @param {Array<number>} distance - Distance to unproject from camera center.
46536      * @param {boolean} [depth] - Treat the distance value as depth from camera center.
46537      *                            Only applicable for perspective images. Will be
46538      *                            ignored for panoramas.
46539      * @returns {Array<number>} Unprojected 3D world coordinates.
46540      */
46541     Transform.prototype.unprojectBasic = function (basic, distance, depth) {
46542         var sfm = this._basicToSfm(basic);
46543         return this.unprojectSfM(sfm, distance, depth);
46544     };
46545     /**
46546      * Project 3D world coordinates to SfM coordinates.
46547      *
46548      * @param {Array<number>} point3d - 3D world coordinates.
46549      * @return {Array<number>} 2D SfM coordinates.
46550      */
46551     Transform.prototype.projectSfM = function (point3d) {
46552         var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
46553         v.applyMatrix4(this._rt);
46554         return this._bearingToSfm([v.x, v.y, v.z]);
46555     };
46556     /**
46557      * Unproject SfM coordinates to a 3D world coordinates.
46558      *
46559      * @param {Array<number>} sfm - 2D SfM coordinates.
46560      * @param {Array<number>} distance - Distance to unproject from camera center.
46561      * @param {boolean} [depth] - Treat the distance value as depth from camera center.
46562      *                            Only applicable for perspective images. Will be
46563      *                            ignored for panoramas.
46564      * @returns {Array<number>} Unprojected 3D world coordinates.
46565      */
46566     Transform.prototype.unprojectSfM = function (sfm, distance, depth) {
46567         var bearing = this._sfmToBearing(sfm);
46568         var v = depth && !this.gpano ?
46569             new THREE.Vector4(distance * bearing[0] / bearing[2], distance * bearing[1] / bearing[2], distance, 1) :
46570             new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
46571         v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
46572         return [v.x / v.w, v.y / v.w, v.z / v.w];
46573     };
46574     /**
46575      * Transform SfM coordinates to bearing vector (3D cartesian
46576      * coordinates on the unit sphere).
46577      *
46578      * @param {Array<number>} sfm - 2D SfM coordinates.
46579      * @returns {Array<number>} Bearing vector (3D cartesian coordinates
46580      * on the unit sphere).
46581      */
46582     Transform.prototype._sfmToBearing = function (sfm) {
46583         if (this._fullPano()) {
46584             var lon = sfm[0] * 2 * Math.PI;
46585             var lat = -sfm[1] * 2 * Math.PI;
46586             var x = Math.cos(lat) * Math.sin(lon);
46587             var y = -Math.sin(lat);
46588             var z = Math.cos(lat) * Math.cos(lon);
46589             return [x, y, z];
46590         }
46591         else if (this._gpano) {
46592             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
46593             var fullPanoPixel = [
46594                 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
46595                 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
46596             ];
46597             var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
46598             var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
46599             var x = Math.cos(lat) * Math.sin(lon);
46600             var y = -Math.sin(lat);
46601             var z = Math.cos(lat) * Math.cos(lon);
46602             return [x, y, z];
46603         }
46604         else if (this._cameraProjection === "fisheye") {
46605             var _a = [sfm[0] / this._focal, sfm[1] / this._focal], dxn = _a[0], dyn = _a[1];
46606             var dTheta = Math.sqrt(dxn * dxn + dyn * dyn);
46607             var d = this._distortionFromDistortedRadius(dTheta, this._ck1, this._ck2, this._radialPeak);
46608             var theta = dTheta / d;
46609             var z = Math.cos(theta);
46610             var r = Math.sin(theta);
46611             var x = r * dxn / dTheta;
46612             var y = r * dyn / dTheta;
46613             return [x, y, z];
46614         }
46615         else {
46616             var _b = [sfm[0] / this._focal, sfm[1] / this._focal], dxn = _b[0], dyn = _b[1];
46617             var dr = Math.sqrt(dxn * dxn + dyn * dyn);
46618             var d = this._distortionFromDistortedRadius(dr, this._ck1, this._ck2, this._radialPeak);
46619             var xn = dxn / d;
46620             var yn = dyn / d;
46621             var v = new THREE.Vector3(xn, yn, 1);
46622             v.normalize();
46623             return [v.x, v.y, v.z];
46624         }
46625     };
46626     /** Compute distortion given the distorted radius.
46627      *
46628      *  Solves for d in the equation
46629      *    y = d(x, k1, k2) * x
46630      * given the distorted radius, y.
46631      */
46632     Transform.prototype._distortionFromDistortedRadius = function (distortedRadius, k1, k2, radialPeak) {
46633         var d = 1.0;
46634         for (var i = 0; i < 10; i++) {
46635             var radius = distortedRadius / d;
46636             if (radius > radialPeak) {
46637                 radius = radialPeak;
46638             }
46639             d = 1 + k1 * Math.pow(radius, 2) + k2 * Math.pow(radius, 4);
46640         }
46641         return d;
46642     };
46643     /**
46644      * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
46645      * SfM coordinates.
46646      *
46647      * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
46648      * unit sphere).
46649      * @returns {Array<number>} 2D SfM coordinates.
46650      */
46651     Transform.prototype._bearingToSfm = function (bearing) {
46652         if (this._fullPano()) {
46653             var x = bearing[0];
46654             var y = bearing[1];
46655             var z = bearing[2];
46656             var lon = Math.atan2(x, z);
46657             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
46658             return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
46659         }
46660         else if (this._gpano) {
46661             var x = bearing[0];
46662             var y = bearing[1];
46663             var z = bearing[2];
46664             var lon = Math.atan2(x, z);
46665             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
46666             var fullPanoPixel = [
46667                 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
46668                 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
46669             ];
46670             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
46671             return [
46672                 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
46673                 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
46674             ];
46675         }
46676         else if (this._cameraProjection === "fisheye") {
46677             if (bearing[2] > 0) {
46678                 var x = bearing[0], y = bearing[1], z = bearing[2];
46679                 var r = Math.sqrt(x * x + y * y);
46680                 var theta = Math.atan2(r, z);
46681                 if (theta > this._radialPeak) {
46682                     theta = this._radialPeak;
46683                 }
46684                 var distortion = 1.0 + Math.pow(theta, 2) * (this._ck1 + Math.pow(theta, 2) * this._ck2);
46685                 var s = this._focal * distortion * theta / r;
46686                 return [s * x, s * y];
46687             }
46688             else {
46689                 return [
46690                     bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
46691                     bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
46692                 ];
46693             }
46694         }
46695         else {
46696             if (bearing[2] > 0) {
46697                 var _a = [bearing[0] / bearing[2], bearing[1] / bearing[2]], xn = _a[0], yn = _a[1];
46698                 var r2 = xn * xn + yn * yn;
46699                 var rp2 = Math.pow(this._radialPeak, 2);
46700                 if (r2 > rp2) {
46701                     r2 = rp2;
46702                 }
46703                 var d = 1 + this._ck1 * r2 + this._ck2 * Math.pow(r2, 2);
46704                 return [
46705                     this._focal * d * xn,
46706                     this._focal * d * yn,
46707                 ];
46708             }
46709             else {
46710                 return [
46711                     bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
46712                     bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
46713                 ];
46714             }
46715         }
46716     };
46717     /**
46718      * Convert basic coordinates to SfM coordinates.
46719      *
46720      * @param {Array<number>} basic - 2D basic coordinates.
46721      * @returns {Array<number>} 2D SfM coordinates.
46722      */
46723     Transform.prototype._basicToSfm = function (basic) {
46724         var rotatedX;
46725         var rotatedY;
46726         switch (this._orientation) {
46727             case 1:
46728                 rotatedX = basic[0];
46729                 rotatedY = basic[1];
46730                 break;
46731             case 3:
46732                 rotatedX = 1 - basic[0];
46733                 rotatedY = 1 - basic[1];
46734                 break;
46735             case 6:
46736                 rotatedX = basic[1];
46737                 rotatedY = 1 - basic[0];
46738                 break;
46739             case 8:
46740                 rotatedX = 1 - basic[1];
46741                 rotatedY = basic[0];
46742                 break;
46743             default:
46744                 rotatedX = basic[0];
46745                 rotatedY = basic[1];
46746                 break;
46747         }
46748         var w = this._width;
46749         var h = this._height;
46750         var s = Math.max(w, h);
46751         var sfmX = rotatedX * w / s - w / s / 2;
46752         var sfmY = rotatedY * h / s - h / s / 2;
46753         return [sfmX, sfmY];
46754     };
46755     /**
46756      * Convert SfM coordinates to basic coordinates.
46757      *
46758      * @param {Array<number>} sfm - 2D SfM coordinates.
46759      * @returns {Array<number>} 2D basic coordinates.
46760      */
46761     Transform.prototype._sfmToBasic = function (sfm) {
46762         var w = this._width;
46763         var h = this._height;
46764         var s = Math.max(w, h);
46765         var rotatedX = (sfm[0] + w / s / 2) / w * s;
46766         var rotatedY = (sfm[1] + h / s / 2) / h * s;
46767         var basicX;
46768         var basicY;
46769         switch (this._orientation) {
46770             case 1:
46771                 basicX = rotatedX;
46772                 basicY = rotatedY;
46773                 break;
46774             case 3:
46775                 basicX = 1 - rotatedX;
46776                 basicY = 1 - rotatedY;
46777                 break;
46778             case 6:
46779                 basicX = 1 - rotatedY;
46780                 basicY = rotatedX;
46781                 break;
46782             case 8:
46783                 basicX = rotatedY;
46784                 basicY = 1 - rotatedX;
46785                 break;
46786             default:
46787                 basicX = rotatedX;
46788                 basicY = rotatedY;
46789                 break;
46790         }
46791         return [basicX, basicY];
46792     };
46793     /**
46794      * Determines if the gpano information indicates a full panorama.
46795      *
46796      * @returns {boolean} Value determining if the gpano information indicates
46797      * a full panorama.
46798      */
46799     Transform.prototype._fullPano = function () {
46800         return this.gpano != null &&
46801             this.gpano.CroppedAreaLeftPixels === 0 &&
46802             this.gpano.CroppedAreaTopPixels === 0 &&
46803             this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
46804             this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
46805     };
46806     /**
46807      * Checks a value and returns it if it exists and is larger than 0.
46808      * Fallbacks if it is null.
46809      *
46810      * @param {number} value - Value to check.
46811      * @param {number} fallback - Value to fall back to.
46812      * @returns {number} The value or its fallback value if it is not defined or negative.
46813      */
46814     Transform.prototype._getValue = function (value, fallback) {
46815         return value != null && value > 0 ? value : fallback;
46816     };
46817     /**
46818      * Creates the extrinsic camera matrix [ R | t ].
46819      *
46820      * @param {Array<number>} rotation - Rotation vector in angle axis representation.
46821      * @param {Array<number>} translation - Translation vector.
46822      * @returns {THREE.Matrix4} Extrisic camera matrix.
46823      */
46824     Transform.prototype._getRt = function (rotation, translation) {
46825         var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
46826         var angle = axis.length();
46827         if (angle > 0) {
46828             axis.normalize();
46829         }
46830         var rt = new THREE.Matrix4();
46831         rt.makeRotationAxis(axis, angle);
46832         rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
46833         return rt;
46834     };
46835     /**
46836      * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
46837      *
46838      * @param {THREE.Matrix4} rt - Extrisic camera matrix.
46839      * @param {number} scale - Scale factor.
46840      * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
46841      */
46842     Transform.prototype._getSrt = function (rt, scale) {
46843         var srt = rt.clone();
46844         var elements = srt.elements;
46845         elements[12] = scale * elements[12];
46846         elements[13] = scale * elements[13];
46847         elements[14] = scale * elements[14];
46848         srt.scale(new THREE.Vector3(scale, scale, scale));
46849         return srt;
46850     };
46851     Transform.prototype._getBasicRt = function (rt, orientation) {
46852         var axis = new THREE.Vector3(0, 0, 1);
46853         var angle = 0;
46854         switch (orientation) {
46855             case 3:
46856                 angle = Math.PI;
46857                 break;
46858             case 6:
46859                 angle = Math.PI / 2;
46860                 break;
46861             case 8:
46862                 angle = 3 * Math.PI / 2;
46863                 break;
46864             default:
46865                 break;
46866         }
46867         return new THREE.Matrix4()
46868             .makeRotationAxis(axis, angle)
46869             .multiply(rt);
46870     };
46871     Transform.prototype._getRadialPeak = function (k1, k2) {
46872         var a = 5 * k2;
46873         var b = 3 * k1;
46874         var c = 1;
46875         var d = Math.pow(b, 2) - 4 * a * c;
46876         if (d < 0) {
46877             return undefined;
46878         }
46879         var root1 = (-b - Math.sqrt(d)) / 2 / a;
46880         var root2 = (-b + Math.sqrt(d)) / 2 / a;
46881         var minRoot = Math.min(root1, root2);
46882         var maxRoot = Math.max(root1, root2);
46883         return minRoot > 0 ?
46884             Math.sqrt(minRoot) :
46885             maxRoot > 0 ?
46886                 Math.sqrt(maxRoot) :
46887                 undefined;
46888     };
46889     /**
46890      * Calculate a transformation matrix from normalized coordinates for
46891      * texture map coordinates.
46892      *
46893      * @returns {THREE.Matrix4} Normalized coordinates to texture map
46894      * coordinates transformation matrix.
46895      */
46896     Transform.prototype._normalizedToTextureMatrix = function () {
46897         var size = Math.max(this._width, this._height);
46898         var scaleX = this._orientation < 5 ? this._textureScale[0] : this._textureScale[1];
46899         var scaleY = this._orientation < 5 ? this._textureScale[1] : this._textureScale[0];
46900         var w = size / this._width * scaleX;
46901         var h = size / this._height * scaleY;
46902         switch (this._orientation) {
46903             case 1:
46904                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
46905             case 3:
46906                 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
46907             case 6:
46908                 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
46909             case 8:
46910                 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
46911             default:
46912                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
46913         }
46914     };
46915     return Transform;
46916 }());
46917 exports.Transform = Transform;
46918
46919 },{"three":242}],414:[function(require,module,exports){
46920 "use strict";
46921 Object.defineProperty(exports, "__esModule", { value: true });
46922 var THREE = require("three");
46923 /**
46924  * @class ViewportCoords
46925  *
46926  * @classdesc Provides methods for calculating 2D coordinate conversions
46927  * as well as 3D projection and unprojection.
46928  *
46929  * Basic coordinates are 2D coordinates on the [0, 1] interval and
46930  * have the origin point, (0, 0), at the top left corner and the
46931  * maximum value, (1, 1), at the bottom right corner of the original
46932  * image.
46933  *
46934  * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
46935  * have the origin point in the center. The bottom left corner point is
46936  * (-1, -1) and the top right corner point is (1, 1).
46937  *
46938  * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
46939  * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
46940  * corner and the maximum value is (canvasWidth, canvasHeight) is in the
46941  * bottom right corner.
46942  *
46943  * 3D coordinates are in the topocentric world reference frame.
46944  */
46945 var ViewportCoords = /** @class */ (function () {
46946     function ViewportCoords() {
46947         this._unprojectDepth = 200;
46948     }
46949     /**
46950      * Convert basic coordinates to canvas coordinates.
46951      *
46952      * @description Transform origin and camera position needs to be the
46953      * equal for reliable return value.
46954      *
46955      * @param {number} basicX - Basic X coordinate.
46956      * @param {number} basicY - Basic Y coordinate.
46957      * @param {HTMLElement} container - The viewer container.
46958      * @param {Transform} transform - Transform of the node to unproject from.
46959      * @param {THREE.Camera} camera - Camera used in rendering.
46960      * @returns {Array<number>} 2D canvas coordinates.
46961      */
46962     ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) {
46963         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
46964         var canvas = this.projectToCanvas(point3d, container, camera);
46965         return canvas;
46966     };
46967     /**
46968      * Convert basic coordinates to canvas coordinates safely. If 3D point is
46969      * behind camera null will be returned.
46970      *
46971      * @description Transform origin and camera position needs to be the
46972      * equal for reliable return value.
46973      *
46974      * @param {number} basicX - Basic X coordinate.
46975      * @param {number} basicY - Basic Y coordinate.
46976      * @param {HTMLElement} container - The viewer container.
46977      * @param {Transform} transform - Transform of the node to unproject from.
46978      * @param {THREE.Camera} camera - Camera used in rendering.
46979      * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point
46980      * in front of the camera, otherwise null.
46981      */
46982     ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) {
46983         var viewport = this.basicToViewportSafe(basicX, basicY, transform, camera);
46984         if (viewport === null) {
46985             return null;
46986         }
46987         var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
46988         return canvas;
46989     };
46990     /**
46991      * Convert basic coordinates to viewport coordinates.
46992      *
46993      * @description Transform origin and camera position needs to be the
46994      * equal for reliable return value.
46995      *
46996      * @param {number} basicX - Basic X coordinate.
46997      * @param {number} basicY - Basic Y coordinate.
46998      * @param {Transform} transform - Transform of the node to unproject from.
46999      * @param {THREE.Camera} camera - Camera used in rendering.
47000      * @returns {Array<number>} 2D viewport coordinates.
47001      */
47002     ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) {
47003         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
47004         var viewport = this.projectToViewport(point3d, camera);
47005         return viewport;
47006     };
47007     /**
47008      * Convert basic coordinates to viewport coordinates safely. If 3D point is
47009      * behind camera null will be returned.
47010      *
47011      * @description Transform origin and camera position needs to be the
47012      * equal for reliable return value.
47013      *
47014      * @param {number} basicX - Basic X coordinate.
47015      * @param {number} basicY - Basic Y coordinate.
47016      * @param {Transform} transform - Transform of the node to unproject from.
47017      * @param {THREE.Camera} camera - Camera used in rendering.
47018      * @returns {Array<number>} 2D viewport coordinates.
47019      */
47020     ViewportCoords.prototype.basicToViewportSafe = function (basicX, basicY, transform, camera) {
47021         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
47022         var pointCamera = this.worldToCamera(point3d, camera);
47023         if (pointCamera[2] > 0) {
47024             return null;
47025         }
47026         var viewport = this.projectToViewport(point3d, camera);
47027         return viewport;
47028     };
47029     /**
47030      * Convert camera 3D coordinates to viewport coordinates.
47031      *
47032      * @param {number} pointCamera - 3D point in camera coordinate system.
47033      * @param {THREE.Camera} camera - Camera used in rendering.
47034      * @returns {Array<number>} 2D viewport coordinates.
47035      */
47036     ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) {
47037         var viewport = new THREE.Vector3().fromArray(pointCamera)
47038             .applyMatrix4(camera.projectionMatrix);
47039         return [viewport.x, viewport.y];
47040     };
47041     /**
47042      * Get canvas pixel position from event.
47043      *
47044      * @param {Event} event - Event containing clientX and clientY properties.
47045      * @param {HTMLElement} element - HTML element.
47046      * @returns {Array<number>} 2D canvas coordinates.
47047      */
47048     ViewportCoords.prototype.canvasPosition = function (event, element) {
47049         var clientRect = element.getBoundingClientRect();
47050         var canvasX = event.clientX - clientRect.left - element.clientLeft;
47051         var canvasY = event.clientY - clientRect.top - element.clientTop;
47052         return [canvasX, canvasY];
47053     };
47054     /**
47055      * Convert canvas coordinates to basic coordinates.
47056      *
47057      * @description Transform origin and camera position needs to be the
47058      * equal for reliable return value.
47059      *
47060      * @param {number} canvasX - Canvas X coordinate.
47061      * @param {number} canvasY - Canvas Y coordinate.
47062      * @param {HTMLElement} container - The viewer container.
47063      * @param {Transform} transform - Transform of the node to unproject from.
47064      * @param {THREE.Camera} camera - Camera used in rendering.
47065      * @returns {Array<number>} 2D basic coordinates.
47066      */
47067     ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) {
47068         var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera)
47069             .toArray();
47070         var basic = transform.projectBasic(point3d);
47071         return basic;
47072     };
47073     /**
47074      * Convert canvas coordinates to viewport coordinates.
47075      *
47076      * @param {number} canvasX - Canvas X coordinate.
47077      * @param {number} canvasY - Canvas Y coordinate.
47078      * @param {HTMLElement} container - The viewer container.
47079      * @returns {Array<number>} 2D viewport coordinates.
47080      */
47081     ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
47082         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
47083         var viewportX = 2 * canvasX / canvasWidth - 1;
47084         var viewportY = 1 - 2 * canvasY / canvasHeight;
47085         return [viewportX, viewportY];
47086     };
47087     /**
47088      * Determines the width and height of the container in canvas coordinates.
47089      *
47090      * @param {HTMLElement} container - The viewer container.
47091      * @returns {Array<number>} 2D canvas coordinates.
47092      */
47093     ViewportCoords.prototype.containerToCanvas = function (container) {
47094         return [container.offsetWidth, container.offsetHeight];
47095     };
47096     /**
47097      * Determine basic distances from image to canvas corners.
47098      *
47099      * @description Transform origin and camera position needs to be the
47100      * equal for reliable return value.
47101      *
47102      * Determines the smallest basic distance for every side of the canvas.
47103      *
47104      * @param {Transform} transform - Transform of the node to unproject from.
47105      * @param {THREE.Camera} camera - Camera used in rendering.
47106      * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
47107      */
47108     ViewportCoords.prototype.getBasicDistances = function (transform, camera) {
47109         var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
47110         var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
47111         var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
47112         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
47113         var topBasicDistance = 0;
47114         var rightBasicDistance = 0;
47115         var bottomBasicDistance = 0;
47116         var leftBasicDistance = 0;
47117         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
47118             topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
47119                 -topLeftBasic[1] :
47120                 -topRightBasic[1];
47121         }
47122         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
47123             rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
47124                 topRightBasic[0] - 1 :
47125                 bottomRightBasic[0] - 1;
47126         }
47127         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
47128             bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
47129                 bottomRightBasic[1] - 1 :
47130                 bottomLeftBasic[1] - 1;
47131         }
47132         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
47133             leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
47134                 -bottomLeftBasic[0] :
47135                 -topLeftBasic[0];
47136         }
47137         return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
47138     };
47139     /**
47140      * Determine pixel distances from image to canvas corners.
47141      *
47142      * @description Transform origin and camera position needs to be the
47143      * equal for reliable return value.
47144      *
47145      * Determines the smallest pixel distance for every side of the canvas.
47146      *
47147      * @param {HTMLElement} container - The viewer container.
47148      * @param {Transform} transform - Transform of the node to unproject from.
47149      * @param {THREE.Camera} camera - Camera used in rendering.
47150      * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
47151      */
47152     ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) {
47153         var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
47154         var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
47155         var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
47156         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
47157         var topPixelDistance = 0;
47158         var rightPixelDistance = 0;
47159         var bottomPixelDistance = 0;
47160         var leftPixelDistance = 0;
47161         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
47162         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
47163             var basicX = topLeftBasic[1] > topRightBasic[1] ?
47164                 topLeftBasic[0] :
47165                 topRightBasic[0];
47166             var canvas = this.basicToCanvas(basicX, 0, container, transform, camera);
47167             topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
47168         }
47169         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
47170             var basicY = topRightBasic[0] < bottomRightBasic[0] ?
47171                 topRightBasic[1] :
47172                 bottomRightBasic[1];
47173             var canvas = this.basicToCanvas(1, basicY, container, transform, camera);
47174             rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
47175         }
47176         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
47177             var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
47178                 bottomRightBasic[0] :
47179                 bottomLeftBasic[0];
47180             var canvas = this.basicToCanvas(basicX, 1, container, transform, camera);
47181             bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
47182         }
47183         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
47184             var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
47185                 bottomLeftBasic[1] :
47186                 topLeftBasic[1];
47187             var canvas = this.basicToCanvas(0, basicY, container, transform, camera);
47188             leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
47189         }
47190         return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
47191     };
47192     /**
47193      * Determine if an event occured inside an element.
47194      *
47195      * @param {Event} event - Event containing clientX and clientY properties.
47196      * @param {HTMLElement} element - HTML element.
47197      * @returns {boolean} Value indicating if the event occured inside the element or not.
47198      */
47199     ViewportCoords.prototype.insideElement = function (event, element) {
47200         var clientRect = element.getBoundingClientRect();
47201         var minX = clientRect.left + element.clientLeft;
47202         var maxX = minX + element.clientWidth;
47203         var minY = clientRect.top + element.clientTop;
47204         var maxY = minY + element.clientHeight;
47205         return event.clientX > minX &&
47206             event.clientX < maxX &&
47207             event.clientY > minY &&
47208             event.clientY < maxY;
47209     };
47210     /**
47211      * Project 3D world coordinates to canvas coordinates.
47212      *
47213      * @param {Array<number>} point3D - 3D world coordinates.
47214      * @param {HTMLElement} container - The viewer container.
47215      * @param {THREE.Camera} camera - Camera used in rendering.
47216      * @returns {Array<number>} 2D canvas coordinates.
47217      */
47218     ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) {
47219         var viewport = this.projectToViewport(point3d, camera);
47220         var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
47221         return canvas;
47222     };
47223     /**
47224      * Project 3D world coordinates to canvas coordinates safely. If 3D
47225      * point is behind camera null will be returned.
47226      *
47227      * @param {Array<number>} point3D - 3D world coordinates.
47228      * @param {HTMLElement} container - The viewer container.
47229      * @param {THREE.Camera} camera - Camera used in rendering.
47230      * @returns {Array<number>} 2D canvas coordinates.
47231      */
47232     ViewportCoords.prototype.projectToCanvasSafe = function (point3d, container, camera) {
47233         var pointCamera = this.worldToCamera(point3d, camera);
47234         if (pointCamera[2] > 0) {
47235             return null;
47236         }
47237         var viewport = this.projectToViewport(point3d, camera);
47238         var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
47239         return canvas;
47240     };
47241     /**
47242      * Project 3D world coordinates to viewport coordinates.
47243      *
47244      * @param {Array<number>} point3D - 3D world coordinates.
47245      * @param {THREE.Camera} camera - Camera used in rendering.
47246      * @returns {Array<number>} 2D viewport coordinates.
47247      */
47248     ViewportCoords.prototype.projectToViewport = function (point3d, camera) {
47249         var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
47250             .project(camera);
47251         return [viewport.x, viewport.y];
47252     };
47253     /**
47254      * Uproject canvas coordinates to 3D world coordinates.
47255      *
47256      * @param {number} canvasX - Canvas X coordinate.
47257      * @param {number} canvasY - Canvas Y coordinate.
47258      * @param {HTMLElement} container - The viewer container.
47259      * @param {THREE.Camera} camera - Camera used in rendering.
47260      * @returns {Array<number>} 3D world coordinates.
47261      */
47262     ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) {
47263         var viewport = this.canvasToViewport(canvasX, canvasY, container);
47264         var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera);
47265         return point3d;
47266     };
47267     /**
47268      * Unproject viewport coordinates to 3D world coordinates.
47269      *
47270      * @param {number} viewportX - Viewport X coordinate.
47271      * @param {number} viewportY - Viewport Y coordinate.
47272      * @param {THREE.Camera} camera - Camera used in rendering.
47273      * @returns {Array<number>} 3D world coordinates.
47274      */
47275     ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) {
47276         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
47277             .unproject(camera);
47278         return point3d;
47279     };
47280     /**
47281      * Convert viewport coordinates to basic coordinates.
47282      *
47283      * @description Transform origin and camera position needs to be the
47284      * equal for reliable return value.
47285      *
47286      * @param {number} viewportX - Viewport X coordinate.
47287      * @param {number} viewportY - Viewport Y coordinate.
47288      * @param {Transform} transform - Transform of the node to unproject from.
47289      * @param {THREE.Camera} camera - Camera used in rendering.
47290      * @returns {Array<number>} 2D basic coordinates.
47291      */
47292     ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) {
47293         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
47294             .unproject(camera)
47295             .toArray();
47296         var basic = transform.projectBasic(point3d);
47297         return basic;
47298     };
47299     /**
47300      * Convert viewport coordinates to canvas coordinates.
47301      *
47302      * @param {number} viewportX - Viewport X coordinate.
47303      * @param {number} viewportY - Viewport Y coordinate.
47304      * @param {HTMLElement} container - The viewer container.
47305      * @returns {Array<number>} 2D canvas coordinates.
47306      */
47307     ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
47308         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
47309         var canvasX = canvasWidth * (viewportX + 1) / 2;
47310         var canvasY = -canvasHeight * (viewportY - 1) / 2;
47311         return [canvasX, canvasY];
47312     };
47313     /**
47314      * Convert 3D world coordinates to 3D camera coordinates.
47315      *
47316      * @param {number} point3D - 3D point in world coordinate system.
47317      * @param {THREE.Camera} camera - Camera used in rendering.
47318      * @returns {Array<number>} 3D camera coordinates.
47319      */
47320     ViewportCoords.prototype.worldToCamera = function (point3d, camera) {
47321         var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
47322             .applyMatrix4(camera.matrixWorldInverse);
47323         return pointCamera.toArray();
47324     };
47325     return ViewportCoords;
47326 }());
47327 exports.ViewportCoords = ViewportCoords;
47328 exports.default = ViewportCoords;
47329
47330
47331 },{"three":242}],415:[function(require,module,exports){
47332 "use strict";
47333 Object.defineProperty(exports, "__esModule", { value: true });
47334 /**
47335  * @class Filter
47336  *
47337  * @classdesc Represents a class for creating node filters. Implementation and
47338  * definitions based on https://github.com/mapbox/feature-filter.
47339  */
47340 var FilterCreator = /** @class */ (function () {
47341     function FilterCreator() {
47342     }
47343     /**
47344      * Create a filter from a filter expression.
47345      *
47346      * @description The following filters are supported:
47347      *
47348      * Comparison
47349      * `==`
47350      * `!=`
47351      * `<`
47352      * `<=`
47353      * `>`
47354      * `>=`
47355      *
47356      * Set membership
47357      * `in`
47358      * `!in`
47359      *
47360      * Combining
47361      * `all`
47362      *
47363      * @param {FilterExpression} filter - Comparison, set membership or combinding filter
47364      * expression.
47365      * @returns {FilterFunction} Function taking a node and returning a boolean that
47366      * indicates whether the node passed the test or not.
47367      */
47368     FilterCreator.prototype.createFilter = function (filter) {
47369         return new Function("node", "return " + this._compile(filter) + ";");
47370     };
47371     FilterCreator.prototype._compile = function (filter) {
47372         if (filter == null || filter.length <= 1) {
47373             return "true";
47374         }
47375         var operator = filter[0];
47376         var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
47377             operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
47378                 operator === ">" ||
47379                     operator === ">=" ||
47380                     operator === "<" ||
47381                     operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
47382                     operator === "in" ?
47383                         this._compileInOp(filter[1], filter.slice(2)) :
47384                         operator === "!in" ?
47385                             this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
47386                             operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
47387                                 "true";
47388         return "(" + operation + ")";
47389     };
47390     FilterCreator.prototype._compare = function (a, b) {
47391         return a < b ? -1 : a > b ? 1 : 0;
47392     };
47393     FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
47394         var left = this._compilePropertyReference(property);
47395         var right = JSON.stringify(value);
47396         return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
47397     };
47398     FilterCreator.prototype._compileInOp = function (property, values) {
47399         var compare = this._compare;
47400         var left = JSON.stringify(values.sort(compare));
47401         var right = this._compilePropertyReference(property);
47402         return left + ".indexOf(" + right + ")!==-1";
47403     };
47404     FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
47405         var compile = this._compile.bind(this);
47406         return filters.map(compile).join(operator);
47407     };
47408     FilterCreator.prototype._compileNegation = function (expression) {
47409         return "!(" + expression + ")";
47410     };
47411     FilterCreator.prototype._compilePropertyReference = function (property) {
47412         return "node[" + JSON.stringify(property) + "]";
47413     };
47414     return FilterCreator;
47415 }());
47416 exports.FilterCreator = FilterCreator;
47417 exports.default = FilterCreator;
47418
47419 },{}],416:[function(require,module,exports){
47420 "use strict";
47421 Object.defineProperty(exports, "__esModule", { value: true });
47422 var rxjs_1 = require("rxjs");
47423 var operators_1 = require("rxjs/operators");
47424 var rbush = require("rbush");
47425 var Edge_1 = require("../Edge");
47426 var Error_1 = require("../Error");
47427 var Graph_1 = require("../Graph");
47428 /**
47429  * @class Graph
47430  *
47431  * @classdesc Represents a graph of nodes with edges.
47432  */
47433 var Graph = /** @class */ (function () {
47434     /**
47435      * Create a new graph instance.
47436      *
47437      * @param {APIv3} [apiV3] - API instance for retrieving data.
47438      * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
47439      * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
47440      * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
47441      * @param {FilterCreator} [filterCreator] - Instance for  filter creation.
47442      * @param {IGraphConfiguration} [configuration] - Configuration struct.
47443      */
47444     function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
47445         this._apiV3 = apiV3;
47446         this._cachedNodes = {};
47447         this._cachedNodeTiles = {};
47448         this._cachedSequenceNodes = {};
47449         this._cachedSpatialEdges = {};
47450         this._cachedTiles = {};
47451         this._cachingFill$ = {};
47452         this._cachingFull$ = {};
47453         this._cachingSequenceNodes$ = {};
47454         this._cachingSequences$ = {};
47455         this._cachingSpatialArea$ = {};
47456         this._cachingTiles$ = {};
47457         this._changed$ = new rxjs_1.Subject();
47458         this._defaultAlt = 2;
47459         this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
47460         this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
47461         this._filter = this._filterCreator.createFilter(undefined);
47462         this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
47463         this._configuration = configuration != null ?
47464             configuration :
47465             {
47466                 maxSequences: 50,
47467                 maxUnusedNodes: 100,
47468                 maxUnusedPreStoredNodes: 30,
47469                 maxUnusedTiles: 20,
47470             };
47471         this._nodes = {};
47472         this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
47473         this._nodeIndexTiles = {};
47474         this._nodeToTile = {};
47475         this._preStored = {};
47476         this._requiredNodeTiles = {};
47477         this._requiredSpatialArea = {};
47478         this._sequences = {};
47479         this._tilePrecision = 7;
47480         this._tileThreshold = 20;
47481     }
47482     Object.defineProperty(Graph.prototype, "changed$", {
47483         /**
47484          * Get changed$.
47485          *
47486          * @returns {Observable<Graph>} Observable emitting
47487          * the graph every time it has changed.
47488          */
47489         get: function () {
47490             return this._changed$;
47491         },
47492         enumerable: true,
47493         configurable: true
47494     });
47495     /**
47496      * Caches the full node data for all images within a bounding
47497      * box.
47498      *
47499      * @description The node assets are not cached.
47500      *
47501      * @param {ILatLon} sw - South west corner of bounding box.
47502      * @param {ILatLon} ne - North east corner of bounding box.
47503      * @returns {Observable<Graph>} Observable emitting the full
47504      * nodes in the bounding box.
47505      */
47506     Graph.prototype.cacheBoundingBox$ = function (sw, ne) {
47507         var _this = this;
47508         var cacheTiles$ = this._graphCalculator.encodeHsFromBoundingBox(sw, ne)
47509             .filter(function (h) {
47510             return !(h in _this._cachedTiles);
47511         })
47512             .map(function (h) {
47513             return h in _this._cachingTiles$ ?
47514                 _this._cachingTiles$[h] :
47515                 _this._cacheTile$(h);
47516         });
47517         if (cacheTiles$.length === 0) {
47518             cacheTiles$.push(rxjs_1.of(this));
47519         }
47520         return rxjs_1.from(cacheTiles$).pipe(operators_1.mergeAll(), operators_1.last(), operators_1.mergeMap(function (graph) {
47521             var nodes = _this._nodeIndex
47522                 .search({
47523                 maxX: ne.lat,
47524                 maxY: ne.lon,
47525                 minX: sw.lat,
47526                 minY: sw.lon,
47527             })
47528                 .map(function (item) {
47529                 return item.node;
47530             });
47531             var fullNodes = [];
47532             var coreNodes = [];
47533             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
47534                 var node = nodes_1[_i];
47535                 if (node.full) {
47536                     fullNodes.push(node);
47537                 }
47538                 else {
47539                     coreNodes.push(node.key);
47540                 }
47541             }
47542             var coreNodeBatches = [];
47543             var batchSize = 200;
47544             while (coreNodes.length > 0) {
47545                 coreNodeBatches.push(coreNodes.splice(0, batchSize));
47546             }
47547             var fullNodes$ = rxjs_1.of(fullNodes);
47548             var fillNodes$ = coreNodeBatches
47549                 .map(function (batch) {
47550                 return _this._apiV3.imageByKeyFill$(batch).pipe(operators_1.map(function (imageByKeyFill) {
47551                     var filledNodes = [];
47552                     for (var fillKey in imageByKeyFill) {
47553                         if (!imageByKeyFill.hasOwnProperty(fillKey)) {
47554                             continue;
47555                         }
47556                         if (_this.hasNode(fillKey)) {
47557                             var node = _this.getNode(fillKey);
47558                             if (!node.full) {
47559                                 _this._makeFull(node, imageByKeyFill[fillKey]);
47560                             }
47561                             filledNodes.push(node);
47562                         }
47563                     }
47564                     return filledNodes;
47565                 }));
47566             });
47567             return rxjs_1.merge(fullNodes$, rxjs_1.from(fillNodes$).pipe(operators_1.mergeAll()));
47568         }), operators_1.reduce(function (acc, value) {
47569             return acc.concat(value);
47570         }));
47571     };
47572     /**
47573      * Retrieve and cache node fill properties.
47574      *
47575      * @param {string} key - Key of node to fill.
47576      * @returns {Observable<Graph>} Observable emitting the graph
47577      * when the node has been updated.
47578      * @throws {GraphMapillaryError} When the operation is not valid on the
47579      * current graph.
47580      */
47581     Graph.prototype.cacheFill$ = function (key) {
47582         var _this = this;
47583         if (key in this._cachingFull$) {
47584             throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
47585         }
47586         if (!this.hasNode(key)) {
47587             throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
47588         }
47589         if (key in this._cachingFill$) {
47590             return this._cachingFill$[key];
47591         }
47592         var node = this.getNode(key);
47593         if (node.full) {
47594             throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
47595         }
47596         this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key]).pipe(operators_1.tap(function (imageByKeyFill) {
47597             if (!node.full) {
47598                 _this._makeFull(node, imageByKeyFill[key]);
47599             }
47600             delete _this._cachingFill$[key];
47601         }), operators_1.map(function (imageByKeyFill) {
47602             return _this;
47603         }), operators_1.finalize(function () {
47604             if (key in _this._cachingFill$) {
47605                 delete _this._cachingFill$[key];
47606             }
47607             _this._changed$.next(_this);
47608         }), operators_1.publish(), operators_1.refCount());
47609         return this._cachingFill$[key];
47610     };
47611     /**
47612      * Retrieve and cache full node properties.
47613      *
47614      * @param {string} key - Key of node to fill.
47615      * @returns {Observable<Graph>} Observable emitting the graph
47616      * when the node has been updated.
47617      * @throws {GraphMapillaryError} When the operation is not valid on the
47618      * current graph.
47619      */
47620     Graph.prototype.cacheFull$ = function (key) {
47621         var _this = this;
47622         if (key in this._cachingFull$) {
47623             return this._cachingFull$[key];
47624         }
47625         if (this.hasNode(key)) {
47626             throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
47627         }
47628         this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key]).pipe(operators_1.tap(function (imageByKeyFull) {
47629             var fn = imageByKeyFull[key];
47630             if (_this.hasNode(key)) {
47631                 var node = _this.getNode(key);
47632                 if (!node.full) {
47633                     _this._makeFull(node, fn);
47634                 }
47635             }
47636             else {
47637                 if (fn.sequence_key == null) {
47638                     throw new Error_1.GraphMapillaryError("Node has no sequence key (" + key + ").");
47639                 }
47640                 var node = new Graph_1.Node(fn);
47641                 _this._makeFull(node, fn);
47642                 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
47643                 _this._preStore(h, node);
47644                 _this._setNode(node);
47645                 delete _this._cachingFull$[key];
47646             }
47647         }), operators_1.map(function (imageByKeyFull) {
47648             return _this;
47649         }), operators_1.finalize(function () {
47650             if (key in _this._cachingFull$) {
47651                 delete _this._cachingFull$[key];
47652             }
47653             _this._changed$.next(_this);
47654         }), operators_1.publish(), operators_1.refCount());
47655         return this._cachingFull$[key];
47656     };
47657     /**
47658      * Retrieve and cache a node sequence.
47659      *
47660      * @param {string} key - Key of node for which to retrieve sequence.
47661      * @returns {Observable<Graph>} Observable emitting the graph
47662      * when the sequence has been retrieved.
47663      * @throws {GraphMapillaryError} When the operation is not valid on the
47664      * current graph.
47665      */
47666     Graph.prototype.cacheNodeSequence$ = function (key) {
47667         if (!this.hasNode(key)) {
47668             throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
47669         }
47670         var node = this.getNode(key);
47671         if (node.sequenceKey in this._sequences) {
47672             throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
47673         }
47674         return this._cacheSequence$(node.sequenceKey);
47675     };
47676     /**
47677      * Retrieve and cache a sequence.
47678      *
47679      * @param {string} sequenceKey - Key of sequence to cache.
47680      * @returns {Observable<Graph>} Observable emitting the graph
47681      * when the sequence has been retrieved.
47682      * @throws {GraphMapillaryError} When the operation is not valid on the
47683      * current graph.
47684      */
47685     Graph.prototype.cacheSequence$ = function (sequenceKey) {
47686         if (sequenceKey in this._sequences) {
47687             throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
47688         }
47689         return this._cacheSequence$(sequenceKey);
47690     };
47691     /**
47692      * Cache sequence edges for a node.
47693      *
47694      * @param {string} key - Key of node.
47695      * @throws {GraphMapillaryError} When the operation is not valid on the
47696      * current graph.
47697      */
47698     Graph.prototype.cacheSequenceEdges = function (key) {
47699         var node = this.getNode(key);
47700         if (!(node.sequenceKey in this._sequences)) {
47701             throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
47702         }
47703         var sequence = this._sequences[node.sequenceKey].sequence;
47704         var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
47705         node.cacheSequenceEdges(edges);
47706     };
47707     /**
47708      * Retrieve and cache full nodes for all keys in a sequence.
47709      *
47710      * @param {string} sequenceKey - Key of sequence.
47711      * @param {string} referenceNodeKey - Key of node to use as reference
47712      * for optimized caching.
47713      * @returns {Observable<Graph>} Observable emitting the graph
47714      * when the nodes of the sequence has been cached.
47715      */
47716     Graph.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
47717         var _this = this;
47718         if (!this.hasSequence(sequenceKey)) {
47719             throw new Error_1.GraphMapillaryError("Cannot cache sequence nodes of sequence that does not exist in graph (" + sequenceKey + ").");
47720         }
47721         if (this.hasSequenceNodes(sequenceKey)) {
47722             throw new Error_1.GraphMapillaryError("Sequence nodes already cached (" + sequenceKey + ").");
47723         }
47724         var sequence = this.getSequence(sequenceKey);
47725         if (sequence.key in this._cachingSequenceNodes$) {
47726             return this._cachingSequenceNodes$[sequence.key];
47727         }
47728         var batches = [];
47729         var keys = sequence.keys.slice();
47730         var referenceBatchSize = 50;
47731         if (!!referenceNodeKey && keys.length > referenceBatchSize) {
47732             var referenceIndex = keys.indexOf(referenceNodeKey);
47733             var startIndex = Math.max(0, Math.min(referenceIndex - referenceBatchSize / 2, keys.length - referenceBatchSize));
47734             batches.push(keys.splice(startIndex, referenceBatchSize));
47735         }
47736         var batchSize = 200;
47737         while (keys.length > 0) {
47738             batches.push(keys.splice(0, batchSize));
47739         }
47740         var batchesToCache = batches.length;
47741         var sequenceNodes$ = rxjs_1.from(batches).pipe(operators_1.mergeMap(function (batch) {
47742             return _this._apiV3.imageByKeyFull$(batch).pipe(operators_1.tap(function (imageByKeyFull) {
47743                 for (var fullKey in imageByKeyFull) {
47744                     if (!imageByKeyFull.hasOwnProperty(fullKey)) {
47745                         continue;
47746                     }
47747                     var fn = imageByKeyFull[fullKey];
47748                     if (_this.hasNode(fullKey)) {
47749                         var node = _this.getNode(fn.key);
47750                         if (!node.full) {
47751                             _this._makeFull(node, fn);
47752                         }
47753                     }
47754                     else {
47755                         if (fn.sequence_key == null) {
47756                             console.warn("Sequence missing, discarding node (" + fn.key + ")");
47757                         }
47758                         var node = new Graph_1.Node(fn);
47759                         _this._makeFull(node, fn);
47760                         var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
47761                         _this._preStore(h, node);
47762                         _this._setNode(node);
47763                     }
47764                 }
47765                 batchesToCache--;
47766             }), operators_1.map(function (imageByKeyFull) {
47767                 return _this;
47768             }));
47769         }, 6), operators_1.last(), operators_1.finalize(function () {
47770             delete _this._cachingSequenceNodes$[sequence.key];
47771             if (batchesToCache === 0) {
47772                 _this._cachedSequenceNodes[sequence.key] = true;
47773             }
47774         }), operators_1.publish(), operators_1.refCount());
47775         this._cachingSequenceNodes$[sequence.key] = sequenceNodes$;
47776         return sequenceNodes$;
47777     };
47778     /**
47779      * Retrieve and cache full nodes for a node spatial area.
47780      *
47781      * @param {string} key - Key of node for which to retrieve sequence.
47782      * @returns {Observable<Graph>} Observable emitting the graph
47783      * when the nodes in the spatial area has been made full.
47784      * @throws {GraphMapillaryError} When the operation is not valid on the
47785      * current graph.
47786      */
47787     Graph.prototype.cacheSpatialArea$ = function (key) {
47788         var _this = this;
47789         if (!this.hasNode(key)) {
47790             throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
47791         }
47792         if (key in this._cachedSpatialEdges) {
47793             throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
47794         }
47795         if (!(key in this._requiredSpatialArea)) {
47796             throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
47797         }
47798         var spatialArea = this._requiredSpatialArea[key];
47799         if (Object.keys(spatialArea.cacheNodes).length === 0) {
47800             throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
47801         }
47802         if (key in this._cachingSpatialArea$) {
47803             return this._cachingSpatialArea$[key];
47804         }
47805         var batches = [];
47806         while (spatialArea.cacheKeys.length > 0) {
47807             batches.push(spatialArea.cacheKeys.splice(0, 200));
47808         }
47809         var batchesToCache = batches.length;
47810         var spatialNodes$ = [];
47811         var _loop_1 = function (batch) {
47812             var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch).pipe(operators_1.tap(function (imageByKeyFill) {
47813                 for (var fillKey in imageByKeyFill) {
47814                     if (!imageByKeyFill.hasOwnProperty(fillKey)) {
47815                         continue;
47816                     }
47817                     var spatialNode = spatialArea.cacheNodes[fillKey];
47818                     if (spatialNode.full) {
47819                         delete spatialArea.cacheNodes[fillKey];
47820                         continue;
47821                     }
47822                     var fillNode = imageByKeyFill[fillKey];
47823                     _this._makeFull(spatialNode, fillNode);
47824                     delete spatialArea.cacheNodes[fillKey];
47825                 }
47826                 if (--batchesToCache === 0) {
47827                     delete _this._cachingSpatialArea$[key];
47828                 }
47829             }), operators_1.map(function (imageByKeyFill) {
47830                 return _this;
47831             }), operators_1.catchError(function (error) {
47832                 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
47833                     var batchKey = batch_1[_i];
47834                     if (batchKey in spatialArea.all) {
47835                         delete spatialArea.all[batchKey];
47836                     }
47837                     if (batchKey in spatialArea.cacheNodes) {
47838                         delete spatialArea.cacheNodes[batchKey];
47839                     }
47840                 }
47841                 if (--batchesToCache === 0) {
47842                     delete _this._cachingSpatialArea$[key];
47843                 }
47844                 throw error;
47845             }), operators_1.finalize(function () {
47846                 if (Object.keys(spatialArea.cacheNodes).length === 0) {
47847                     _this._changed$.next(_this);
47848                 }
47849             }), operators_1.publish(), operators_1.refCount());
47850             spatialNodes$.push(spatialNodeBatch$);
47851         };
47852         var this_1 = this;
47853         for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
47854             var batch = batches_1[_i];
47855             _loop_1(batch);
47856         }
47857         this._cachingSpatialArea$[key] = spatialNodes$;
47858         return spatialNodes$;
47859     };
47860     /**
47861      * Cache spatial edges for a node.
47862      *
47863      * @param {string} key - Key of node.
47864      * @throws {GraphMapillaryError} When the operation is not valid on the
47865      * current graph.
47866      */
47867     Graph.prototype.cacheSpatialEdges = function (key) {
47868         if (key in this._cachedSpatialEdges) {
47869             throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
47870         }
47871         var node = this.getNode(key);
47872         var sequence = this._sequences[node.sequenceKey].sequence;
47873         var fallbackKeys = [];
47874         var prevKey = sequence.findPrevKey(node.key);
47875         if (prevKey != null) {
47876             fallbackKeys.push(prevKey);
47877         }
47878         var nextKey = sequence.findNextKey(node.key);
47879         if (nextKey != null) {
47880             fallbackKeys.push(nextKey);
47881         }
47882         var allSpatialNodes = this._requiredSpatialArea[key].all;
47883         var potentialNodes = [];
47884         var filter = this._filter;
47885         for (var spatialNodeKey in allSpatialNodes) {
47886             if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
47887                 continue;
47888             }
47889             var spatialNode = allSpatialNodes[spatialNodeKey];
47890             if (filter(spatialNode)) {
47891                 potentialNodes.push(spatialNode);
47892             }
47893         }
47894         var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
47895         var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
47896         edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
47897         edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
47898         edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
47899         edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
47900         node.cacheSpatialEdges(edges);
47901         this._cachedSpatialEdges[key] = node;
47902         delete this._requiredSpatialArea[key];
47903         delete this._cachedNodeTiles[key];
47904     };
47905     /**
47906      * Retrieve and cache geohash tiles for a node.
47907      *
47908      * @param {string} key - Key of node for which to retrieve tiles.
47909      * @returns {Array<Observable<Graph>>} Array of observables emitting
47910      * the graph for each tile required for the node has been cached.
47911      * @throws {GraphMapillaryError} When the operation is not valid on the
47912      * current graph.
47913      */
47914     Graph.prototype.cacheTiles$ = function (key) {
47915         var _this = this;
47916         if (key in this._cachedNodeTiles) {
47917             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
47918         }
47919         if (key in this._cachedSpatialEdges) {
47920             throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
47921         }
47922         if (!(key in this._requiredNodeTiles)) {
47923             throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
47924         }
47925         var nodeTiles = this._requiredNodeTiles[key];
47926         if (nodeTiles.cache.length === 0 &&
47927             nodeTiles.caching.length === 0) {
47928             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
47929         }
47930         if (!this.hasNode(key)) {
47931             throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
47932         }
47933         var hs = nodeTiles.cache.slice();
47934         nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
47935         nodeTiles.cache = [];
47936         var cacheTiles$ = [];
47937         var _loop_2 = function (h) {
47938             var cacheTile$ = h in this_2._cachingTiles$ ?
47939                 this_2._cachingTiles$[h] :
47940                 this_2._cacheTile$(h);
47941             cacheTiles$.push(cacheTile$.pipe(operators_1.tap(function (graph) {
47942                 var index = nodeTiles.caching.indexOf(h);
47943                 if (index > -1) {
47944                     nodeTiles.caching.splice(index, 1);
47945                 }
47946                 if (nodeTiles.caching.length === 0 &&
47947                     nodeTiles.cache.length === 0) {
47948                     delete _this._requiredNodeTiles[key];
47949                     _this._cachedNodeTiles[key] = true;
47950                 }
47951             }), operators_1.catchError(function (error) {
47952                 var index = nodeTiles.caching.indexOf(h);
47953                 if (index > -1) {
47954                     nodeTiles.caching.splice(index, 1);
47955                 }
47956                 if (nodeTiles.caching.length === 0 &&
47957                     nodeTiles.cache.length === 0) {
47958                     delete _this._requiredNodeTiles[key];
47959                     _this._cachedNodeTiles[key] = true;
47960                 }
47961                 throw error;
47962             }), operators_1.finalize(function () {
47963                 _this._changed$.next(_this);
47964             }), operators_1.publish(), operators_1.refCount()));
47965         };
47966         var this_2 = this;
47967         for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
47968             var h = _a[_i];
47969             _loop_2(h);
47970         }
47971         return cacheTiles$;
47972     };
47973     /**
47974      * Initialize the cache for a node.
47975      *
47976      * @param {string} key - Key of node.
47977      * @throws {GraphMapillaryError} When the operation is not valid on the
47978      * current graph.
47979      */
47980     Graph.prototype.initializeCache = function (key) {
47981         if (key in this._cachedNodes) {
47982             throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
47983         }
47984         var node = this.getNode(key);
47985         node.initializeCache(new Graph_1.NodeCache());
47986         var accessed = new Date().getTime();
47987         this._cachedNodes[key] = { accessed: accessed, node: node };
47988         this._updateCachedTileAccess(key, accessed);
47989     };
47990     /**
47991      * Get a value indicating if the graph is fill caching a node.
47992      *
47993      * @param {string} key - Key of node.
47994      * @returns {boolean} Value indicating if the node is being fill cached.
47995      */
47996     Graph.prototype.isCachingFill = function (key) {
47997         return key in this._cachingFill$;
47998     };
47999     /**
48000      * Get a value indicating if the graph is fully caching a node.
48001      *
48002      * @param {string} key - Key of node.
48003      * @returns {boolean} Value indicating if the node is being fully cached.
48004      */
48005     Graph.prototype.isCachingFull = function (key) {
48006         return key in this._cachingFull$;
48007     };
48008     /**
48009      * Get a value indicating if the graph is caching a sequence of a node.
48010      *
48011      * @param {string} key - Key of node.
48012      * @returns {boolean} Value indicating if the sequence of a node is
48013      * being cached.
48014      */
48015     Graph.prototype.isCachingNodeSequence = function (key) {
48016         var node = this.getNode(key);
48017         return node.sequenceKey in this._cachingSequences$;
48018     };
48019     /**
48020      * Get a value indicating if the graph is caching a sequence.
48021      *
48022      * @param {string} sequenceKey - Key of sequence.
48023      * @returns {boolean} Value indicating if the sequence is
48024      * being cached.
48025      */
48026     Graph.prototype.isCachingSequence = function (sequenceKey) {
48027         return sequenceKey in this._cachingSequences$;
48028     };
48029     /**
48030      * Get a value indicating if the graph is caching sequence nodes.
48031      *
48032      * @param {string} sequenceKey - Key of sequence.
48033      * @returns {boolean} Value indicating if the sequence nodes are
48034      * being cached.
48035      */
48036     Graph.prototype.isCachingSequenceNodes = function (sequenceKey) {
48037         return sequenceKey in this._cachingSequenceNodes$;
48038     };
48039     /**
48040      * Get a value indicating if the graph is caching the tiles
48041      * required for calculating spatial edges of a node.
48042      *
48043      * @param {string} key - Key of node.
48044      * @returns {boolean} Value indicating if the tiles of
48045      * a node are being cached.
48046      */
48047     Graph.prototype.isCachingTiles = function (key) {
48048         return key in this._requiredNodeTiles &&
48049             this._requiredNodeTiles[key].cache.length === 0 &&
48050             this._requiredNodeTiles[key].caching.length > 0;
48051     };
48052     /**
48053      * Get a value indicating if the cache has been initialized
48054      * for a node.
48055      *
48056      * @param {string} key - Key of node.
48057      * @returns {boolean} Value indicating if the cache has been
48058      * initialized for a node.
48059      */
48060     Graph.prototype.hasInitializedCache = function (key) {
48061         return key in this._cachedNodes;
48062     };
48063     /**
48064      * Get a value indicating if a node exist in the graph.
48065      *
48066      * @param {string} key - Key of node.
48067      * @returns {boolean} Value indicating if a node exist in the graph.
48068      */
48069     Graph.prototype.hasNode = function (key) {
48070         var accessed = new Date().getTime();
48071         this._updateCachedNodeAccess(key, accessed);
48072         this._updateCachedTileAccess(key, accessed);
48073         return key in this._nodes;
48074     };
48075     /**
48076      * Get a value indicating if a node sequence exist in the graph.
48077      *
48078      * @param {string} key - Key of node.
48079      * @returns {boolean} Value indicating if a node sequence exist
48080      * in the graph.
48081      */
48082     Graph.prototype.hasNodeSequence = function (key) {
48083         var node = this.getNode(key);
48084         var sequenceKey = node.sequenceKey;
48085         var hasNodeSequence = sequenceKey in this._sequences;
48086         if (hasNodeSequence) {
48087             this._sequences[sequenceKey].accessed = new Date().getTime();
48088         }
48089         return hasNodeSequence;
48090     };
48091     /**
48092      * Get a value indicating if a sequence exist in the graph.
48093      *
48094      * @param {string} sequenceKey - Key of sequence.
48095      * @returns {boolean} Value indicating if a sequence exist
48096      * in the graph.
48097      */
48098     Graph.prototype.hasSequence = function (sequenceKey) {
48099         var hasSequence = sequenceKey in this._sequences;
48100         if (hasSequence) {
48101             this._sequences[sequenceKey].accessed = new Date().getTime();
48102         }
48103         return hasSequence;
48104     };
48105     /**
48106      * Get a value indicating if sequence nodes has been cached in the graph.
48107      *
48108      * @param {string} sequenceKey - Key of sequence.
48109      * @returns {boolean} Value indicating if a sequence nodes has been
48110      * cached in the graph.
48111      */
48112     Graph.prototype.hasSequenceNodes = function (sequenceKey) {
48113         return sequenceKey in this._cachedSequenceNodes;
48114     };
48115     /**
48116      * Get a value indicating if the graph has fully cached
48117      * all nodes in the spatial area of a node.
48118      *
48119      * @param {string} key - Key of node.
48120      * @returns {boolean} Value indicating if the spatial area
48121      * of a node has been cached.
48122      */
48123     Graph.prototype.hasSpatialArea = function (key) {
48124         if (!this.hasNode(key)) {
48125             throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
48126         }
48127         if (key in this._cachedSpatialEdges) {
48128             return true;
48129         }
48130         if (key in this._requiredSpatialArea) {
48131             return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
48132         }
48133         var node = this.getNode(key);
48134         var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
48135         var spatialItems = this._nodeIndex.search({
48136             maxX: bbox[1].lat,
48137             maxY: bbox[1].lon,
48138             minX: bbox[0].lat,
48139             minY: bbox[0].lon,
48140         });
48141         var spatialNodes = {
48142             all: {},
48143             cacheKeys: [],
48144             cacheNodes: {},
48145         };
48146         for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
48147             var spatialItem = spatialItems_1[_i];
48148             spatialNodes.all[spatialItem.node.key] = spatialItem.node;
48149             if (!spatialItem.node.full) {
48150                 spatialNodes.cacheKeys.push(spatialItem.node.key);
48151                 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
48152             }
48153         }
48154         this._requiredSpatialArea[key] = spatialNodes;
48155         return spatialNodes.cacheKeys.length === 0;
48156     };
48157     /**
48158      * Get a value indicating if the graph has a tiles required
48159      * for a node.
48160      *
48161      * @param {string} key - Key of node.
48162      * @returns {boolean} Value indicating if the the tiles required
48163      * by a node has been cached.
48164      */
48165     Graph.prototype.hasTiles = function (key) {
48166         var _this = this;
48167         if (key in this._cachedNodeTiles) {
48168             return true;
48169         }
48170         if (key in this._cachedSpatialEdges) {
48171             return true;
48172         }
48173         if (!this.hasNode(key)) {
48174             throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
48175         }
48176         var nodeTiles = { cache: [], caching: [] };
48177         if (!(key in this._requiredNodeTiles)) {
48178             var node = this.getNode(key);
48179             nodeTiles.cache = this._graphCalculator
48180                 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
48181                 .filter(function (h) {
48182                 return !(h in _this._cachedTiles);
48183             });
48184             if (nodeTiles.cache.length > 0) {
48185                 this._requiredNodeTiles[key] = nodeTiles;
48186             }
48187         }
48188         else {
48189             nodeTiles = this._requiredNodeTiles[key];
48190         }
48191         return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
48192     };
48193     /**
48194      * Get a node.
48195      *
48196      * @param {string} key - Key of node.
48197      * @returns {Node} Retrieved node.
48198      */
48199     Graph.prototype.getNode = function (key) {
48200         var accessed = new Date().getTime();
48201         this._updateCachedNodeAccess(key, accessed);
48202         this._updateCachedTileAccess(key, accessed);
48203         return this._nodes[key];
48204     };
48205     /**
48206      * Get a sequence.
48207      *
48208      * @param {string} sequenceKey - Key of sequence.
48209      * @returns {Node} Retrieved sequence.
48210      */
48211     Graph.prototype.getSequence = function (sequenceKey) {
48212         var sequenceAccess = this._sequences[sequenceKey];
48213         sequenceAccess.accessed = new Date().getTime();
48214         return sequenceAccess.sequence;
48215     };
48216     /**
48217      * Reset all spatial edges of the graph nodes.
48218      */
48219     Graph.prototype.resetSpatialEdges = function () {
48220         var cachedKeys = Object.keys(this._cachedSpatialEdges);
48221         for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
48222             var cachedKey = cachedKeys_1[_i];
48223             var node = this._cachedSpatialEdges[cachedKey];
48224             node.resetSpatialEdges();
48225             delete this._cachedSpatialEdges[cachedKey];
48226         }
48227     };
48228     /**
48229      * Reset the complete graph but keep the nodes corresponding
48230      * to the supplied keys. All other nodes will be disposed.
48231      *
48232      * @param {Array<string>} keepKeys - Keys for nodes to keep
48233      * in graph after reset.
48234      */
48235     Graph.prototype.reset = function (keepKeys) {
48236         var nodes = [];
48237         for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
48238             var key = keepKeys_1[_i];
48239             if (!this.hasNode(key)) {
48240                 throw new Error("Node does not exist " + key);
48241             }
48242             var node = this.getNode(key);
48243             node.resetSequenceEdges();
48244             node.resetSpatialEdges();
48245             nodes.push(node);
48246         }
48247         for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
48248             var cachedKey = _b[_a];
48249             if (keepKeys.indexOf(cachedKey) !== -1) {
48250                 continue;
48251             }
48252             this._cachedNodes[cachedKey].node.dispose();
48253             delete this._cachedNodes[cachedKey];
48254         }
48255         this._cachedNodeTiles = {};
48256         this._cachedSpatialEdges = {};
48257         this._cachedTiles = {};
48258         this._cachingFill$ = {};
48259         this._cachingFull$ = {};
48260         this._cachingSequences$ = {};
48261         this._cachingSpatialArea$ = {};
48262         this._cachingTiles$ = {};
48263         this._nodes = {};
48264         this._nodeToTile = {};
48265         this._preStored = {};
48266         for (var _c = 0, nodes_2 = nodes; _c < nodes_2.length; _c++) {
48267             var node = nodes_2[_c];
48268             this._nodes[node.key] = node;
48269             var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
48270             this._preStore(h, node);
48271         }
48272         this._requiredNodeTiles = {};
48273         this._requiredSpatialArea = {};
48274         this._sequences = {};
48275         this._nodeIndexTiles = {};
48276         this._nodeIndex.clear();
48277     };
48278     /**
48279      * Set the spatial node filter.
48280      *
48281      * @param {FilterExpression} filter - Filter expression to be applied
48282      * when calculating spatial edges.
48283      */
48284     Graph.prototype.setFilter = function (filter) {
48285         this._filter = this._filterCreator.createFilter(filter);
48286     };
48287     /**
48288      * Uncache the graph according to the graph configuration.
48289      *
48290      * @description Uncaches unused tiles, unused nodes and
48291      * sequences according to the numbers specified in the
48292      * graph configuration. Sequences does not have a direct
48293      * reference to either tiles or nodes and may be uncached
48294      * even if they are related to the nodes that should be kept.
48295      *
48296      * @param {Array<string>} keepKeys - Keys of nodes to keep in
48297      * graph unrelated to last access. Tiles related to those keys
48298      * will also be kept in graph.
48299      * @param {string} keepSequenceKey - Optional key of sequence
48300      * for which the belonging nodes should not be disposed or
48301      * removed from the graph. These nodes may still be uncached if
48302      * not specified in keep keys param.
48303      */
48304     Graph.prototype.uncache = function (keepKeys, keepSequenceKey) {
48305         var keysInUse = {};
48306         this._addNewKeys(keysInUse, this._cachingFull$);
48307         this._addNewKeys(keysInUse, this._cachingFill$);
48308         this._addNewKeys(keysInUse, this._cachingSpatialArea$);
48309         this._addNewKeys(keysInUse, this._requiredNodeTiles);
48310         this._addNewKeys(keysInUse, this._requiredSpatialArea);
48311         for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
48312             var key = keepKeys_2[_i];
48313             if (key in keysInUse) {
48314                 continue;
48315             }
48316             keysInUse[key] = true;
48317         }
48318         var keepHs = {};
48319         for (var key in keysInUse) {
48320             if (!keysInUse.hasOwnProperty(key)) {
48321                 continue;
48322             }
48323             var node = this._nodes[key];
48324             var nodeHs = this._graphCalculator.encodeHs(node.latLon);
48325             for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
48326                 var nodeH = nodeHs_1[_a];
48327                 if (!(nodeH in keepHs)) {
48328                     keepHs[nodeH] = true;
48329                 }
48330             }
48331         }
48332         var potentialHs = [];
48333         for (var h in this._cachedTiles) {
48334             if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
48335                 continue;
48336             }
48337             potentialHs.push([h, this._cachedTiles[h]]);
48338         }
48339         var uncacheHs = potentialHs
48340             .sort(function (h1, h2) {
48341             return h2[1].accessed - h1[1].accessed;
48342         })
48343             .slice(this._configuration.maxUnusedTiles)
48344             .map(function (h) {
48345             return h[0];
48346         });
48347         for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
48348             var uncacheH = uncacheHs_1[_b];
48349             this._uncacheTile(uncacheH, keepSequenceKey);
48350         }
48351         var potentialPreStored = [];
48352         var nonCachedPreStored = [];
48353         for (var h in this._preStored) {
48354             if (!this._preStored.hasOwnProperty(h) || h in this._cachingTiles$) {
48355                 continue;
48356             }
48357             var prestoredNodes = this._preStored[h];
48358             for (var key in prestoredNodes) {
48359                 if (!prestoredNodes.hasOwnProperty(key) || key in keysInUse) {
48360                     continue;
48361                 }
48362                 if (prestoredNodes[key].sequenceKey === keepSequenceKey) {
48363                     continue;
48364                 }
48365                 if (key in this._cachedNodes) {
48366                     potentialPreStored.push([this._cachedNodes[key], h]);
48367                 }
48368                 else {
48369                     nonCachedPreStored.push([key, h]);
48370                 }
48371             }
48372         }
48373         var uncachePreStored = potentialPreStored
48374             .sort(function (_a, _b) {
48375             var na1 = _a[0], h1 = _a[1];
48376             var na2 = _b[0], h2 = _b[1];
48377             return na2.accessed - na1.accessed;
48378         })
48379             .slice(this._configuration.maxUnusedPreStoredNodes)
48380             .map(function (_a) {
48381             var na = _a[0], h = _a[1];
48382             return [na.node.key, h];
48383         });
48384         this._uncachePreStored(nonCachedPreStored);
48385         this._uncachePreStored(uncachePreStored);
48386         var potentialNodes = [];
48387         for (var key in this._cachedNodes) {
48388             if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
48389                 continue;
48390             }
48391             potentialNodes.push(this._cachedNodes[key]);
48392         }
48393         var uncacheNodes = potentialNodes
48394             .sort(function (n1, n2) {
48395             return n2.accessed - n1.accessed;
48396         })
48397             .slice(this._configuration.maxUnusedNodes);
48398         for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
48399             var nodeAccess = uncacheNodes_1[_c];
48400             nodeAccess.node.uncache();
48401             var key = nodeAccess.node.key;
48402             delete this._cachedNodes[key];
48403             if (key in this._cachedNodeTiles) {
48404                 delete this._cachedNodeTiles[key];
48405             }
48406             if (key in this._cachedSpatialEdges) {
48407                 delete this._cachedSpatialEdges[key];
48408             }
48409         }
48410         var potentialSequences = [];
48411         for (var sequenceKey in this._sequences) {
48412             if (!this._sequences.hasOwnProperty(sequenceKey) ||
48413                 sequenceKey in this._cachingSequences$ ||
48414                 sequenceKey === keepSequenceKey) {
48415                 continue;
48416             }
48417             potentialSequences.push(this._sequences[sequenceKey]);
48418         }
48419         var uncacheSequences = potentialSequences
48420             .sort(function (s1, s2) {
48421             return s2.accessed - s1.accessed;
48422         })
48423             .slice(this._configuration.maxSequences);
48424         for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
48425             var sequenceAccess = uncacheSequences_1[_d];
48426             var sequenceKey = sequenceAccess.sequence.key;
48427             delete this._sequences[sequenceKey];
48428             if (sequenceKey in this._cachedSequenceNodes) {
48429                 delete this._cachedSequenceNodes[sequenceKey];
48430             }
48431             sequenceAccess.sequence.dispose();
48432         }
48433     };
48434     Graph.prototype._addNewKeys = function (keys, dict) {
48435         for (var key in dict) {
48436             if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
48437                 continue;
48438             }
48439             if (!(key in keys)) {
48440                 keys[key] = true;
48441             }
48442         }
48443     };
48444     Graph.prototype._cacheSequence$ = function (sequenceKey) {
48445         var _this = this;
48446         if (sequenceKey in this._cachingSequences$) {
48447             return this._cachingSequences$[sequenceKey];
48448         }
48449         this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey]).pipe(operators_1.tap(function (sequenceByKey) {
48450             if (!(sequenceKey in _this._sequences)) {
48451                 _this._sequences[sequenceKey] = {
48452                     accessed: new Date().getTime(),
48453                     sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
48454                 };
48455             }
48456             delete _this._cachingSequences$[sequenceKey];
48457         }), operators_1.map(function (sequenceByKey) {
48458             return _this;
48459         }), operators_1.finalize(function () {
48460             if (sequenceKey in _this._cachingSequences$) {
48461                 delete _this._cachingSequences$[sequenceKey];
48462             }
48463             _this._changed$.next(_this);
48464         }), operators_1.publish(), operators_1.refCount());
48465         return this._cachingSequences$[sequenceKey];
48466     };
48467     Graph.prototype._cacheTile$ = function (h) {
48468         var _this = this;
48469         this._cachingTiles$[h] = this._apiV3.imagesByH$([h]).pipe(operators_1.tap(function (imagesByH) {
48470             var coreNodes = imagesByH[h];
48471             if (h in _this._cachedTiles) {
48472                 return;
48473             }
48474             _this._nodeIndexTiles[h] = [];
48475             _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
48476             var hCache = _this._cachedTiles[h].nodes;
48477             var preStored = _this._removeFromPreStore(h);
48478             for (var index in coreNodes) {
48479                 if (!coreNodes.hasOwnProperty(index)) {
48480                     continue;
48481                 }
48482                 var coreNode = coreNodes[index];
48483                 if (coreNode == null) {
48484                     break;
48485                 }
48486                 if (coreNode.sequence_key == null) {
48487                     console.warn("Sequence missing, discarding node (" + coreNode.key + ")");
48488                     continue;
48489                 }
48490                 if (preStored != null && coreNode.key in preStored) {
48491                     var preStoredNode = preStored[coreNode.key];
48492                     delete preStored[coreNode.key];
48493                     hCache.push(preStoredNode);
48494                     var preStoredNodeIndexItem = {
48495                         lat: preStoredNode.latLon.lat,
48496                         lon: preStoredNode.latLon.lon,
48497                         node: preStoredNode,
48498                     };
48499                     _this._nodeIndex.insert(preStoredNodeIndexItem);
48500                     _this._nodeIndexTiles[h].push(preStoredNodeIndexItem);
48501                     _this._nodeToTile[preStoredNode.key] = h;
48502                     continue;
48503                 }
48504                 var node = new Graph_1.Node(coreNode);
48505                 hCache.push(node);
48506                 var nodeIndexItem = {
48507                     lat: node.latLon.lat,
48508                     lon: node.latLon.lon,
48509                     node: node,
48510                 };
48511                 _this._nodeIndex.insert(nodeIndexItem);
48512                 _this._nodeIndexTiles[h].push(nodeIndexItem);
48513                 _this._nodeToTile[node.key] = h;
48514                 _this._setNode(node);
48515             }
48516             delete _this._cachingTiles$[h];
48517         }), operators_1.map(function (imagesByH) {
48518             return _this;
48519         }), operators_1.catchError(function (error) {
48520             delete _this._cachingTiles$[h];
48521             throw error;
48522         }), operators_1.publish(), operators_1.refCount());
48523         return this._cachingTiles$[h];
48524     };
48525     Graph.prototype._makeFull = function (node, fillNode) {
48526         if (fillNode.calt == null) {
48527             fillNode.calt = this._defaultAlt;
48528         }
48529         if (fillNode.c_rotation == null) {
48530             fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
48531         }
48532         node.makeFull(fillNode);
48533     };
48534     Graph.prototype._preStore = function (h, node) {
48535         if (!(h in this._preStored)) {
48536             this._preStored[h] = {};
48537         }
48538         this._preStored[h][node.key] = node;
48539     };
48540     Graph.prototype._removeFromPreStore = function (h) {
48541         var preStored = null;
48542         if (h in this._preStored) {
48543             preStored = this._preStored[h];
48544             delete this._preStored[h];
48545         }
48546         return preStored;
48547     };
48548     Graph.prototype._setNode = function (node) {
48549         var key = node.key;
48550         if (this.hasNode(key)) {
48551             throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
48552         }
48553         this._nodes[key] = node;
48554     };
48555     Graph.prototype._uncacheTile = function (h, keepSequenceKey) {
48556         for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
48557             var node = _a[_i];
48558             var key = node.key;
48559             delete this._nodeToTile[key];
48560             if (key in this._cachedNodes) {
48561                 delete this._cachedNodes[key];
48562             }
48563             if (key in this._cachedNodeTiles) {
48564                 delete this._cachedNodeTiles[key];
48565             }
48566             if (key in this._cachedSpatialEdges) {
48567                 delete this._cachedSpatialEdges[key];
48568             }
48569             if (node.sequenceKey === keepSequenceKey) {
48570                 this._preStore(h, node);
48571                 node.uncache();
48572             }
48573             else {
48574                 delete this._nodes[key];
48575                 if (node.sequenceKey in this._cachedSequenceNodes) {
48576                     delete this._cachedSequenceNodes[node.sequenceKey];
48577                 }
48578                 node.dispose();
48579             }
48580         }
48581         for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
48582             var nodeIndexItem = _c[_b];
48583             this._nodeIndex.remove(nodeIndexItem);
48584         }
48585         delete this._nodeIndexTiles[h];
48586         delete this._cachedTiles[h];
48587     };
48588     Graph.prototype._uncachePreStored = function (preStored) {
48589         var hs = {};
48590         for (var _i = 0, preStored_1 = preStored; _i < preStored_1.length; _i++) {
48591             var _a = preStored_1[_i], key = _a[0], h = _a[1];
48592             if (key in this._nodes) {
48593                 delete this._nodes[key];
48594             }
48595             if (key in this._cachedNodes) {
48596                 delete this._cachedNodes[key];
48597             }
48598             var node = this._preStored[h][key];
48599             if (node.sequenceKey in this._cachedSequenceNodes) {
48600                 delete this._cachedSequenceNodes[node.sequenceKey];
48601             }
48602             delete this._preStored[h][key];
48603             node.dispose();
48604             hs[h] = true;
48605         }
48606         for (var h in hs) {
48607             if (!hs.hasOwnProperty(h)) {
48608                 continue;
48609             }
48610             if (Object.keys(this._preStored[h]).length === 0) {
48611                 delete this._preStored[h];
48612             }
48613         }
48614     };
48615     Graph.prototype._updateCachedTileAccess = function (key, accessed) {
48616         if (key in this._nodeToTile) {
48617             this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
48618         }
48619     };
48620     Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
48621         if (key in this._cachedNodes) {
48622             this._cachedNodes[key].accessed = accessed;
48623         }
48624     };
48625     return Graph;
48626 }());
48627 exports.Graph = Graph;
48628 exports.default = Graph;
48629
48630 },{"../Edge":292,"../Error":293,"../Graph":295,"rbush":42,"rxjs":43,"rxjs/operators":241}],417:[function(require,module,exports){
48631 "use strict";
48632 Object.defineProperty(exports, "__esModule", { value: true });
48633 var geohash = require("latlon-geohash");
48634 var THREE = require("three");
48635 var Error_1 = require("../Error");
48636 var Geo_1 = require("../Geo");
48637 /**
48638  * @class GraphCalculator
48639  *
48640  * @classdesc Represents a calculator for graph entities.
48641  */
48642 var GraphCalculator = /** @class */ (function () {
48643     /**
48644      * Create a new graph calculator instance.
48645      *
48646      * @param {GeoCoords} geoCoords - Geo coords instance.
48647      */
48648     function GraphCalculator(geoCoords) {
48649         this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
48650     }
48651     /**
48652      * Encode the geohash tile for geodetic coordinates.
48653      *
48654      * @param {ILatLon} latlon - Latitude and longitude to encode.
48655      * @param {number} precision - Precision of the encoding.
48656      *
48657      * @returns {string} The geohash tile for the lat, lon and precision.
48658      */
48659     GraphCalculator.prototype.encodeH = function (latLon, precision) {
48660         if (precision === void 0) { precision = 7; }
48661         return geohash.encode(latLon.lat, latLon.lon, precision);
48662     };
48663     /**
48664      * Encode the geohash tiles within a threshold from a position
48665      * using Manhattan distance.
48666      *
48667      * @param {ILatLon} latlon - Latitude and longitude to encode.
48668      * @param {number} precision - Precision of the encoding.
48669      * @param {number} threshold - Threshold of the encoding in meters.
48670      *
48671      * @returns {string} The geohash tiles reachable within the threshold.
48672      */
48673     GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
48674         if (precision === void 0) { precision = 7; }
48675         if (threshold === void 0) { threshold = 20; }
48676         var h = geohash.encode(latLon.lat, latLon.lon, precision);
48677         var bounds = geohash.bounds(h);
48678         var ne = bounds.ne;
48679         var sw = bounds.sw;
48680         var neighbours = geohash.neighbours(h);
48681         var bl = [0, 0, 0];
48682         var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
48683         var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
48684         var left = position[0] - bl[0];
48685         var right = tr[0] - position[0];
48686         var bottom = position[1] - bl[1];
48687         var top = tr[1] - position[1];
48688         var l = left < threshold;
48689         var r = right < threshold;
48690         var b = bottom < threshold;
48691         var t = top < threshold;
48692         var hs = [h];
48693         if (t) {
48694             hs.push(neighbours.n);
48695         }
48696         if (t && l) {
48697             hs.push(neighbours.nw);
48698         }
48699         if (l) {
48700             hs.push(neighbours.w);
48701         }
48702         if (l && b) {
48703             hs.push(neighbours.sw);
48704         }
48705         if (b) {
48706             hs.push(neighbours.s);
48707         }
48708         if (b && r) {
48709             hs.push(neighbours.se);
48710         }
48711         if (r) {
48712             hs.push(neighbours.e);
48713         }
48714         if (r && t) {
48715             hs.push(neighbours.ne);
48716         }
48717         return hs;
48718     };
48719     /**
48720      * Encode the minimum set of geohash tiles containing a bounding box.
48721      *
48722      * @description The current algorithm does expect the bounding box
48723      * to be sufficiently small to be contained in an area with the size
48724      * of maximally four tiles. Up to nine adjacent tiles may be returned.
48725      * The method currently uses the largest side as the threshold leading to
48726      * more tiles being returned than needed in edge cases.
48727      *
48728      * @param {ILatLon} sw - South west corner of bounding box.
48729      * @param {ILatLon} ne - North east corner of bounding box.
48730      * @param {number} precision - Precision of the encoding.
48731      *
48732      * @returns {string} The geohash tiles containing the bounding box.
48733      */
48734     GraphCalculator.prototype.encodeHsFromBoundingBox = function (sw, ne, precision) {
48735         if (precision === void 0) { precision = 7; }
48736         if (ne.lat <= sw.lat || ne.lon <= sw.lon) {
48737             throw new Error_1.GraphMapillaryError("North east needs to be top right of south west");
48738         }
48739         var centerLat = (sw.lat + ne.lat) / 2;
48740         var centerLon = (sw.lon + ne.lon) / 2;
48741         var enu = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, centerLat, centerLon, 0);
48742         var threshold = Math.max(enu[0], enu[1]);
48743         return this.encodeHs({ lat: centerLat, lon: centerLon }, precision, threshold);
48744     };
48745     /**
48746      * Get the bounding box corners for a circle with radius of a threshold
48747      * with center in a geodetic position.
48748      *
48749      * @param {ILatLon} latlon - Latitude and longitude to encode.
48750      * @param {number} threshold - Threshold distance from the position in meters.
48751      *
48752      * @returns {Array<ILatLon>} The south west and north east corners of the
48753      * bounding box.
48754      */
48755     GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
48756         var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
48757         var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
48758         return [
48759             { lat: bl[0], lon: bl[1] },
48760             { lat: tr[0], lon: tr[1] },
48761         ];
48762     };
48763     /**
48764      * Convert a compass angle to an angle axis rotation vector.
48765      *
48766      * @param {number} compassAngle - The compass angle in degrees.
48767      * @param {number} orientation - The orientation of the original image.
48768      *
48769      * @returns {Array<number>} Angle axis rotation vector.
48770      */
48771     GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
48772         var x = 0;
48773         var y = 0;
48774         var z = 0;
48775         switch (orientation) {
48776             case 1:
48777                 x = Math.PI / 2;
48778                 break;
48779             case 3:
48780                 x = -Math.PI / 2;
48781                 z = Math.PI;
48782                 break;
48783             case 6:
48784                 y = -Math.PI / 2;
48785                 z = -Math.PI / 2;
48786                 break;
48787             case 8:
48788                 y = Math.PI / 2;
48789                 z = Math.PI / 2;
48790                 break;
48791             default:
48792                 break;
48793         }
48794         var rz = new THREE.Matrix4().makeRotationZ(z);
48795         var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
48796         var re = new THREE.Matrix4().makeRotationFromEuler(euler);
48797         var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
48798         return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
48799     };
48800     return GraphCalculator;
48801 }());
48802 exports.GraphCalculator = GraphCalculator;
48803 exports.default = GraphCalculator;
48804
48805 },{"../Error":293,"../Geo":294,"latlon-geohash":21,"three":242}],418:[function(require,module,exports){
48806 "use strict";
48807 Object.defineProperty(exports, "__esModule", { value: true });
48808 /**
48809  * Enumeration for graph modes.
48810  * @enum {number}
48811  * @readonly
48812  * @description Modes for the retrieval and caching performed
48813  * by the graph service on the graph.
48814  */
48815 var GraphMode;
48816 (function (GraphMode) {
48817     /**
48818      * Caching is performed on sequences only and sequence edges are
48819      * calculated. Spatial tiles
48820      * are not retrieved and spatial edges are not calculated when
48821      * caching nodes. Complete sequences are being cached for requested
48822      * nodes within the graph.
48823      */
48824     GraphMode[GraphMode["Sequence"] = 0] = "Sequence";
48825     /**
48826      * Caching is performed with emphasis on spatial data. Sequence edges
48827      * as well as spatial edges are cached. Sequence data
48828      * is still requested but complete sequences are not being cached
48829      * for requested nodes.
48830      *
48831      * This is the initial mode of the graph service.
48832      */
48833     GraphMode[GraphMode["Spatial"] = 1] = "Spatial";
48834 })(GraphMode = exports.GraphMode || (exports.GraphMode = {}));
48835 exports.default = GraphMode;
48836
48837 },{}],419:[function(require,module,exports){
48838 "use strict";
48839 Object.defineProperty(exports, "__esModule", { value: true });
48840 var rxjs_1 = require("rxjs");
48841 var operators_1 = require("rxjs/operators");
48842 var Graph_1 = require("../Graph");
48843 /**
48844  * @class GraphService
48845  *
48846  * @classdesc Represents a service for graph operations.
48847  */
48848 var GraphService = /** @class */ (function () {
48849     /**
48850      * Create a new graph service instance.
48851      *
48852      * @param {Graph} graph - Graph instance to be operated on.
48853      */
48854     function GraphService(graph, imageLoadingService) {
48855         this._graph$ = rxjs_1.concat(rxjs_1.of(graph), graph.changed$).pipe(operators_1.publishReplay(1), operators_1.refCount());
48856         this._graph$.subscribe(function () { });
48857         this._graphMode = Graph_1.GraphMode.Spatial;
48858         this._graphModeSubject$ = new rxjs_1.Subject();
48859         this._graphMode$ = this._graphModeSubject$.pipe(operators_1.startWith(this._graphMode), operators_1.publishReplay(1), operators_1.refCount());
48860         this._graphMode$.subscribe(function () { });
48861         this._imageLoadingService = imageLoadingService;
48862         this._firstGraphSubjects$ = [];
48863         this._initializeCacheSubscriptions = [];
48864         this._sequenceSubscriptions = [];
48865         this._spatialSubscriptions = [];
48866     }
48867     Object.defineProperty(GraphService.prototype, "graphMode$", {
48868         /**
48869          * Get graph mode observable.
48870          *
48871          * @description Emits the current graph mode.
48872          *
48873          * @returns {Observable<GraphMode>} Observable
48874          * emitting the current graph mode when it changes.
48875          */
48876         get: function () {
48877             return this._graphMode$;
48878         },
48879         enumerable: true,
48880         configurable: true
48881     });
48882     /**
48883      * Cache full nodes in a bounding box.
48884      *
48885      * @description When called, the full properties of
48886      * the node are retrieved. The node cache is not initialized
48887      * for any new nodes retrieved and the node assets are not
48888      * retrieved, {@link cacheNode$} needs to be called for caching
48889      * assets.
48890      *
48891      * @param {ILatLon} sw - South west corner of bounding box.
48892      * @param {ILatLon} ne - North east corner of bounding box.
48893      * @return {Observable<Array<Node>>} Observable emitting a single item,
48894      * the nodes of the bounding box, when they have all been retrieved.
48895      * @throws {Error} Propagates any IO node caching errors to the caller.
48896      */
48897     GraphService.prototype.cacheBoundingBox$ = function (sw, ne) {
48898         return this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
48899             return graph.cacheBoundingBox$(sw, ne);
48900         }));
48901     };
48902     /**
48903      * Cache a node in the graph and retrieve it.
48904      *
48905      * @description When called, the full properties of
48906      * the node are retrieved and the node cache is initialized.
48907      * After that the node assets are cached and the node
48908      * is emitted to the observable when.
48909      * In parallel to caching the node assets, the sequence and
48910      * spatial edges of the node are cached. For this, the sequence
48911      * of the node and the required tiles and spatial nodes are
48912      * retrieved. The sequence and spatial edges may be set before
48913      * or after the node is returned.
48914      *
48915      * @param {string} key - Key of the node to cache.
48916      * @return {Observable<Node>} Observable emitting a single item,
48917      * the node, when it has been retrieved and its assets are cached.
48918      * @throws {Error} Propagates any IO node caching errors to the caller.
48919      */
48920     GraphService.prototype.cacheNode$ = function (key) {
48921         var _this = this;
48922         var firstGraphSubject$ = new rxjs_1.Subject();
48923         this._firstGraphSubjects$.push(firstGraphSubject$);
48924         var firstGraph$ = firstGraphSubject$.pipe(operators_1.publishReplay(1), operators_1.refCount());
48925         var node$ = firstGraph$.pipe(operators_1.map(function (graph) {
48926             return graph.getNode(key);
48927         }), operators_1.mergeMap(function (node) {
48928             return node.assetsCached ?
48929                 rxjs_1.of(node) :
48930                 node.cacheAssets$();
48931         }), operators_1.publishReplay(1), operators_1.refCount());
48932         node$.subscribe(function (node) {
48933             _this._imageLoadingService.loadnode$.next(node);
48934         }, function (error) {
48935             console.error("Failed to cache node (" + key + ")", error);
48936         });
48937         var initializeCacheSubscription = this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
48938             if (graph.isCachingFull(key) || !graph.hasNode(key)) {
48939                 return graph.cacheFull$(key);
48940             }
48941             if (graph.isCachingFill(key) || !graph.getNode(key).full) {
48942                 return graph.cacheFill$(key);
48943             }
48944             return rxjs_1.of(graph);
48945         }), operators_1.tap(function (graph) {
48946             if (!graph.hasInitializedCache(key)) {
48947                 graph.initializeCache(key);
48948             }
48949         }), operators_1.finalize(function () {
48950             if (initializeCacheSubscription == null) {
48951                 return;
48952             }
48953             _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
48954             _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
48955         }))
48956             .subscribe(function (graph) {
48957             firstGraphSubject$.next(graph);
48958             firstGraphSubject$.complete();
48959         }, function (error) {
48960             firstGraphSubject$.error(error);
48961         });
48962         if (!initializeCacheSubscription.closed) {
48963             this._initializeCacheSubscriptions.push(initializeCacheSubscription);
48964         }
48965         var graphSequence$ = firstGraph$.pipe(operators_1.mergeMap(function (graph) {
48966             if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
48967                 return graph.cacheNodeSequence$(key);
48968             }
48969             return rxjs_1.of(graph);
48970         }), operators_1.publishReplay(1), operators_1.refCount());
48971         var sequenceSubscription = graphSequence$.pipe(operators_1.tap(function (graph) {
48972             if (!graph.getNode(key).sequenceEdges.cached) {
48973                 graph.cacheSequenceEdges(key);
48974             }
48975         }), operators_1.finalize(function () {
48976             if (sequenceSubscription == null) {
48977                 return;
48978             }
48979             _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
48980         }))
48981             .subscribe(function (graph) { return; }, function (error) {
48982             console.error("Failed to cache sequence edges (" + key + ").", error);
48983         });
48984         if (!sequenceSubscription.closed) {
48985             this._sequenceSubscriptions.push(sequenceSubscription);
48986         }
48987         if (this._graphMode === Graph_1.GraphMode.Spatial) {
48988             var spatialSubscription_1 = firstGraph$.pipe(operators_1.expand(function (graph) {
48989                 if (graph.hasTiles(key)) {
48990                     return rxjs_1.empty();
48991                 }
48992                 return rxjs_1.from(graph.cacheTiles$(key)).pipe(operators_1.mergeMap(function (graph$) {
48993                     return graph$.pipe(operators_1.mergeMap(function (g) {
48994                         if (g.isCachingTiles(key)) {
48995                             return rxjs_1.empty();
48996                         }
48997                         return rxjs_1.of(g);
48998                     }), operators_1.catchError(function (error, caught$) {
48999                         console.error("Failed to cache tile data (" + key + ").", error);
49000                         return rxjs_1.empty();
49001                     }));
49002                 }));
49003             }), operators_1.last(), operators_1.mergeMap(function (graph) {
49004                 if (graph.hasSpatialArea(key)) {
49005                     return rxjs_1.of(graph);
49006                 }
49007                 return rxjs_1.from(graph.cacheSpatialArea$(key)).pipe(operators_1.mergeMap(function (graph$) {
49008                     return graph$.pipe(operators_1.catchError(function (error, caught$) {
49009                         console.error("Failed to cache spatial nodes (" + key + ").", error);
49010                         return rxjs_1.empty();
49011                     }));
49012                 }));
49013             }), operators_1.last(), operators_1.mergeMap(function (graph) {
49014                 return graph.hasNodeSequence(key) ?
49015                     rxjs_1.of(graph) :
49016                     graph.cacheNodeSequence$(key);
49017             }), operators_1.tap(function (graph) {
49018                 if (!graph.getNode(key).spatialEdges.cached) {
49019                     graph.cacheSpatialEdges(key);
49020                 }
49021             }), operators_1.finalize(function () {
49022                 if (spatialSubscription_1 == null) {
49023                     return;
49024                 }
49025                 _this._removeFromArray(spatialSubscription_1, _this._spatialSubscriptions);
49026             }))
49027                 .subscribe(function (graph) { return; }, function (error) {
49028                 console.error("Failed to cache spatial edges (" + key + ").", error);
49029             });
49030             if (!spatialSubscription_1.closed) {
49031                 this._spatialSubscriptions.push(spatialSubscription_1);
49032             }
49033         }
49034         return node$.pipe(operators_1.first(function (node) {
49035             return node.assetsCached;
49036         }));
49037     };
49038     /**
49039      * Cache a sequence in the graph and retrieve it.
49040      *
49041      * @param {string} sequenceKey - Sequence key.
49042      * @returns {Observable<Sequence>} Observable emitting a single item,
49043      * the sequence, when it has been retrieved and its assets are cached.
49044      * @throws {Error} Propagates any IO node caching errors to the caller.
49045      */
49046     GraphService.prototype.cacheSequence$ = function (sequenceKey) {
49047         return this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
49048             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
49049                 return graph.cacheSequence$(sequenceKey);
49050             }
49051             return rxjs_1.of(graph);
49052         }), operators_1.map(function (graph) {
49053             return graph.getSequence(sequenceKey);
49054         }));
49055     };
49056     /**
49057      * Cache a sequence and its nodes in the graph and retrieve the sequence.
49058      *
49059      * @description Caches a sequence and its assets are cached and
49060      * retrieves all nodes belonging to the sequence. The node assets
49061      * or edges will not be cached.
49062      *
49063      * @param {string} sequenceKey - Sequence key.
49064      * @param {string} referenceNodeKey - Key of node to use as reference
49065      * for optimized caching.
49066      * @returns {Observable<Sequence>} Observable emitting a single item,
49067      * the sequence, when it has been retrieved, its assets are cached and
49068      * all nodes belonging to the sequence has been retrieved.
49069      * @throws {Error} Propagates any IO node caching errors to the caller.
49070      */
49071     GraphService.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
49072         return this._graph$.pipe(operators_1.first(), operators_1.mergeMap(function (graph) {
49073             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
49074                 return graph.cacheSequence$(sequenceKey);
49075             }
49076             return rxjs_1.of(graph);
49077         }), operators_1.mergeMap(function (graph) {
49078             if (graph.isCachingSequenceNodes(sequenceKey) || !graph.hasSequenceNodes(sequenceKey)) {
49079                 return graph.cacheSequenceNodes$(sequenceKey, referenceNodeKey);
49080             }
49081             return rxjs_1.of(graph);
49082         }), operators_1.map(function (graph) {
49083             return graph.getSequence(sequenceKey);
49084         }));
49085     };
49086     /**
49087      * Set a spatial edge filter on the graph.
49088      *
49089      * @description Resets the spatial edges of all cached nodes.
49090      *
49091      * @param {FilterExpression} filter - Filter expression to be applied.
49092      * @return {Observable<Graph>} Observable emitting a single item,
49093      * the graph, when the spatial edges have been reset.
49094      */
49095     GraphService.prototype.setFilter$ = function (filter) {
49096         this._resetSubscriptions(this._spatialSubscriptions);
49097         return this._graph$.pipe(operators_1.first(), operators_1.tap(function (graph) {
49098             graph.resetSpatialEdges();
49099             graph.setFilter(filter);
49100         }), operators_1.map(function (graph) {
49101             return undefined;
49102         }));
49103     };
49104     /**
49105      * Set the graph mode.
49106      *
49107      * @description If graph mode is set to spatial, caching
49108      * is performed with emphasis on spatial edges. If graph
49109      * mode is set to sequence no tile data is requested and
49110      * no spatial edges are computed.
49111      *
49112      * When setting graph mode to sequence all spatial
49113      * subscriptions are aborted.
49114      *
49115      * @param {GraphMode} mode - Graph mode to set.
49116      */
49117     GraphService.prototype.setGraphMode = function (mode) {
49118         if (this._graphMode === mode) {
49119             return;
49120         }
49121         if (mode === Graph_1.GraphMode.Sequence) {
49122             this._resetSubscriptions(this._spatialSubscriptions);
49123         }
49124         this._graphMode = mode;
49125         this._graphModeSubject$.next(this._graphMode);
49126     };
49127     /**
49128      * Reset the graph.
49129      *
49130      * @description Resets the graph but keeps the nodes of the
49131      * supplied keys.
49132      *
49133      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
49134      * @return {Observable<Node>} Observable emitting a single item,
49135      * the graph, when it has been reset.
49136      */
49137     GraphService.prototype.reset$ = function (keepKeys) {
49138         this._abortSubjects(this._firstGraphSubjects$);
49139         this._resetSubscriptions(this._initializeCacheSubscriptions);
49140         this._resetSubscriptions(this._sequenceSubscriptions);
49141         this._resetSubscriptions(this._spatialSubscriptions);
49142         return this._graph$.pipe(operators_1.first(), operators_1.tap(function (graph) {
49143             graph.reset(keepKeys);
49144         }), operators_1.map(function (graph) {
49145             return undefined;
49146         }));
49147     };
49148     /**
49149      * Uncache the graph.
49150      *
49151      * @description Uncaches the graph by removing tiles, nodes and
49152      * sequences. Keeps the nodes of the supplied keys and the tiles
49153      * related to those nodes.
49154      *
49155      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
49156      * @param {string} keepSequenceKey - Optional key of sequence
49157      * for which the belonging nodes should not be disposed or
49158      * removed from the graph. These nodes may still be uncached if
49159      * not specified in keep keys param.
49160      * @return {Observable<Graph>} Observable emitting a single item,
49161      * the graph, when the graph has been uncached.
49162      */
49163     GraphService.prototype.uncache$ = function (keepKeys, keepSequenceKey) {
49164         return this._graph$.pipe(operators_1.first(), operators_1.tap(function (graph) {
49165             graph.uncache(keepKeys, keepSequenceKey);
49166         }), operators_1.map(function (graph) {
49167             return undefined;
49168         }));
49169     };
49170     GraphService.prototype._abortSubjects = function (subjects) {
49171         for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
49172             var subject = _a[_i];
49173             this._removeFromArray(subject, subjects);
49174             subject.error(new Error("Cache node request was aborted."));
49175         }
49176     };
49177     GraphService.prototype._removeFromArray = function (object, objects) {
49178         var index = objects.indexOf(object);
49179         if (index !== -1) {
49180             objects.splice(index, 1);
49181         }
49182     };
49183     GraphService.prototype._resetSubscriptions = function (subscriptions) {
49184         for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
49185             var subscription = _a[_i];
49186             this._removeFromArray(subscription, subscriptions);
49187             if (!subscription.closed) {
49188                 subscription.unsubscribe();
49189             }
49190         }
49191     };
49192     return GraphService;
49193 }());
49194 exports.GraphService = GraphService;
49195 exports.default = GraphService;
49196
49197 },{"../Graph":295,"rxjs":43,"rxjs/operators":241}],420:[function(require,module,exports){
49198 "use strict";
49199 Object.defineProperty(exports, "__esModule", { value: true });
49200 var operators_1 = require("rxjs/operators");
49201 var rxjs_1 = require("rxjs");
49202 var ImageLoadingService = /** @class */ (function () {
49203     function ImageLoadingService() {
49204         this._loadnode$ = new rxjs_1.Subject();
49205         this._loadstatus$ = this._loadnode$.pipe(operators_1.scan(function (_a, node) {
49206             var nodes = _a[0];
49207             var changed = false;
49208             if (node.loadStatus.total === 0 || node.loadStatus.loaded === node.loadStatus.total) {
49209                 if (node.key in nodes) {
49210                     delete nodes[node.key];
49211                     changed = true;
49212                 }
49213             }
49214             else {
49215                 nodes[node.key] = node.loadStatus;
49216                 changed = true;
49217             }
49218             return [nodes, changed];
49219         }, [{}, false]), operators_1.filter(function (_a) {
49220             var nodes = _a[0], changed = _a[1];
49221             return changed;
49222         }), operators_1.map(function (_a) {
49223             var nodes = _a[0];
49224             return nodes;
49225         }), operators_1.publishReplay(1), operators_1.refCount());
49226         this._loadstatus$.subscribe(function () { });
49227     }
49228     Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
49229         get: function () {
49230             return this._loadnode$;
49231         },
49232         enumerable: true,
49233         configurable: true
49234     });
49235     Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
49236         get: function () {
49237             return this._loadstatus$;
49238         },
49239         enumerable: true,
49240         configurable: true
49241     });
49242     return ImageLoadingService;
49243 }());
49244 exports.ImageLoadingService = ImageLoadingService;
49245
49246 },{"rxjs":43,"rxjs/operators":241}],421:[function(require,module,exports){
49247 "use strict";
49248 Object.defineProperty(exports, "__esModule", { value: true });
49249 var Pbf = require("pbf");
49250 var MeshReader = /** @class */ (function () {
49251     function MeshReader() {
49252     }
49253     MeshReader.read = function (buffer) {
49254         var pbf = new Pbf(buffer);
49255         return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
49256     };
49257     MeshReader._readMeshField = function (tag, mesh, pbf) {
49258         if (tag === 1) {
49259             mesh.vertices.push(pbf.readFloat());
49260         }
49261         else if (tag === 2) {
49262             mesh.faces.push(pbf.readVarint());
49263         }
49264     };
49265     return MeshReader;
49266 }());
49267 exports.MeshReader = MeshReader;
49268
49269 },{"pbf":40}],422:[function(require,module,exports){
49270 "use strict";
49271 Object.defineProperty(exports, "__esModule", { value: true });
49272 var operators_1 = require("rxjs/operators");
49273 /**
49274  * @class Node
49275  *
49276  * @classdesc Represents a node in the navigation graph.
49277  *
49278  * Explanation of position and bearing properties:
49279  *
49280  * When images are uploaded they will have GPS information in the EXIF, this is what
49281  * is called `originalLatLon` {@link Node.originalLatLon}.
49282  *
49283  * When Structure from Motions has been run for a node a `computedLatLon` that
49284  * differs from the `originalLatLon` will be created. It is different because
49285  * GPS positions are not very exact and SfM aligns the camera positions according
49286  * to the 3D reconstruction {@link Node.computedLatLon}.
49287  *
49288  * At last there exist a `latLon` property which evaluates to
49289  * the `computedLatLon` from SfM if it exists but falls back
49290  * to the `originalLatLon` from the EXIF GPS otherwise {@link Node.latLon}.
49291  *
49292  * Everything that is done in in the Viewer is based on the SfM positions,
49293  * i.e. `computedLatLon`. That is why the smooth transitions go in the right
49294  * direction (nd not in strange directions because of bad GPS).
49295  *
49296  * E.g. when placing a marker in the Viewer it is relative to the SfM
49297  * position i.e. the `computedLatLon`.
49298  *
49299  * The same concept as above also applies to the compass angle (or bearing) properties
49300  * `originalCa`, `computedCa` and `ca`.
49301  */
49302 var Node = /** @class */ (function () {
49303     /**
49304      * Create a new node instance.
49305      *
49306      * @description Nodes are always created internally by the library.
49307      * Nodes can not be added to the library through any API method.
49308      *
49309      * @param {ICoreNode} coreNode - Raw core node data.
49310      * @ignore
49311      */
49312     function Node(core) {
49313         this._cache = null;
49314         this._core = core;
49315         this._fill = null;
49316     }
49317     Object.defineProperty(Node.prototype, "assetsCached", {
49318         /**
49319          * Get assets cached.
49320          *
49321          * @description The assets that need to be cached for this property
49322          * to report true are the following: fill properties, image and mesh.
49323          * The library ensures that the current node will always have the
49324          * assets cached.
49325          *
49326          * @returns {boolean} Value indicating whether all assets have been
49327          * cached.
49328          *
49329          * @ignore
49330          */
49331         get: function () {
49332             return this._core != null &&
49333                 this._fill != null &&
49334                 this._cache != null &&
49335                 this._cache.image != null &&
49336                 this._cache.mesh != null;
49337         },
49338         enumerable: true,
49339         configurable: true
49340     });
49341     Object.defineProperty(Node.prototype, "alt", {
49342         /**
49343          * Get alt.
49344          *
49345          * @description If SfM has not been run the computed altitude is
49346          * set to a default value of two meters.
49347          *
49348          * @returns {number} Altitude, in meters.
49349          */
49350         get: function () {
49351             return this._fill.calt;
49352         },
49353         enumerable: true,
49354         configurable: true
49355     });
49356     Object.defineProperty(Node.prototype, "ca", {
49357         /**
49358          * Get ca.
49359          *
49360          * @description If the SfM computed compass angle exists it will
49361          * be returned, otherwise the original EXIF compass angle.
49362          *
49363          * @returns {number} Compass angle, measured in degrees
49364          * clockwise with respect to north.
49365          */
49366         get: function () {
49367             return this._fill.cca != null ? this._fill.cca : this._fill.ca;
49368         },
49369         enumerable: true,
49370         configurable: true
49371     });
49372     Object.defineProperty(Node.prototype, "cameraProjection", {
49373         /**
49374          * Get cameraProjection.
49375          *
49376          * @description Will be undefined if SfM has not been run.
49377          *
49378          * @returns {number} The camera projection of the image.
49379          */
49380         get: function () {
49381             return this._fill.camera_projection_type;
49382         },
49383         enumerable: true,
49384         configurable: true
49385     });
49386     Object.defineProperty(Node.prototype, "capturedAt", {
49387         /**
49388          * Get capturedAt.
49389          *
49390          * @returns {number} Timestamp when the image was captured.
49391          */
49392         get: function () {
49393             return this._fill.captured_at;
49394         },
49395         enumerable: true,
49396         configurable: true
49397     });
49398     Object.defineProperty(Node.prototype, "cameraUuid", {
49399         /**
49400          * Get camera uuid.
49401          *
49402          * @description Will be undefined if the camera uuid was not
49403          * recorded in the image exif information.
49404          *
49405          * @returns {string} Universally unique id for camera used
49406          * when capturing image.
49407          */
49408         get: function () {
49409             return this._fill.captured_with_camera_uuid;
49410         },
49411         enumerable: true,
49412         configurable: true
49413     });
49414     Object.defineProperty(Node.prototype, "clusterKey", {
49415         /**
49416          * Get clusterKey.
49417          *
49418          * @returns {string} Unique key of the SfM cluster to which
49419          * the node belongs.
49420          */
49421         get: function () {
49422             return this._fill.cluster_key;
49423         },
49424         enumerable: true,
49425         configurable: true
49426     });
49427     Object.defineProperty(Node.prototype, "ck1", {
49428         /**
49429          * Get ck1.
49430          *
49431          * @description Will not be set if SfM has not been run.
49432          *
49433          * @returns {number} SfM computed radial distortion parameter
49434          * k1.
49435          */
49436         get: function () {
49437             return this._fill.ck1;
49438         },
49439         enumerable: true,
49440         configurable: true
49441     });
49442     Object.defineProperty(Node.prototype, "ck2", {
49443         /**
49444          * Get ck2.
49445          *
49446          * @description Will not be set if SfM has not been run.
49447          *
49448          * @returns {number} SfM computed radial distortion parameter
49449          * k2.
49450          */
49451         get: function () {
49452             return this._fill.ck2;
49453         },
49454         enumerable: true,
49455         configurable: true
49456     });
49457     Object.defineProperty(Node.prototype, "computedCA", {
49458         /**
49459          * Get computedCA.
49460          *
49461          * @description Will not be set if SfM has not been run.
49462          *
49463          * @returns {number} SfM computed compass angle, measured
49464          * in degrees clockwise with respect to north.
49465          */
49466         get: function () {
49467             return this._fill.cca;
49468         },
49469         enumerable: true,
49470         configurable: true
49471     });
49472     Object.defineProperty(Node.prototype, "computedLatLon", {
49473         /**
49474          * Get computedLatLon.
49475          *
49476          * @description Will not be set if SfM has not been run.
49477          *
49478          * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
49479          * measured in degrees.
49480          */
49481         get: function () {
49482             return this._core.cl;
49483         },
49484         enumerable: true,
49485         configurable: true
49486     });
49487     Object.defineProperty(Node.prototype, "focal", {
49488         /**
49489          * Get focal.
49490          *
49491          * @description Will not be set if SfM has not been run.
49492          *
49493          * @returns {number} SfM computed focal length.
49494          */
49495         get: function () {
49496             return this._fill.cfocal;
49497         },
49498         enumerable: true,
49499         configurable: true
49500     });
49501     Object.defineProperty(Node.prototype, "full", {
49502         /**
49503          * Get full.
49504          *
49505          * @description The library ensures that the current node will
49506          * always be full.
49507          *
49508          * @returns {boolean} Value indicating whether the node has all
49509          * properties filled.
49510          *
49511          * @ignore
49512          */
49513         get: function () {
49514             return this._fill != null;
49515         },
49516         enumerable: true,
49517         configurable: true
49518     });
49519     Object.defineProperty(Node.prototype, "fullPano", {
49520         /**
49521          * Get fullPano.
49522          *
49523          * @returns {boolean} Value indicating whether the node is a complete
49524          * 360 panorama.
49525          */
49526         get: function () {
49527             return this._fill.gpano != null &&
49528                 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
49529                 this._fill.gpano.CroppedAreaTopPixels === 0 &&
49530                 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
49531                 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
49532         },
49533         enumerable: true,
49534         configurable: true
49535     });
49536     Object.defineProperty(Node.prototype, "gpano", {
49537         /**
49538          * Get gpano.
49539          *
49540          * @description Will not be set for non panoramic images.
49541          *
49542          * @returns {IGPano} Panorama information for panorama images.
49543          */
49544         get: function () {
49545             return this._fill.gpano;
49546         },
49547         enumerable: true,
49548         configurable: true
49549     });
49550     Object.defineProperty(Node.prototype, "height", {
49551         /**
49552          * Get height.
49553          *
49554          * @returns {number} Height of original image, not adjusted
49555          * for orientation.
49556          */
49557         get: function () {
49558             return this._fill.height;
49559         },
49560         enumerable: true,
49561         configurable: true
49562     });
49563     Object.defineProperty(Node.prototype, "image", {
49564         /**
49565          * Get image.
49566          *
49567          * @description The image will always be set on the current node.
49568          *
49569          * @returns {HTMLImageElement} Cached image element of the node.
49570          */
49571         get: function () {
49572             return this._cache.image;
49573         },
49574         enumerable: true,
49575         configurable: true
49576     });
49577     Object.defineProperty(Node.prototype, "image$", {
49578         /**
49579          * Get image$.
49580          *
49581          * @returns {Observable<HTMLImageElement>} Observable emitting
49582          * the cached image when it is updated.
49583          *
49584          * @ignore
49585          */
49586         get: function () {
49587             return this._cache.image$;
49588         },
49589         enumerable: true,
49590         configurable: true
49591     });
49592     Object.defineProperty(Node.prototype, "key", {
49593         /**
49594          * Get key.
49595          *
49596          * @returns {string} Unique key of the node.
49597          */
49598         get: function () {
49599             return this._core.key;
49600         },
49601         enumerable: true,
49602         configurable: true
49603     });
49604     Object.defineProperty(Node.prototype, "latLon", {
49605         /**
49606          * Get latLon.
49607          *
49608          * @description If the SfM computed latitude longitude exist
49609          * it will be returned, otherwise the original EXIF latitude
49610          * longitude.
49611          *
49612          * @returns {ILatLon} Latitude longitude in WGS84 datum,
49613          * measured in degrees.
49614          */
49615         get: function () {
49616             return this._core.cl != null ? this._core.cl : this._core.l;
49617         },
49618         enumerable: true,
49619         configurable: true
49620     });
49621     Object.defineProperty(Node.prototype, "loadStatus", {
49622         /**
49623          * Get loadStatus.
49624          *
49625          * @returns {ILoadStatus} Value indicating the load status
49626          * of the mesh and image.
49627          *
49628          * @ignore
49629          */
49630         get: function () {
49631             return this._cache.loadStatus;
49632         },
49633         enumerable: true,
49634         configurable: true
49635     });
49636     Object.defineProperty(Node.prototype, "merged", {
49637         /**
49638          * Get merged.
49639          *
49640          * @returns {boolean} Value indicating whether SfM has been
49641          * run on the node and the node has been merged into a
49642          * connected component.
49643          */
49644         get: function () {
49645             return this._fill != null &&
49646                 this._fill.merge_version != null &&
49647                 this._fill.merge_version > 0;
49648         },
49649         enumerable: true,
49650         configurable: true
49651     });
49652     Object.defineProperty(Node.prototype, "mergeCC", {
49653         /**
49654          * Get mergeCC.
49655          *
49656          * @description Will not be set if SfM has not yet been run on
49657          * node.
49658          *
49659          * @returns {number} SfM connected component key to which
49660          * image belongs.
49661          */
49662         get: function () {
49663             return this._fill.merge_cc;
49664         },
49665         enumerable: true,
49666         configurable: true
49667     });
49668     Object.defineProperty(Node.prototype, "mergeVersion", {
49669         /**
49670          * Get mergeVersion.
49671          *
49672          * @returns {number} Version for which SfM was run and image was merged.
49673          */
49674         get: function () {
49675             return this._fill.merge_version;
49676         },
49677         enumerable: true,
49678         configurable: true
49679     });
49680     Object.defineProperty(Node.prototype, "mesh", {
49681         /**
49682          * Get mesh.
49683          *
49684          * @description The mesh will always be set on the current node.
49685          *
49686          * @returns {IMesh} SfM triangulated mesh of reconstructed
49687          * atomic 3D points.
49688          */
49689         get: function () {
49690             return this._cache.mesh;
49691         },
49692         enumerable: true,
49693         configurable: true
49694     });
49695     Object.defineProperty(Node.prototype, "organizationKey", {
49696         /**
49697          * Get organizationKey.
49698          *
49699          * @returns {string} Unique key of the organization to which
49700          * the node belongs. If the node does not belong to an
49701          * organization the organization key will be undefined.
49702          */
49703         get: function () {
49704             return this._fill.organization_key;
49705         },
49706         enumerable: true,
49707         configurable: true
49708     });
49709     Object.defineProperty(Node.prototype, "orientation", {
49710         /**
49711          * Get orientation.
49712          *
49713          * @returns {number} EXIF orientation of original image.
49714          */
49715         get: function () {
49716             return this._fill.orientation;
49717         },
49718         enumerable: true,
49719         configurable: true
49720     });
49721     Object.defineProperty(Node.prototype, "originalCA", {
49722         /**
49723          * Get originalCA.
49724          *
49725          * @returns {number} Original EXIF compass angle, measured in
49726          * degrees.
49727          */
49728         get: function () {
49729             return this._fill.ca;
49730         },
49731         enumerable: true,
49732         configurable: true
49733     });
49734     Object.defineProperty(Node.prototype, "originalLatLon", {
49735         /**
49736          * Get originalLatLon.
49737          *
49738          * @returns {ILatLon} Original EXIF latitude longitude in
49739          * WGS84 datum, measured in degrees.
49740          */
49741         get: function () {
49742             return this._core.l;
49743         },
49744         enumerable: true,
49745         configurable: true
49746     });
49747     Object.defineProperty(Node.prototype, "pano", {
49748         /**
49749          * Get pano.
49750          *
49751          * @returns {boolean} Value indicating whether the node is a panorama.
49752          * It could be a cropped or full panorama.
49753          */
49754         get: function () {
49755             return this._fill.gpano != null &&
49756                 this._fill.gpano.FullPanoWidthPixels != null;
49757         },
49758         enumerable: true,
49759         configurable: true
49760     });
49761     Object.defineProperty(Node.prototype, "private", {
49762         /**
49763          * Get private.
49764          *
49765          * @returns {boolean} Value specifying if image is accessible to
49766          * organization members only or to everyone.
49767          */
49768         get: function () {
49769             return this._fill.private;
49770         },
49771         enumerable: true,
49772         configurable: true
49773     });
49774     Object.defineProperty(Node.prototype, "projectKey", {
49775         /**
49776          * Get projectKey.
49777          *
49778          * @returns {string} Unique key of the project to which
49779          * the node belongs. If the node does not belong to a
49780          * project the project key will be undefined.
49781          *
49782          * @deprecated This property will be deprecated in favor
49783          * of the organization key and private properties.
49784          */
49785         get: function () {
49786             return this._fill.project != null ?
49787                 this._fill.project.key :
49788                 null;
49789         },
49790         enumerable: true,
49791         configurable: true
49792     });
49793     Object.defineProperty(Node.prototype, "rotation", {
49794         /**
49795          * Get rotation.
49796          *
49797          * @description Will not be set if SfM has not been run.
49798          *
49799          * @returns {Array<number>} Rotation vector in angle axis representation.
49800          */
49801         get: function () {
49802             return this._fill.c_rotation;
49803         },
49804         enumerable: true,
49805         configurable: true
49806     });
49807     Object.defineProperty(Node.prototype, "scale", {
49808         /**
49809          * Get scale.
49810          *
49811          * @description Will not be set if SfM has not been run.
49812          *
49813          * @returns {number} Scale of atomic reconstruction.
49814          */
49815         get: function () {
49816             return this._fill.atomic_scale;
49817         },
49818         enumerable: true,
49819         configurable: true
49820     });
49821     Object.defineProperty(Node.prototype, "sequenceKey", {
49822         /**
49823          * Get sequenceKey.
49824          *
49825          * @returns {string} Unique key of the sequence to which
49826          * the node belongs.
49827          */
49828         get: function () {
49829             return this._core.sequence_key;
49830         },
49831         enumerable: true,
49832         configurable: true
49833     });
49834     Object.defineProperty(Node.prototype, "sequenceEdges", {
49835         /**
49836          * Get sequenceEdges.
49837          *
49838          * @returns {IEdgeStatus} Value describing the status of the
49839          * sequence edges.
49840          *
49841          * @ignore
49842          */
49843         get: function () {
49844             return this._cache.sequenceEdges;
49845         },
49846         enumerable: true,
49847         configurable: true
49848     });
49849     Object.defineProperty(Node.prototype, "sequenceEdges$", {
49850         /**
49851          * Get sequenceEdges$.
49852          *
49853          * @description Internal observable, should not be used as an API.
49854          *
49855          * @returns {Observable<IEdgeStatus>} Observable emitting
49856          * values describing the status of the sequence edges.
49857          *
49858          * @ignore
49859          */
49860         get: function () {
49861             return this._cache.sequenceEdges$;
49862         },
49863         enumerable: true,
49864         configurable: true
49865     });
49866     Object.defineProperty(Node.prototype, "spatialEdges", {
49867         /**
49868          * Get spatialEdges.
49869          *
49870          * @returns {IEdgeStatus} Value describing the status of the
49871          * spatial edges.
49872          *
49873          * @ignore
49874          */
49875         get: function () {
49876             return this._cache.spatialEdges;
49877         },
49878         enumerable: true,
49879         configurable: true
49880     });
49881     Object.defineProperty(Node.prototype, "spatialEdges$", {
49882         /**
49883          * Get spatialEdges$.
49884          *
49885          * @description Internal observable, should not be used as an API.
49886          *
49887          * @returns {Observable<IEdgeStatus>} Observable emitting
49888          * values describing the status of the spatial edges.
49889          *
49890          * @ignore
49891          */
49892         get: function () {
49893             return this._cache.spatialEdges$;
49894         },
49895         enumerable: true,
49896         configurable: true
49897     });
49898     Object.defineProperty(Node.prototype, "userKey", {
49899         /**
49900          * Get userKey.
49901          *
49902          * @returns {string} Unique key of the user who uploaded
49903          * the image.
49904          */
49905         get: function () {
49906             return this._fill.user.key;
49907         },
49908         enumerable: true,
49909         configurable: true
49910     });
49911     Object.defineProperty(Node.prototype, "username", {
49912         /**
49913          * Get username.
49914          *
49915          * @returns {string} Username of the user who uploaded
49916          * the image.
49917          */
49918         get: function () {
49919             return this._fill.user.username;
49920         },
49921         enumerable: true,
49922         configurable: true
49923     });
49924     Object.defineProperty(Node.prototype, "width", {
49925         /**
49926          * Get width.
49927          *
49928          * @returns {number} Width of original image, not
49929          * adjusted for orientation.
49930          */
49931         get: function () {
49932             return this._fill.width;
49933         },
49934         enumerable: true,
49935         configurable: true
49936     });
49937     /**
49938      * Cache the image and mesh assets.
49939      *
49940      * @description The assets are always cached internally by the
49941      * library prior to setting a node as the current node.
49942      *
49943      * @returns {Observable<Node>} Observable emitting this node whenever the
49944      * load status has changed and when the mesh or image has been fully loaded.
49945      *
49946      * @ignore
49947      */
49948     Node.prototype.cacheAssets$ = function () {
49949         var _this = this;
49950         return this._cache.cacheAssets$(this.key, this.pano, this.merged).pipe(operators_1.map(function () {
49951             return _this;
49952         }));
49953     };
49954     /**
49955      * Cache the image asset.
49956      *
49957      * @description Use for caching a differently sized image than
49958      * the one currently held by the node.
49959      *
49960      * @returns {Observable<Node>} Observable emitting this node whenever the
49961      * load status has changed and when the mesh or image has been fully loaded.
49962      *
49963      * @ignore
49964      */
49965     Node.prototype.cacheImage$ = function (imageSize) {
49966         var _this = this;
49967         return this._cache.cacheImage$(this.key, imageSize).pipe(operators_1.map(function () {
49968             return _this;
49969         }));
49970     };
49971     /**
49972      * Cache the sequence edges.
49973      *
49974      * @description The sequence edges are cached asynchronously
49975      * internally by the library.
49976      *
49977      * @param {Array<IEdge>} edges - Sequence edges to cache.
49978      * @ignore
49979      */
49980     Node.prototype.cacheSequenceEdges = function (edges) {
49981         this._cache.cacheSequenceEdges(edges);
49982     };
49983     /**
49984      * Cache the spatial edges.
49985      *
49986      * @description The spatial edges are cached asynchronously
49987      * internally by the library.
49988      *
49989      * @param {Array<IEdge>} edges - Spatial edges to cache.
49990      * @ignore
49991      */
49992     Node.prototype.cacheSpatialEdges = function (edges) {
49993         this._cache.cacheSpatialEdges(edges);
49994     };
49995     /**
49996      * Dispose the node.
49997      *
49998      * @description Disposes all cached assets.
49999      * @ignore
50000      */
50001     Node.prototype.dispose = function () {
50002         if (this._cache != null) {
50003             this._cache.dispose();
50004             this._cache = null;
50005         }
50006         this._core = null;
50007         this._fill = null;
50008     };
50009     /**
50010      * Initialize the node cache.
50011      *
50012      * @description The node cache is initialized internally by
50013      * the library.
50014      *
50015      * @param {NodeCache} cache - The node cache to set as cache.
50016      * @ignore
50017      */
50018     Node.prototype.initializeCache = function (cache) {
50019         if (this._cache != null) {
50020             throw new Error("Node cache already initialized (" + this.key + ").");
50021         }
50022         this._cache = cache;
50023     };
50024     /**
50025      * Fill the node with all properties.
50026      *
50027      * @description The node is filled internally by
50028      * the library.
50029      *
50030      * @param {IFillNode} fill - The fill node struct.
50031      * @ignore
50032      */
50033     Node.prototype.makeFull = function (fill) {
50034         if (fill == null) {
50035             throw new Error("Fill can not be null.");
50036         }
50037         this._fill = fill;
50038     };
50039     /**
50040      * Reset the sequence edges.
50041      *
50042      * @ignore
50043      */
50044     Node.prototype.resetSequenceEdges = function () {
50045         this._cache.resetSequenceEdges();
50046     };
50047     /**
50048      * Reset the spatial edges.
50049      *
50050      * @ignore
50051      */
50052     Node.prototype.resetSpatialEdges = function () {
50053         this._cache.resetSpatialEdges();
50054     };
50055     /**
50056      * Clears the image and mesh assets, aborts
50057      * any outstanding requests and resets edges.
50058      *
50059      * @ignore
50060      */
50061     Node.prototype.uncache = function () {
50062         if (this._cache == null) {
50063             return;
50064         }
50065         this._cache.dispose();
50066         this._cache = null;
50067     };
50068     return Node;
50069 }());
50070 exports.Node = Node;
50071 exports.default = Node;
50072
50073 },{"rxjs/operators":241}],423:[function(require,module,exports){
50074 (function (Buffer){
50075 "use strict";
50076 Object.defineProperty(exports, "__esModule", { value: true });
50077 var rxjs_1 = require("rxjs");
50078 var operators_1 = require("rxjs/operators");
50079 var Graph_1 = require("../Graph");
50080 var Utils_1 = require("../Utils");
50081 /**
50082  * @class NodeCache
50083  *
50084  * @classdesc Represents the cached properties of a node.
50085  */
50086 var NodeCache = /** @class */ (function () {
50087     /**
50088      * Create a new node cache instance.
50089      */
50090     function NodeCache() {
50091         this._disposed = false;
50092         this._image = null;
50093         this._loadStatus = { loaded: 0, total: 0 };
50094         this._mesh = null;
50095         this._sequenceEdges = { cached: false, edges: [] };
50096         this._spatialEdges = { cached: false, edges: [] };
50097         this._imageChanged$ = new rxjs_1.Subject();
50098         this._image$ = this._imageChanged$.pipe(operators_1.startWith(null), operators_1.publishReplay(1), operators_1.refCount());
50099         this._iamgeSubscription = this._image$.subscribe();
50100         this._sequenceEdgesChanged$ = new rxjs_1.Subject();
50101         this._sequenceEdges$ = this._sequenceEdgesChanged$.pipe(operators_1.startWith(this._sequenceEdges), operators_1.publishReplay(1), operators_1.refCount());
50102         this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
50103         this._spatialEdgesChanged$ = new rxjs_1.Subject();
50104         this._spatialEdges$ = this._spatialEdgesChanged$.pipe(operators_1.startWith(this._spatialEdges), operators_1.publishReplay(1), operators_1.refCount());
50105         this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
50106         this._cachingAssets$ = null;
50107     }
50108     Object.defineProperty(NodeCache.prototype, "image", {
50109         /**
50110          * Get image.
50111          *
50112          * @description Will not be set when assets have not been cached
50113          * or when the object has been disposed.
50114          *
50115          * @returns {HTMLImageElement} Cached image element of the node.
50116          */
50117         get: function () {
50118             return this._image;
50119         },
50120         enumerable: true,
50121         configurable: true
50122     });
50123     Object.defineProperty(NodeCache.prototype, "image$", {
50124         /**
50125          * Get image$.
50126          *
50127          * @returns {Observable<HTMLImageElement>} Observable emitting
50128          * the cached image when it is updated.
50129          */
50130         get: function () {
50131             return this._image$;
50132         },
50133         enumerable: true,
50134         configurable: true
50135     });
50136     Object.defineProperty(NodeCache.prototype, "loadStatus", {
50137         /**
50138          * Get loadStatus.
50139          *
50140          * @returns {ILoadStatus} Value indicating the load status
50141          * of the mesh and image.
50142          */
50143         get: function () {
50144             return this._loadStatus;
50145         },
50146         enumerable: true,
50147         configurable: true
50148     });
50149     Object.defineProperty(NodeCache.prototype, "mesh", {
50150         /**
50151          * Get mesh.
50152          *
50153          * @description Will not be set when assets have not been cached
50154          * or when the object has been disposed.
50155          *
50156          * @returns {IMesh} SfM triangulated mesh of reconstructed
50157          * atomic 3D points.
50158          */
50159         get: function () {
50160             return this._mesh;
50161         },
50162         enumerable: true,
50163         configurable: true
50164     });
50165     Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
50166         /**
50167          * Get sequenceEdges.
50168          *
50169          * @returns {IEdgeStatus} Value describing the status of the
50170          * sequence edges.
50171          */
50172         get: function () {
50173             return this._sequenceEdges;
50174         },
50175         enumerable: true,
50176         configurable: true
50177     });
50178     Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
50179         /**
50180          * Get sequenceEdges$.
50181          *
50182          * @returns {Observable<IEdgeStatus>} Observable emitting
50183          * values describing the status of the sequence edges.
50184          */
50185         get: function () {
50186             return this._sequenceEdges$;
50187         },
50188         enumerable: true,
50189         configurable: true
50190     });
50191     Object.defineProperty(NodeCache.prototype, "spatialEdges", {
50192         /**
50193          * Get spatialEdges.
50194          *
50195          * @returns {IEdgeStatus} Value describing the status of the
50196          * spatial edges.
50197          */
50198         get: function () {
50199             return this._spatialEdges;
50200         },
50201         enumerable: true,
50202         configurable: true
50203     });
50204     Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
50205         /**
50206          * Get spatialEdges$.
50207          *
50208          * @returns {Observable<IEdgeStatus>} Observable emitting
50209          * values describing the status of the spatial edges.
50210          */
50211         get: function () {
50212             return this._spatialEdges$;
50213         },
50214         enumerable: true,
50215         configurable: true
50216     });
50217     /**
50218      * Cache the image and mesh assets.
50219      *
50220      * @param {string} key - Key of the node to cache.
50221      * @param {boolean} pano - Value indicating whether node is a panorama.
50222      * @param {boolean} merged - Value indicating whether node is merged.
50223      * @returns {Observable<NodeCache>} Observable emitting this node
50224      * cache whenever the load status has changed and when the mesh or image
50225      * has been fully loaded.
50226      */
50227     NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
50228         var _this = this;
50229         if (this._cachingAssets$ != null) {
50230             return this._cachingAssets$;
50231         }
50232         var imageSize = pano ?
50233             Utils_1.Settings.basePanoramaSize :
50234             Utils_1.Settings.baseImageSize;
50235         this._cachingAssets$ = rxjs_1.combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged)).pipe(operators_1.map(function (_a) {
50236             var imageStatus = _a[0], meshStatus = _a[1];
50237             _this._loadStatus.loaded = 0;
50238             _this._loadStatus.total = 0;
50239             if (meshStatus) {
50240                 _this._mesh = meshStatus.object;
50241                 _this._loadStatus.loaded += meshStatus.loaded.loaded;
50242                 _this._loadStatus.total += meshStatus.loaded.total;
50243             }
50244             if (imageStatus) {
50245                 _this._image = imageStatus.object;
50246                 _this._loadStatus.loaded += imageStatus.loaded.loaded;
50247                 _this._loadStatus.total += imageStatus.loaded.total;
50248             }
50249             return _this;
50250         }), operators_1.finalize(function () {
50251             _this._cachingAssets$ = null;
50252         }), operators_1.publishReplay(1), operators_1.refCount());
50253         this._cachingAssets$.pipe(operators_1.first(function (nodeCache) {
50254             return !!nodeCache._image;
50255         }))
50256             .subscribe(function (nodeCache) {
50257             _this._imageChanged$.next(_this._image);
50258         }, function (error) { });
50259         return this._cachingAssets$;
50260     };
50261     /**
50262      * Cache an image with a higher resolution than the current one.
50263      *
50264      * @param {string} key - Key of the node to cache.
50265      * @param {ImageSize} imageSize - The size to cache.
50266      * @returns {Observable<NodeCache>} Observable emitting a single item,
50267      * the node cache, when the image has been cached. If supplied image
50268      * size is not larger than the current image size the node cache is
50269      * returned immediately.
50270      */
50271     NodeCache.prototype.cacheImage$ = function (key, imageSize) {
50272         var _this = this;
50273         if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
50274             return rxjs_1.of(this);
50275         }
50276         var cacheImage$ = this._cacheImage$(key, imageSize).pipe(operators_1.first(function (status) {
50277             return status.object != null;
50278         }), operators_1.tap(function (status) {
50279             _this._disposeImage();
50280             _this._image = status.object;
50281         }), operators_1.map(function (imageStatus) {
50282             return _this;
50283         }), operators_1.publishReplay(1), operators_1.refCount());
50284         cacheImage$
50285             .subscribe(function (nodeCache) {
50286             _this._imageChanged$.next(_this._image);
50287         }, function (error) { });
50288         return cacheImage$;
50289     };
50290     /**
50291      * Cache the sequence edges.
50292      *
50293      * @param {Array<IEdge>} edges - Sequence edges to cache.
50294      */
50295     NodeCache.prototype.cacheSequenceEdges = function (edges) {
50296         this._sequenceEdges = { cached: true, edges: edges };
50297         this._sequenceEdgesChanged$.next(this._sequenceEdges);
50298     };
50299     /**
50300      * Cache the spatial edges.
50301      *
50302      * @param {Array<IEdge>} edges - Spatial edges to cache.
50303      */
50304     NodeCache.prototype.cacheSpatialEdges = function (edges) {
50305         this._spatialEdges = { cached: true, edges: edges };
50306         this._spatialEdgesChanged$.next(this._spatialEdges);
50307     };
50308     /**
50309      * Dispose the node cache.
50310      *
50311      * @description Disposes all cached assets and unsubscribes to
50312      * all streams.
50313      */
50314     NodeCache.prototype.dispose = function () {
50315         this._iamgeSubscription.unsubscribe();
50316         this._sequenceEdgesSubscription.unsubscribe();
50317         this._spatialEdgesSubscription.unsubscribe();
50318         this._disposeImage();
50319         this._mesh = null;
50320         this._loadStatus.loaded = 0;
50321         this._loadStatus.total = 0;
50322         this._sequenceEdges = { cached: false, edges: [] };
50323         this._spatialEdges = { cached: false, edges: [] };
50324         this._imageChanged$.next(null);
50325         this._sequenceEdgesChanged$.next(this._sequenceEdges);
50326         this._spatialEdgesChanged$.next(this._spatialEdges);
50327         this._disposed = true;
50328         if (this._imageRequest != null) {
50329             this._imageRequest.abort();
50330         }
50331         if (this._meshRequest != null) {
50332             this._meshRequest.abort();
50333         }
50334     };
50335     /**
50336      * Reset the sequence edges.
50337      */
50338     NodeCache.prototype.resetSequenceEdges = function () {
50339         this._sequenceEdges = { cached: false, edges: [] };
50340         this._sequenceEdgesChanged$.next(this._sequenceEdges);
50341     };
50342     /**
50343      * Reset the spatial edges.
50344      */
50345     NodeCache.prototype.resetSpatialEdges = function () {
50346         this._spatialEdges = { cached: false, edges: [] };
50347         this._spatialEdgesChanged$.next(this._spatialEdges);
50348     };
50349     /**
50350      * Cache the image.
50351      *
50352      * @param {string} key - Key of the node to cache.
50353      * @param {boolean} pano - Value indicating whether node is a panorama.
50354      * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
50355      * emitting a load status object every time the load status changes
50356      * and completes when the image is fully loaded.
50357      */
50358     NodeCache.prototype._cacheImage$ = function (key, imageSize) {
50359         var _this = this;
50360         return rxjs_1.Observable.create(function (subscriber) {
50361             var xmlHTTP = new XMLHttpRequest();
50362             xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize, Utils_1.Urls.origin), true);
50363             xmlHTTP.responseType = "arraybuffer";
50364             xmlHTTP.timeout = 15000;
50365             xmlHTTP.onload = function (pe) {
50366                 if (xmlHTTP.status !== 200) {
50367                     _this._imageRequest = null;
50368                     subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
50369                     return;
50370                 }
50371                 var image = new Image();
50372                 image.crossOrigin = "Anonymous";
50373                 image.onload = function (e) {
50374                     _this._imageRequest = null;
50375                     if (_this._disposed) {
50376                         window.URL.revokeObjectURL(image.src);
50377                         subscriber.error(new Error("Image load was aborted (" + key + ")"));
50378                         return;
50379                     }
50380                     subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
50381                     subscriber.complete();
50382                 };
50383                 image.onerror = function (error) {
50384                     _this._imageRequest = null;
50385                     subscriber.error(new Error("Failed to load image (" + key + ")"));
50386                 };
50387                 var blob = new Blob([xmlHTTP.response]);
50388                 image.src = window.URL.createObjectURL(blob);
50389             };
50390             xmlHTTP.onprogress = function (pe) {
50391                 if (_this._disposed) {
50392                     return;
50393                 }
50394                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
50395             };
50396             xmlHTTP.onerror = function (error) {
50397                 _this._imageRequest = null;
50398                 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
50399             };
50400             xmlHTTP.ontimeout = function (e) {
50401                 _this._imageRequest = null;
50402                 subscriber.error(new Error("Image request timed out (" + key + ")"));
50403             };
50404             xmlHTTP.onabort = function (event) {
50405                 _this._imageRequest = null;
50406                 subscriber.error(new Error("Image request was aborted (" + key + ")"));
50407             };
50408             _this._imageRequest = xmlHTTP;
50409             xmlHTTP.send(null);
50410         });
50411     };
50412     /**
50413      * Cache the mesh.
50414      *
50415      * @param {string} key - Key of the node to cache.
50416      * @param {boolean} merged - Value indicating whether node is merged.
50417      * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
50418      * a load status object every time the load status changes and completes
50419      * when the mesh is fully loaded.
50420      */
50421     NodeCache.prototype._cacheMesh$ = function (key, merged) {
50422         var _this = this;
50423         return rxjs_1.Observable.create(function (subscriber) {
50424             if (!merged) {
50425                 subscriber.next(_this._createEmptyMeshLoadStatus());
50426                 subscriber.complete();
50427                 return;
50428             }
50429             var xmlHTTP = new XMLHttpRequest();
50430             xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
50431             xmlHTTP.responseType = "arraybuffer";
50432             xmlHTTP.timeout = 15000;
50433             xmlHTTP.onload = function (pe) {
50434                 _this._meshRequest = null;
50435                 if (_this._disposed) {
50436                     return;
50437                 }
50438                 var mesh = xmlHTTP.status === 200 ?
50439                     Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
50440                     { faces: [], vertices: [] };
50441                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
50442                 subscriber.complete();
50443             };
50444             xmlHTTP.onprogress = function (pe) {
50445                 if (_this._disposed) {
50446                     return;
50447                 }
50448                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
50449             };
50450             xmlHTTP.onerror = function (e) {
50451                 _this._meshRequest = null;
50452                 console.error("Failed to cache mesh (" + key + ")");
50453                 subscriber.next(_this._createEmptyMeshLoadStatus());
50454                 subscriber.complete();
50455             };
50456             xmlHTTP.ontimeout = function (e) {
50457                 _this._meshRequest = null;
50458                 console.error("Mesh request timed out (" + key + ")");
50459                 subscriber.next(_this._createEmptyMeshLoadStatus());
50460                 subscriber.complete();
50461             };
50462             xmlHTTP.onabort = function (e) {
50463                 _this._meshRequest = null;
50464                 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
50465             };
50466             _this._meshRequest = xmlHTTP;
50467             xmlHTTP.send(null);
50468         });
50469     };
50470     /**
50471      * Create a load status object with an empty mesh.
50472      *
50473      * @returns {ILoadStatusObject<IMesh>} Load status object
50474      * with empty mesh.
50475      */
50476     NodeCache.prototype._createEmptyMeshLoadStatus = function () {
50477         return {
50478             loaded: { loaded: 0, total: 0 },
50479             object: { faces: [], vertices: [] },
50480         };
50481     };
50482     NodeCache.prototype._disposeImage = function () {
50483         if (this._image != null) {
50484             window.URL.revokeObjectURL(this._image.src);
50485         }
50486         this._image = null;
50487     };
50488     return NodeCache;
50489 }());
50490 exports.NodeCache = NodeCache;
50491 exports.default = NodeCache;
50492
50493 }).call(this,require("buffer").Buffer)
50494
50495 },{"../Graph":295,"../Utils":301,"buffer":7,"rxjs":43,"rxjs/operators":241}],424:[function(require,module,exports){
50496 "use strict";
50497 Object.defineProperty(exports, "__esModule", { value: true });
50498 /**
50499  * @class Sequence
50500  *
50501  * @classdesc Represents a sequence of ordered nodes.
50502  */
50503 var Sequence = /** @class */ (function () {
50504     /**
50505      * Create a new sequene instance.
50506      *
50507      * @param {ISequence} sequence - Raw sequence data.
50508      */
50509     function Sequence(sequence) {
50510         this._key = sequence.key;
50511         this._keys = sequence.keys;
50512     }
50513     Object.defineProperty(Sequence.prototype, "key", {
50514         /**
50515          * Get key.
50516          *
50517          * @returns {string} Unique sequence key.
50518          */
50519         get: function () {
50520             return this._key;
50521         },
50522         enumerable: true,
50523         configurable: true
50524     });
50525     Object.defineProperty(Sequence.prototype, "keys", {
50526         /**
50527          * Get keys.
50528          *
50529          * @returns {Array<string>} Array of ordered node keys in the sequence.
50530          */
50531         get: function () {
50532             return this._keys;
50533         },
50534         enumerable: true,
50535         configurable: true
50536     });
50537     /**
50538      * Dispose the sequence.
50539      *
50540      * @description Disposes all cached assets.
50541      */
50542     Sequence.prototype.dispose = function () {
50543         this._key = null;
50544         this._keys = null;
50545     };
50546     /**
50547      * Find the next node key in the sequence with respect to
50548      * the provided node key.
50549      *
50550      * @param {string} key - Reference node key.
50551      * @returns {string} Next key in sequence if it exists, null otherwise.
50552      */
50553     Sequence.prototype.findNextKey = function (key) {
50554         var i = this._keys.indexOf(key);
50555         if ((i + 1) >= this._keys.length || i === -1) {
50556             return null;
50557         }
50558         else {
50559             return this._keys[i + 1];
50560         }
50561     };
50562     /**
50563      * Find the previous node key in the sequence with respect to
50564      * the provided node key.
50565      *
50566      * @param {string} key - Reference node key.
50567      * @returns {string} Previous key in sequence if it exists, null otherwise.
50568      */
50569     Sequence.prototype.findPrevKey = function (key) {
50570         var i = this._keys.indexOf(key);
50571         if (i === 0 || i === -1) {
50572             return null;
50573         }
50574         else {
50575             return this._keys[i - 1];
50576         }
50577     };
50578     return Sequence;
50579 }());
50580 exports.Sequence = Sequence;
50581 exports.default = Sequence;
50582
50583 },{}],425:[function(require,module,exports){
50584 "use strict";
50585 Object.defineProperty(exports, "__esModule", { value: true });
50586 var THREE = require("three");
50587 var Edge_1 = require("../../Edge");
50588 var Error_1 = require("../../Error");
50589 var Geo_1 = require("../../Geo");
50590 /**
50591  * @class EdgeCalculator
50592  *
50593  * @classdesc Represents a class for calculating node edges.
50594  */
50595 var EdgeCalculator = /** @class */ (function () {
50596     /**
50597      * Create a new edge calculator instance.
50598      *
50599      * @param {EdgeCalculatorSettings} settings - Settings struct.
50600      * @param {EdgeCalculatorDirections} directions - Directions struct.
50601      * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
50602      */
50603     function EdgeCalculator(settings, directions, coefficients) {
50604         this._spatial = new Geo_1.Spatial();
50605         this._geoCoords = new Geo_1.GeoCoords();
50606         this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
50607         this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
50608         this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
50609     }
50610     /**
50611      * Returns the potential edges to destination nodes for a set
50612      * of nodes with respect to a source node.
50613      *
50614      * @param {Node} node - Source node.
50615      * @param {Array<Node>} nodes - Potential destination nodes.
50616      * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
50617      * be returned even if they do not meet the criteria for a potential edge.
50618      * @throws {ArgumentMapillaryError} If node is not full.
50619      */
50620     EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
50621         if (!node.full) {
50622             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
50623         }
50624         if (!node.merged) {
50625             return [];
50626         }
50627         var currentDirection = this._spatial.viewingDirection(node.rotation);
50628         var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
50629         var potentialEdges = [];
50630         for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
50631             var potential = potentialNodes_1[_i];
50632             if (!potential.merged ||
50633                 potential.key === node.key) {
50634                 continue;
50635             }
50636             var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
50637             var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
50638             var distance = motion.length();
50639             if (distance > this._settings.maxDistance &&
50640                 fallbackKeys.indexOf(potential.key) < 0) {
50641                 continue;
50642             }
50643             var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
50644             var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
50645             var direction = this._spatial.viewingDirection(potential.rotation);
50646             var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
50647             var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
50648             var verticalDirectionChange = verticalDirection - currentVerticalDirection;
50649             var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
50650             var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
50651             var sameSequence = potential.sequenceKey != null &&
50652                 node.sequenceKey != null &&
50653                 potential.sequenceKey === node.sequenceKey;
50654             var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
50655                 potential.mergeCC === node.mergeCC;
50656             var sameUser = potential.userKey === node.userKey;
50657             var potentialEdge = {
50658                 capturedAt: potential.capturedAt,
50659                 croppedPano: potential.pano && !potential.fullPano,
50660                 directionChange: directionChange,
50661                 distance: distance,
50662                 fullPano: potential.fullPano,
50663                 key: potential.key,
50664                 motionChange: motionChange,
50665                 rotation: rotation,
50666                 sameMergeCC: sameMergeCC,
50667                 sameSequence: sameSequence,
50668                 sameUser: sameUser,
50669                 sequenceKey: potential.sequenceKey,
50670                 verticalDirectionChange: verticalDirectionChange,
50671                 verticalMotion: verticalMotion,
50672                 worldMotionAzimuth: worldMotionAzimuth,
50673             };
50674             potentialEdges.push(potentialEdge);
50675         }
50676         return potentialEdges;
50677     };
50678     /**
50679      * Computes the sequence edges for a node.
50680      *
50681      * @param {Node} node - Source node.
50682      * @throws {ArgumentMapillaryError} If node is not full.
50683      */
50684     EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
50685         if (!node.full) {
50686             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
50687         }
50688         if (node.sequenceKey !== sequence.key) {
50689             throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
50690         }
50691         var edges = [];
50692         var nextKey = sequence.findNextKey(node.key);
50693         if (nextKey != null) {
50694             edges.push({
50695                 data: {
50696                     direction: Edge_1.EdgeDirection.Next,
50697                     worldMotionAzimuth: Number.NaN,
50698                 },
50699                 from: node.key,
50700                 to: nextKey,
50701             });
50702         }
50703         var prevKey = sequence.findPrevKey(node.key);
50704         if (prevKey != null) {
50705             edges.push({
50706                 data: {
50707                     direction: Edge_1.EdgeDirection.Prev,
50708                     worldMotionAzimuth: Number.NaN,
50709                 },
50710                 from: node.key,
50711                 to: prevKey,
50712             });
50713         }
50714         return edges;
50715     };
50716     /**
50717      * Computes the similar edges for a node.
50718      *
50719      * @description Similar edges for perspective images and cropped panoramas
50720      * look roughly in the same direction and are positioned closed to the node.
50721      * Similar edges for full panoramas only target other full panoramas.
50722      *
50723      * @param {Node} node - Source node.
50724      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
50725      * @throws {ArgumentMapillaryError} If node is not full.
50726      */
50727     EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
50728         var _this = this;
50729         if (!node.full) {
50730             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
50731         }
50732         var nodeFullPano = node.fullPano;
50733         var sequenceGroups = {};
50734         for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
50735             var potentialEdge = potentialEdges_1[_i];
50736             if (potentialEdge.sequenceKey == null) {
50737                 continue;
50738             }
50739             if (potentialEdge.sameSequence) {
50740                 continue;
50741             }
50742             if (nodeFullPano) {
50743                 if (!potentialEdge.fullPano) {
50744                     continue;
50745                 }
50746             }
50747             else {
50748                 if (!potentialEdge.fullPano &&
50749                     Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
50750                     continue;
50751                 }
50752             }
50753             if (potentialEdge.distance > this._settings.similarMaxDistance) {
50754                 continue;
50755             }
50756             if (potentialEdge.sameUser &&
50757                 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
50758                     this._settings.similarMinTimeDifference) {
50759                 continue;
50760             }
50761             if (sequenceGroups[potentialEdge.sequenceKey] == null) {
50762                 sequenceGroups[potentialEdge.sequenceKey] = [];
50763             }
50764             sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
50765         }
50766         var similarEdges = [];
50767         var calculateScore = node.fullPano ?
50768             function (potentialEdge) {
50769                 return potentialEdge.distance;
50770             } :
50771             function (potentialEdge) {
50772                 return _this._coefficients.similarDistance * potentialEdge.distance +
50773                     _this._coefficients.similarRotation * potentialEdge.rotation;
50774             };
50775         for (var sequenceKey in sequenceGroups) {
50776             if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
50777                 continue;
50778             }
50779             var lowestScore = Number.MAX_VALUE;
50780             var similarEdge = null;
50781             for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
50782                 var potentialEdge = _b[_a];
50783                 var score = calculateScore(potentialEdge);
50784                 if (score < lowestScore) {
50785                     lowestScore = score;
50786                     similarEdge = potentialEdge;
50787                 }
50788             }
50789             if (similarEdge == null) {
50790                 continue;
50791             }
50792             similarEdges.push(similarEdge);
50793         }
50794         return similarEdges
50795             .map(function (potentialEdge) {
50796             return {
50797                 data: {
50798                     direction: Edge_1.EdgeDirection.Similar,
50799                     worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
50800                 },
50801                 from: node.key,
50802                 to: potentialEdge.key,
50803             };
50804         });
50805     };
50806     /**
50807      * Computes the step edges for a perspective node.
50808      *
50809      * @description Step edge targets can only be other perspective nodes.
50810      * Returns an empty array for cropped and full panoramas.
50811      *
50812      * @param {Node} node - Source node.
50813      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
50814      * @param {string} prevKey - Key of previous node in sequence.
50815      * @param {string} prevKey - Key of next node in sequence.
50816      * @throws {ArgumentMapillaryError} If node is not full.
50817      */
50818     EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
50819         if (!node.full) {
50820             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
50821         }
50822         var edges = [];
50823         if (node.pano) {
50824             return edges;
50825         }
50826         for (var k in this._directions.steps) {
50827             if (!this._directions.steps.hasOwnProperty(k)) {
50828                 continue;
50829             }
50830             var step = this._directions.steps[k];
50831             var lowestScore = Number.MAX_VALUE;
50832             var edge = null;
50833             var fallback = null;
50834             for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
50835                 var potential = potentialEdges_2[_i];
50836                 if (potential.croppedPano || potential.fullPano) {
50837                     continue;
50838                 }
50839                 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
50840                     continue;
50841                 }
50842                 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
50843                 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
50844                 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
50845                 if (Math.abs(drift) > this._settings.stepMaxDrift) {
50846                     continue;
50847                 }
50848                 var potentialKey = potential.key;
50849                 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
50850                     fallback = potential;
50851                 }
50852                 if (potential.distance > this._settings.stepMaxDistance) {
50853                     continue;
50854                 }
50855                 motionDifference = Math.sqrt(motionDifference * motionDifference +
50856                     potential.verticalMotion * potential.verticalMotion);
50857                 var score = this._coefficients.stepPreferredDistance *
50858                     Math.abs(potential.distance - this._settings.stepPreferredDistance) /
50859                     this._settings.stepMaxDistance +
50860                     this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
50861                     this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
50862                     this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
50863                     this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
50864                 if (score < lowestScore) {
50865                     lowestScore = score;
50866                     edge = potential;
50867                 }
50868             }
50869             edge = edge == null ? fallback : edge;
50870             if (edge != null) {
50871                 edges.push({
50872                     data: {
50873                         direction: step.direction,
50874                         worldMotionAzimuth: edge.worldMotionAzimuth,
50875                     },
50876                     from: node.key,
50877                     to: edge.key,
50878                 });
50879             }
50880         }
50881         return edges;
50882     };
50883     /**
50884      * Computes the turn edges for a perspective node.
50885      *
50886      * @description Turn edge targets can only be other perspective images.
50887      * Returns an empty array for cropped and full panoramas.
50888      *
50889      * @param {Node} node - Source node.
50890      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
50891      * @throws {ArgumentMapillaryError} If node is not full.
50892      */
50893     EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
50894         if (!node.full) {
50895             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
50896         }
50897         var edges = [];
50898         if (node.pano) {
50899             return edges;
50900         }
50901         for (var k in this._directions.turns) {
50902             if (!this._directions.turns.hasOwnProperty(k)) {
50903                 continue;
50904             }
50905             var turn = this._directions.turns[k];
50906             var lowestScore = Number.MAX_VALUE;
50907             var edge = null;
50908             for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
50909                 var potential = potentialEdges_3[_i];
50910                 if (potential.croppedPano || potential.fullPano) {
50911                     continue;
50912                 }
50913                 if (potential.distance > this._settings.turnMaxDistance) {
50914                     continue;
50915                 }
50916                 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
50917                     potential.distance < this._settings.turnMaxRigDistance &&
50918                     Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
50919                 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
50920                 var score = void 0;
50921                 if (rig &&
50922                     potential.directionChange * turn.directionChange > 0 &&
50923                     Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
50924                     score = -Math.PI / 2 + Math.abs(potential.directionChange);
50925                 }
50926                 else {
50927                     if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
50928                         continue;
50929                     }
50930                     var motionDifference = turn.motionChange ?
50931                         this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
50932                     motionDifference = Math.sqrt(motionDifference * motionDifference +
50933                         potential.verticalMotion * potential.verticalMotion);
50934                     score =
50935                         this._coefficients.turnDistance * potential.distance /
50936                             this._settings.turnMaxDistance +
50937                             this._coefficients.turnMotion * motionDifference / Math.PI +
50938                             this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
50939                             this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
50940                 }
50941                 if (score < lowestScore) {
50942                     lowestScore = score;
50943                     edge = potential;
50944                 }
50945             }
50946             if (edge != null) {
50947                 edges.push({
50948                     data: {
50949                         direction: turn.direction,
50950                         worldMotionAzimuth: edge.worldMotionAzimuth,
50951                     },
50952                     from: node.key,
50953                     to: edge.key,
50954                 });
50955             }
50956         }
50957         return edges;
50958     };
50959     /**
50960      * Computes the pano edges for a perspective node.
50961      *
50962      * @description Perspective to pano edge targets can only be
50963      * full pano nodes. Returns an empty array for cropped and full panoramas.
50964      *
50965      * @param {Node} node - Source node.
50966      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
50967      * @throws {ArgumentMapillaryError} If node is not full.
50968      */
50969     EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
50970         if (!node.full) {
50971             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
50972         }
50973         if (node.pano) {
50974             return [];
50975         }
50976         var lowestScore = Number.MAX_VALUE;
50977         var edge = null;
50978         for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
50979             var potential = potentialEdges_4[_i];
50980             if (!potential.fullPano) {
50981                 continue;
50982             }
50983             var score = this._coefficients.panoPreferredDistance *
50984                 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
50985                 this._settings.panoMaxDistance +
50986                 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
50987                 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
50988             if (score < lowestScore) {
50989                 lowestScore = score;
50990                 edge = potential;
50991             }
50992         }
50993         if (edge == null) {
50994             return [];
50995         }
50996         return [
50997             {
50998                 data: {
50999                     direction: Edge_1.EdgeDirection.Pano,
51000                     worldMotionAzimuth: edge.worldMotionAzimuth,
51001                 },
51002                 from: node.key,
51003                 to: edge.key,
51004             },
51005         ];
51006     };
51007     /**
51008      * Computes the full pano and step edges for a full pano node.
51009      *
51010      * @description Pano to pano edge targets can only be
51011      * full pano nodes. Pano to step edge targets can only be perspective
51012      * nodes.
51013      * Returns an empty array for cropped panoramas and perspective nodes.
51014      *
51015      * @param {Node} node - Source node.
51016      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
51017      * @throws {ArgumentMapillaryError} If node is not full.
51018      */
51019     EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
51020         if (!node.full) {
51021             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
51022         }
51023         if (!node.fullPano) {
51024             return [];
51025         }
51026         var panoEdges = [];
51027         var potentialPanos = [];
51028         var potentialSteps = [];
51029         for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
51030             var potential = potentialEdges_5[_i];
51031             if (potential.distance > this._settings.panoMaxDistance) {
51032                 continue;
51033             }
51034             if (potential.fullPano) {
51035                 if (potential.distance < this._settings.panoMinDistance) {
51036                     continue;
51037                 }
51038                 potentialPanos.push(potential);
51039             }
51040             else {
51041                 if (potential.croppedPano) {
51042                     continue;
51043                 }
51044                 for (var k in this._directions.panos) {
51045                     if (!this._directions.panos.hasOwnProperty(k)) {
51046                         continue;
51047                     }
51048                     var pano = this._directions.panos[k];
51049                     var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
51050                     var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
51051                     if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
51052                         continue;
51053                     }
51054                     potentialSteps.push([pano.direction, potential]);
51055                     // break if step direction found
51056                     break;
51057                 }
51058             }
51059         }
51060         var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
51061         var occupiedAngles = [];
51062         var stepAngles = [];
51063         for (var index = 0; index < this._settings.panoMaxItems; index++) {
51064             var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
51065             var lowestScore = Number.MAX_VALUE;
51066             var edge = null;
51067             for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
51068                 var potential = potentialPanos_1[_a];
51069                 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
51070                 if (Math.abs(motionDifference) > maxRotationDifference) {
51071                     continue;
51072                 }
51073                 var occupiedDifference = Number.MAX_VALUE;
51074                 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
51075                     var occupiedAngle = occupiedAngles_1[_b];
51076                     var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
51077                     if (difference < occupiedDifference) {
51078                         occupiedDifference = difference;
51079                     }
51080                 }
51081                 if (occupiedDifference <= maxRotationDifference) {
51082                     continue;
51083                 }
51084                 var score = this._coefficients.panoPreferredDistance *
51085                     Math.abs(potential.distance - this._settings.panoPreferredDistance) /
51086                     this._settings.panoMaxDistance +
51087                     this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
51088                     this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
51089                     this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
51090                 if (score < lowestScore) {
51091                     lowestScore = score;
51092                     edge = potential;
51093                 }
51094             }
51095             if (edge != null) {
51096                 occupiedAngles.push(edge.motionChange);
51097                 panoEdges.push({
51098                     data: {
51099                         direction: Edge_1.EdgeDirection.Pano,
51100                         worldMotionAzimuth: edge.worldMotionAzimuth,
51101                     },
51102                     from: node.key,
51103                     to: edge.key,
51104                 });
51105             }
51106             else {
51107                 stepAngles.push(rotation);
51108             }
51109         }
51110         var occupiedStepAngles = {};
51111         occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
51112         occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
51113         occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
51114         occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
51115         occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
51116         for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
51117             var stepAngle = stepAngles_1[_c];
51118             var occupations = [];
51119             for (var k in this._directions.panos) {
51120                 if (!this._directions.panos.hasOwnProperty(k)) {
51121                     continue;
51122                 }
51123                 var pano = this._directions.panos[k];
51124                 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
51125                     .concat(occupiedStepAngles[pano.direction])
51126                     .concat(occupiedStepAngles[pano.prev])
51127                     .concat(occupiedStepAngles[pano.next]);
51128                 var lowestScore = Number.MAX_VALUE;
51129                 var edge = null;
51130                 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
51131                     var potential = potentialSteps_1[_d];
51132                     if (potential[0] !== pano.direction) {
51133                         continue;
51134                     }
51135                     var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
51136                     if (Math.abs(motionChange) > maxRotationDifference) {
51137                         continue;
51138                     }
51139                     var minOccupiedDifference = Number.MAX_VALUE;
51140                     for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
51141                         var occupiedAngle = allOccupiedAngles_1[_e];
51142                         var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
51143                         if (occupiedDifference < minOccupiedDifference) {
51144                             minOccupiedDifference = occupiedDifference;
51145                         }
51146                     }
51147                     if (minOccupiedDifference <= maxRotationDifference) {
51148                         continue;
51149                     }
51150                     var score = this._coefficients.panoPreferredDistance *
51151                         Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
51152                         this._settings.panoMaxDistance +
51153                         this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
51154                         this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
51155                     if (score < lowestScore) {
51156                         lowestScore = score;
51157                         edge = potential;
51158                     }
51159                 }
51160                 if (edge != null) {
51161                     occupations.push(edge);
51162                     panoEdges.push({
51163                         data: {
51164                             direction: edge[0],
51165                             worldMotionAzimuth: edge[1].worldMotionAzimuth,
51166                         },
51167                         from: node.key,
51168                         to: edge[1].key,
51169                     });
51170                 }
51171             }
51172             for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
51173                 var occupation = occupations_1[_f];
51174                 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
51175             }
51176         }
51177         return panoEdges;
51178     };
51179     return EdgeCalculator;
51180 }());
51181 exports.EdgeCalculator = EdgeCalculator;
51182 exports.default = EdgeCalculator;
51183
51184 },{"../../Edge":292,"../../Error":293,"../../Geo":294,"three":242}],426:[function(require,module,exports){
51185 "use strict";
51186 Object.defineProperty(exports, "__esModule", { value: true });
51187 var EdgeCalculatorCoefficients = /** @class */ (function () {
51188     function EdgeCalculatorCoefficients() {
51189         this.panoPreferredDistance = 2;
51190         this.panoMotion = 2;
51191         this.panoSequencePenalty = 1;
51192         this.panoMergeCCPenalty = 4;
51193         this.stepPreferredDistance = 4;
51194         this.stepMotion = 3;
51195         this.stepRotation = 4;
51196         this.stepSequencePenalty = 2;
51197         this.stepMergeCCPenalty = 6;
51198         this.similarDistance = 2;
51199         this.similarRotation = 3;
51200         this.turnDistance = 4;
51201         this.turnMotion = 2;
51202         this.turnSequencePenalty = 1;
51203         this.turnMergeCCPenalty = 4;
51204     }
51205     return EdgeCalculatorCoefficients;
51206 }());
51207 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
51208 exports.default = EdgeCalculatorCoefficients;
51209
51210 },{}],427:[function(require,module,exports){
51211 "use strict";
51212 Object.defineProperty(exports, "__esModule", { value: true });
51213 var Edge_1 = require("../../Edge");
51214 var EdgeCalculatorDirections = /** @class */ (function () {
51215     function EdgeCalculatorDirections() {
51216         this.steps = {};
51217         this.turns = {};
51218         this.panos = {};
51219         this.steps[Edge_1.EdgeDirection.StepForward] = {
51220             direction: Edge_1.EdgeDirection.StepForward,
51221             motionChange: 0,
51222             useFallback: true,
51223         };
51224         this.steps[Edge_1.EdgeDirection.StepBackward] = {
51225             direction: Edge_1.EdgeDirection.StepBackward,
51226             motionChange: Math.PI,
51227             useFallback: true,
51228         };
51229         this.steps[Edge_1.EdgeDirection.StepLeft] = {
51230             direction: Edge_1.EdgeDirection.StepLeft,
51231             motionChange: Math.PI / 2,
51232             useFallback: false,
51233         };
51234         this.steps[Edge_1.EdgeDirection.StepRight] = {
51235             direction: Edge_1.EdgeDirection.StepRight,
51236             motionChange: -Math.PI / 2,
51237             useFallback: false,
51238         };
51239         this.turns[Edge_1.EdgeDirection.TurnLeft] = {
51240             direction: Edge_1.EdgeDirection.TurnLeft,
51241             directionChange: Math.PI / 2,
51242             motionChange: Math.PI / 4,
51243         };
51244         this.turns[Edge_1.EdgeDirection.TurnRight] = {
51245             direction: Edge_1.EdgeDirection.TurnRight,
51246             directionChange: -Math.PI / 2,
51247             motionChange: -Math.PI / 4,
51248         };
51249         this.turns[Edge_1.EdgeDirection.TurnU] = {
51250             direction: Edge_1.EdgeDirection.TurnU,
51251             directionChange: Math.PI,
51252             motionChange: null,
51253         };
51254         this.panos[Edge_1.EdgeDirection.StepForward] = {
51255             direction: Edge_1.EdgeDirection.StepForward,
51256             directionChange: 0,
51257             next: Edge_1.EdgeDirection.StepLeft,
51258             prev: Edge_1.EdgeDirection.StepRight,
51259         };
51260         this.panos[Edge_1.EdgeDirection.StepBackward] = {
51261             direction: Edge_1.EdgeDirection.StepBackward,
51262             directionChange: Math.PI,
51263             next: Edge_1.EdgeDirection.StepRight,
51264             prev: Edge_1.EdgeDirection.StepLeft,
51265         };
51266         this.panos[Edge_1.EdgeDirection.StepLeft] = {
51267             direction: Edge_1.EdgeDirection.StepLeft,
51268             directionChange: Math.PI / 2,
51269             next: Edge_1.EdgeDirection.StepBackward,
51270             prev: Edge_1.EdgeDirection.StepForward,
51271         };
51272         this.panos[Edge_1.EdgeDirection.StepRight] = {
51273             direction: Edge_1.EdgeDirection.StepRight,
51274             directionChange: -Math.PI / 2,
51275             next: Edge_1.EdgeDirection.StepForward,
51276             prev: Edge_1.EdgeDirection.StepBackward,
51277         };
51278     }
51279     return EdgeCalculatorDirections;
51280 }());
51281 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
51282
51283 },{"../../Edge":292}],428:[function(require,module,exports){
51284 "use strict";
51285 Object.defineProperty(exports, "__esModule", { value: true });
51286 var EdgeCalculatorSettings = /** @class */ (function () {
51287     function EdgeCalculatorSettings() {
51288         this.panoMinDistance = 0.1;
51289         this.panoMaxDistance = 20;
51290         this.panoPreferredDistance = 5;
51291         this.panoMaxItems = 4;
51292         this.panoMaxStepTurnChange = Math.PI / 8;
51293         this.rotationMaxDistance = this.turnMaxRigDistance;
51294         this.rotationMaxDirectionChange = Math.PI / 6;
51295         this.rotationMaxVerticalDirectionChange = Math.PI / 8;
51296         this.similarMaxDirectionChange = Math.PI / 8;
51297         this.similarMaxDistance = 12;
51298         this.similarMinTimeDifference = 12 * 3600 * 1000;
51299         this.stepMaxDistance = 20;
51300         this.stepMaxDirectionChange = Math.PI / 6;
51301         this.stepMaxDrift = Math.PI / 6;
51302         this.stepPreferredDistance = 4;
51303         this.turnMaxDistance = 15;
51304         this.turnMaxDirectionChange = 2 * Math.PI / 9;
51305         this.turnMaxRigDistance = 0.65;
51306         this.turnMinRigDirectionChange = Math.PI / 6;
51307     }
51308     Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
51309         get: function () {
51310             return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
51311         },
51312         enumerable: true,
51313         configurable: true
51314     });
51315     return EdgeCalculatorSettings;
51316 }());
51317 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
51318 exports.default = EdgeCalculatorSettings;
51319
51320 },{}],429:[function(require,module,exports){
51321 "use strict";
51322 Object.defineProperty(exports, "__esModule", { value: true });
51323 /**
51324  * Enumeration for edge directions
51325  * @enum {number}
51326  * @readonly
51327  * @description Directions for edges in node graph describing
51328  * sequence, spatial and node type relations between nodes.
51329  */
51330 var EdgeDirection;
51331 (function (EdgeDirection) {
51332     /**
51333      * Next node in the sequence.
51334      */
51335     EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
51336     /**
51337      * Previous node in the sequence.
51338      */
51339     EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
51340     /**
51341      * Step to the left keeping viewing direction.
51342      */
51343     EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
51344     /**
51345      * Step to the right keeping viewing direction.
51346      */
51347     EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
51348     /**
51349      * Step forward keeping viewing direction.
51350      */
51351     EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
51352     /**
51353      * Step backward keeping viewing direction.
51354      */
51355     EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
51356     /**
51357      * Turn 90 degrees counter clockwise.
51358      */
51359     EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
51360     /**
51361      * Turn 90 degrees clockwise.
51362      */
51363     EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
51364     /**
51365      * Turn 180 degrees.
51366      */
51367     EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
51368     /**
51369      * Panorama in general direction.
51370      */
51371     EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
51372     /**
51373      * Looking in roughly the same direction at rougly the same position.
51374      */
51375     EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
51376 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
51377
51378 },{}],430:[function(require,module,exports){
51379 "use strict";
51380 Object.defineProperty(exports, "__esModule", { value: true });
51381 var rxjs_1 = require("rxjs");
51382 var operators_1 = require("rxjs/operators");
51383 var vd = require("virtual-dom");
51384 var rxjs_2 = require("rxjs");
51385 var Render_1 = require("../Render");
51386 var DOMRenderer = /** @class */ (function () {
51387     function DOMRenderer(element, renderService, currentFrame$) {
51388         this._adaptiveOperation$ = new rxjs_2.Subject();
51389         this._render$ = new rxjs_2.Subject();
51390         this._renderAdaptive$ = new rxjs_2.Subject();
51391         this._renderService = renderService;
51392         this._currentFrame$ = currentFrame$;
51393         var rootNode = vd.create(vd.h("div.domRenderer", []));
51394         element.appendChild(rootNode);
51395         this._offset$ = this._adaptiveOperation$.pipe(operators_1.scan(function (adaptive, operation) {
51396             return operation(adaptive);
51397         }, {
51398             elementHeight: element.offsetHeight,
51399             elementWidth: element.offsetWidth,
51400             imageAspect: 0,
51401             renderMode: Render_1.RenderMode.Fill,
51402         }), operators_1.filter(function (adaptive) {
51403             return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
51404         }), operators_1.map(function (adaptive) {
51405             var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
51406             var ratio = adaptive.imageAspect / elementAspect;
51407             var verticalOffset = 0;
51408             var horizontalOffset = 0;
51409             if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
51410                 if (adaptive.imageAspect > elementAspect) {
51411                     verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
51412                 }
51413                 else {
51414                     horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
51415                 }
51416             }
51417             else {
51418                 if (adaptive.imageAspect > elementAspect) {
51419                     horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
51420                 }
51421                 else {
51422                     verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
51423                 }
51424             }
51425             return {
51426                 bottom: verticalOffset,
51427                 left: horizontalOffset,
51428                 right: horizontalOffset,
51429                 top: verticalOffset,
51430             };
51431         }));
51432         this._currentFrame$.pipe(operators_1.filter(function (frame) {
51433             return frame.state.currentNode != null;
51434         }), operators_1.distinctUntilChanged(function (k1, k2) {
51435             return k1 === k2;
51436         }, function (frame) {
51437             return frame.state.currentNode.key;
51438         }), operators_1.map(function (frame) {
51439             return frame.state.currentTransform.basicAspect;
51440         }), operators_1.map(function (aspect) {
51441             return function (adaptive) {
51442                 adaptive.imageAspect = aspect;
51443                 return adaptive;
51444             };
51445         }))
51446             .subscribe(this._adaptiveOperation$);
51447         rxjs_1.combineLatest(this._renderAdaptive$.pipe(operators_1.scan(function (vNodeHashes, vNodeHash) {
51448             if (vNodeHash.vnode == null) {
51449                 delete vNodeHashes[vNodeHash.name];
51450             }
51451             else {
51452                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
51453             }
51454             return vNodeHashes;
51455         }, {})), this._offset$).pipe(operators_1.map(function (vo) {
51456             var vNodes = [];
51457             var hashes = vo[0];
51458             for (var name_1 in hashes) {
51459                 if (!hashes.hasOwnProperty(name_1)) {
51460                     continue;
51461                 }
51462                 vNodes.push(hashes[name_1]);
51463             }
51464             var offset = vo[1];
51465             var properties = {
51466                 style: {
51467                     bottom: offset.bottom + "px",
51468                     left: offset.left + "px",
51469                     "pointer-events": "none",
51470                     position: "absolute",
51471                     right: offset.right + "px",
51472                     top: offset.top + "px",
51473                 },
51474             };
51475             return {
51476                 name: "adaptiveDomRenderer",
51477                 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
51478             };
51479         }))
51480             .subscribe(this._render$);
51481         this._vNode$ = this._render$.pipe(operators_1.scan(function (vNodeHashes, vNodeHash) {
51482             if (vNodeHash.vnode == null) {
51483                 delete vNodeHashes[vNodeHash.name];
51484             }
51485             else {
51486                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
51487             }
51488             return vNodeHashes;
51489         }, {}), operators_1.map(function (hashes) {
51490             var vNodes = [];
51491             for (var name_2 in hashes) {
51492                 if (!hashes.hasOwnProperty(name_2)) {
51493                     continue;
51494                 }
51495                 vNodes.push(hashes[name_2]);
51496             }
51497             return vd.h("div.domRenderer", vNodes);
51498         }));
51499         this._vPatch$ = this._vNode$.pipe(operators_1.scan(function (nodePatch, vNode) {
51500             nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
51501             nodePatch.vnode = vNode;
51502             return nodePatch;
51503         }, { vnode: vd.h("div.domRenderer", []), vpatch: null }), operators_1.pluck("vpatch"));
51504         this._element$ = this._vPatch$.pipe(operators_1.scan(function (oldElement, vPatch) {
51505             return vd.patch(oldElement, vPatch);
51506         }, rootNode), operators_1.publishReplay(1), operators_1.refCount());
51507         this._element$.subscribe(function () { });
51508         this._renderService.size$.pipe(operators_1.map(function (size) {
51509             return function (adaptive) {
51510                 adaptive.elementWidth = size.width;
51511                 adaptive.elementHeight = size.height;
51512                 return adaptive;
51513             };
51514         }))
51515             .subscribe(this._adaptiveOperation$);
51516         this._renderService.renderMode$.pipe(operators_1.map(function (renderMode) {
51517             return function (adaptive) {
51518                 adaptive.renderMode = renderMode;
51519                 return adaptive;
51520             };
51521         }))
51522             .subscribe(this._adaptiveOperation$);
51523     }
51524     Object.defineProperty(DOMRenderer.prototype, "element$", {
51525         get: function () {
51526             return this._element$;
51527         },
51528         enumerable: true,
51529         configurable: true
51530     });
51531     Object.defineProperty(DOMRenderer.prototype, "render$", {
51532         get: function () {
51533             return this._render$;
51534         },
51535         enumerable: true,
51536         configurable: true
51537     });
51538     Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
51539         get: function () {
51540             return this._renderAdaptive$;
51541         },
51542         enumerable: true,
51543         configurable: true
51544     });
51545     DOMRenderer.prototype.clear = function (name) {
51546         this._renderAdaptive$.next({ name: name, vnode: null });
51547         this._render$.next({ name: name, vnode: null });
51548     };
51549     return DOMRenderer;
51550 }());
51551 exports.DOMRenderer = DOMRenderer;
51552 exports.default = DOMRenderer;
51553
51554
51555 },{"../Render":297,"rxjs":43,"rxjs/operators":241,"virtual-dom":247}],431:[function(require,module,exports){
51556 "use strict";
51557 Object.defineProperty(exports, "__esModule", { value: true });
51558 var GLRenderStage;
51559 (function (GLRenderStage) {
51560     GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
51561     GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
51562 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
51563 exports.default = GLRenderStage;
51564
51565 },{}],432:[function(require,module,exports){
51566 "use strict";
51567 Object.defineProperty(exports, "__esModule", { value: true });
51568 var rxjs_1 = require("rxjs");
51569 var operators_1 = require("rxjs/operators");
51570 var THREE = require("three");
51571 var Render_1 = require("../Render");
51572 var Utils_1 = require("../Utils");
51573 var GLRenderer = /** @class */ (function () {
51574     function GLRenderer(canvasContainer, renderService, dom) {
51575         var _this = this;
51576         this._renderFrame$ = new rxjs_1.Subject();
51577         this._renderCameraOperation$ = new rxjs_1.Subject();
51578         this._render$ = new rxjs_1.Subject();
51579         this._clear$ = new rxjs_1.Subject();
51580         this._renderOperation$ = new rxjs_1.Subject();
51581         this._rendererOperation$ = new rxjs_1.Subject();
51582         this._eraserOperation$ = new rxjs_1.Subject();
51583         this._renderService = renderService;
51584         this._dom = !!dom ? dom : new Utils_1.DOM();
51585         this._renderer$ = this._rendererOperation$.pipe(operators_1.scan(function (renderer, operation) {
51586             return operation(renderer);
51587         }, { needsRender: false, renderer: null }), operators_1.filter(function (renderer) {
51588             return !!renderer.renderer;
51589         }));
51590         this._renderCollection$ = this._renderOperation$.pipe(operators_1.scan(function (hashes, operation) {
51591             return operation(hashes);
51592         }, {}), operators_1.share());
51593         this._renderCamera$ = this._renderCameraOperation$.pipe(operators_1.scan(function (rc, operation) {
51594             return operation(rc);
51595         }, { frameId: -1, needsRender: false, perspective: null }));
51596         this._eraser$ = this._eraserOperation$.pipe(operators_1.startWith(function (eraser) {
51597             return eraser;
51598         }), operators_1.scan(function (eraser, operation) {
51599             return operation(eraser);
51600         }, { needsRender: false }));
51601         rxjs_1.combineLatest(this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$).pipe(operators_1.map(function (_a) {
51602             var renderer = _a[0], hashes = _a[1], rc = _a[2], eraser = _a[3];
51603             var renders = Object.keys(hashes)
51604                 .map(function (key) {
51605                 return hashes[key];
51606             });
51607             return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
51608         }), operators_1.filter(function (co) {
51609             var needsRender = co.renderer.needsRender ||
51610                 co.camera.needsRender ||
51611                 co.eraser.needsRender;
51612             var frameId = co.camera.frameId;
51613             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
51614                 var render = _a[_i];
51615                 if (render.frameId !== frameId) {
51616                     return false;
51617                 }
51618                 needsRender = needsRender || render.needsRender;
51619             }
51620             return needsRender;
51621         }), operators_1.distinctUntilChanged(function (n1, n2) {
51622             return n1 === n2;
51623         }, function (co) {
51624             return co.eraser.needsRender ? -1 : co.camera.frameId;
51625         }))
51626             .subscribe(function (co) {
51627             co.renderer.needsRender = false;
51628             co.camera.needsRender = false;
51629             co.eraser.needsRender = false;
51630             var perspectiveCamera = co.camera.perspective;
51631             var backgroundRenders = [];
51632             var foregroundRenders = [];
51633             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
51634                 var render = _a[_i];
51635                 if (render.stage === Render_1.GLRenderStage.Background) {
51636                     backgroundRenders.push(render.render);
51637                 }
51638                 else if (render.stage === Render_1.GLRenderStage.Foreground) {
51639                     foregroundRenders.push(render.render);
51640                 }
51641             }
51642             var renderer = co.renderer.renderer;
51643             renderer.clear();
51644             for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
51645                 var render = backgroundRenders_1[_b];
51646                 render(perspectiveCamera, renderer);
51647             }
51648             renderer.clearDepth();
51649             for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
51650                 var render = foregroundRenders_1[_c];
51651                 render(perspectiveCamera, renderer);
51652             }
51653         });
51654         this._renderFrame$.pipe(operators_1.map(function (rc) {
51655             return function (irc) {
51656                 irc.frameId = rc.frameId;
51657                 irc.perspective = rc.perspective;
51658                 if (rc.changed === true) {
51659                     irc.needsRender = true;
51660                 }
51661                 return irc;
51662             };
51663         }))
51664             .subscribe(this._renderCameraOperation$);
51665         this._renderFrameSubscribe();
51666         var renderHash$ = this._render$.pipe(operators_1.map(function (hash) {
51667             return function (hashes) {
51668                 hashes[hash.name] = hash.render;
51669                 return hashes;
51670             };
51671         }));
51672         var clearHash$ = this._clear$.pipe(operators_1.map(function (name) {
51673             return function (hashes) {
51674                 delete hashes[name];
51675                 return hashes;
51676             };
51677         }));
51678         rxjs_1.merge(renderHash$, clearHash$)
51679             .subscribe(this._renderOperation$);
51680         this._webGLRenderer$ = this._render$.pipe(operators_1.first(), operators_1.map(function (hash) {
51681             var canvas = _this._dom.createElement("canvas", "mapillary-js-canvas");
51682             canvas.style.position = "absolute";
51683             canvas.setAttribute("tabindex", "0");
51684             canvasContainer.appendChild(canvas);
51685             var element = renderService.element;
51686             var webGLRenderer = new THREE.WebGLRenderer({ canvas: canvas });
51687             webGLRenderer.setPixelRatio(window.devicePixelRatio);
51688             webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
51689             webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
51690             webGLRenderer.autoClear = false;
51691             return webGLRenderer;
51692         }), operators_1.publishReplay(1), operators_1.refCount());
51693         this._webGLRenderer$.subscribe(function () { });
51694         var createRenderer$ = this._webGLRenderer$.pipe(operators_1.first(), operators_1.map(function (webGLRenderer) {
51695             return function (renderer) {
51696                 renderer.needsRender = true;
51697                 renderer.renderer = webGLRenderer;
51698                 return renderer;
51699             };
51700         }));
51701         var resizeRenderer$ = this._renderService.size$.pipe(operators_1.map(function (size) {
51702             return function (renderer) {
51703                 if (renderer.renderer == null) {
51704                     return renderer;
51705                 }
51706                 renderer.renderer.setSize(size.width, size.height);
51707                 renderer.needsRender = true;
51708                 return renderer;
51709             };
51710         }));
51711         var clearRenderer$ = this._clear$.pipe(operators_1.map(function (name) {
51712             return function (renderer) {
51713                 if (renderer.renderer == null) {
51714                     return renderer;
51715                 }
51716                 renderer.needsRender = true;
51717                 return renderer;
51718             };
51719         }));
51720         rxjs_1.merge(createRenderer$, resizeRenderer$, clearRenderer$)
51721             .subscribe(this._rendererOperation$);
51722         var renderCollectionEmpty$ = this._renderCollection$.pipe(operators_1.filter(function (hashes) {
51723             return Object.keys(hashes).length === 0;
51724         }), operators_1.share());
51725         renderCollectionEmpty$
51726             .subscribe(function (hashes) {
51727             if (_this._renderFrameSubscription == null) {
51728                 return;
51729             }
51730             _this._renderFrameSubscription.unsubscribe();
51731             _this._renderFrameSubscription = null;
51732             _this._renderFrameSubscribe();
51733         });
51734         renderCollectionEmpty$.pipe(operators_1.map(function (hashes) {
51735             return function (eraser) {
51736                 eraser.needsRender = true;
51737                 return eraser;
51738             };
51739         }))
51740             .subscribe(this._eraserOperation$);
51741     }
51742     Object.defineProperty(GLRenderer.prototype, "render$", {
51743         get: function () {
51744             return this._render$;
51745         },
51746         enumerable: true,
51747         configurable: true
51748     });
51749     Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
51750         get: function () {
51751             return this._webGLRenderer$;
51752         },
51753         enumerable: true,
51754         configurable: true
51755     });
51756     GLRenderer.prototype.clear = function (name) {
51757         this._clear$.next(name);
51758     };
51759     GLRenderer.prototype._renderFrameSubscribe = function () {
51760         var _this = this;
51761         this._render$.pipe(operators_1.first(), operators_1.map(function (renderHash) {
51762             return function (irc) {
51763                 irc.needsRender = true;
51764                 return irc;
51765             };
51766         }))
51767             .subscribe(function (operation) {
51768             _this._renderCameraOperation$.next(operation);
51769         });
51770         this._renderFrameSubscription = this._render$.pipe(operators_1.first(), operators_1.mergeMap(function (hash) {
51771             return _this._renderService.renderCameraFrame$;
51772         }))
51773             .subscribe(this._renderFrame$);
51774     };
51775     return GLRenderer;
51776 }());
51777 exports.GLRenderer = GLRenderer;
51778 exports.default = GLRenderer;
51779
51780
51781 },{"../Render":297,"../Utils":301,"rxjs":43,"rxjs/operators":241,"three":242}],433:[function(require,module,exports){
51782 "use strict";
51783 Object.defineProperty(exports, "__esModule", { value: true });
51784 var THREE = require("three");
51785 var Geo_1 = require("../Geo");
51786 var Render_1 = require("../Render");
51787 var State_1 = require("../State");
51788 var RenderCamera = /** @class */ (function () {
51789     function RenderCamera(elementWidth, elementHeight, renderMode) {
51790         this._spatial = new Geo_1.Spatial();
51791         this._viewportCoords = new Geo_1.ViewportCoords();
51792         this._initialFov = 50;
51793         this._alpha = -1;
51794         this._renderMode = renderMode;
51795         this._zoom = 0;
51796         this._frameId = -1;
51797         this._changed = false;
51798         this._changedForFrame = -1;
51799         this._currentNodeId = null;
51800         this._previousNodeId = null;
51801         this._currentPano = false;
51802         this._previousPano = false;
51803         this._state = null;
51804         this._currentProjectedPoints = [];
51805         this._previousProjectedPoints = [];
51806         this._currentFov = this._initialFov;
51807         this._previousFov = this._initialFov;
51808         this._camera = new Geo_1.Camera();
51809         this._perspective = new THREE.PerspectiveCamera(this._initialFov, this._computeAspect(elementWidth, elementHeight), 0.16, 10000);
51810         this._perspective.matrixAutoUpdate = false;
51811         this._rotation = { phi: 0, theta: 0 };
51812     }
51813     Object.defineProperty(RenderCamera.prototype, "alpha", {
51814         get: function () {
51815             return this._alpha;
51816         },
51817         enumerable: true,
51818         configurable: true
51819     });
51820     Object.defineProperty(RenderCamera.prototype, "camera", {
51821         get: function () {
51822             return this._camera;
51823         },
51824         enumerable: true,
51825         configurable: true
51826     });
51827     Object.defineProperty(RenderCamera.prototype, "changed", {
51828         get: function () {
51829             return this._frameId === this._changedForFrame;
51830         },
51831         enumerable: true,
51832         configurable: true
51833     });
51834     Object.defineProperty(RenderCamera.prototype, "frameId", {
51835         get: function () {
51836             return this._frameId;
51837         },
51838         enumerable: true,
51839         configurable: true
51840     });
51841     Object.defineProperty(RenderCamera.prototype, "perspective", {
51842         get: function () {
51843             return this._perspective;
51844         },
51845         enumerable: true,
51846         configurable: true
51847     });
51848     Object.defineProperty(RenderCamera.prototype, "renderMode", {
51849         get: function () {
51850             return this._renderMode;
51851         },
51852         enumerable: true,
51853         configurable: true
51854     });
51855     Object.defineProperty(RenderCamera.prototype, "rotation", {
51856         get: function () {
51857             return this._rotation;
51858         },
51859         enumerable: true,
51860         configurable: true
51861     });
51862     Object.defineProperty(RenderCamera.prototype, "zoom", {
51863         get: function () {
51864             return this._zoom;
51865         },
51866         enumerable: true,
51867         configurable: true
51868     });
51869     RenderCamera.prototype.getTilt = function () {
51870         return 90 - this._spatial.radToDeg(this._rotation.theta);
51871     };
51872     RenderCamera.prototype.fovToZoom = function (fov) {
51873         fov = Math.min(90, Math.max(0, fov));
51874         var currentFov = this._computeCurrentFov(0);
51875         var actualFov = this._alpha === 1 ?
51876             currentFov :
51877             this._interpolateFov(currentFov, this._computePreviousFov(0), this._alpha);
51878         var y0 = Math.tan(actualFov / 2 * Math.PI / 180);
51879         var y1 = Math.tan(fov / 2 * Math.PI / 180);
51880         var zoom = Math.log(y0 / y1) / Math.log(2);
51881         return zoom;
51882     };
51883     RenderCamera.prototype.setFrame = function (frame) {
51884         var state = frame.state;
51885         if (state.state !== this._state) {
51886             this._state = state.state;
51887             this._changed = true;
51888         }
51889         var currentNodeId = state.currentNode.key;
51890         var previousNodeId = !!state.previousNode ? state.previousNode.key : null;
51891         if (currentNodeId !== this._currentNodeId) {
51892             this._currentNodeId = currentNodeId;
51893             this._currentPano = !!state.currentTransform.gpano;
51894             this._currentProjectedPoints = this._computeProjectedPoints(state.currentTransform);
51895             this._changed = true;
51896         }
51897         if (previousNodeId !== this._previousNodeId) {
51898             this._previousNodeId = previousNodeId;
51899             this._previousPano = !!state.previousTransform.gpano;
51900             this._previousProjectedPoints = this._computeProjectedPoints(state.previousTransform);
51901             this._changed = true;
51902         }
51903         var zoom = state.zoom;
51904         if (zoom !== this._zoom) {
51905             this._zoom = zoom;
51906             this._changed = true;
51907         }
51908         if (this._changed) {
51909             this._currentFov = this._computeCurrentFov(this.zoom);
51910             this._previousFov = this._computePreviousFov(this._zoom);
51911         }
51912         var alpha = state.alpha;
51913         if (this._changed || alpha !== this._alpha) {
51914             this._alpha = alpha;
51915             this._perspective.fov = this._state === State_1.State.Earth ?
51916                 60 :
51917                 this._interpolateFov(this._currentFov, this._previousFov, this._alpha);
51918             this._changed = true;
51919         }
51920         var camera = state.camera;
51921         if (this._camera.diff(camera) > 1e-9) {
51922             this._camera.copy(camera);
51923             this._rotation = this._computeRotation(camera);
51924             this._perspective.up.copy(camera.up);
51925             this._perspective.position.copy(camera.position);
51926             this._perspective.lookAt(camera.lookat);
51927             this._perspective.updateMatrix();
51928             this._perspective.updateMatrixWorld(false);
51929             this._changed = true;
51930         }
51931         if (this._changed) {
51932             this._perspective.updateProjectionMatrix();
51933         }
51934         this._setFrameId(frame.id);
51935     };
51936     RenderCamera.prototype.setRenderMode = function (renderMode) {
51937         this._renderMode = renderMode;
51938         this._perspective.fov = this._computeFov();
51939         this._perspective.updateProjectionMatrix();
51940         this._changed = true;
51941     };
51942     RenderCamera.prototype.setSize = function (size) {
51943         this._perspective.aspect = this._computeAspect(size.width, size.height);
51944         this._perspective.fov = this._computeFov();
51945         this._perspective.updateProjectionMatrix();
51946         this._changed = true;
51947     };
51948     RenderCamera.prototype._computeAspect = function (elementWidth, elementHeight) {
51949         return elementWidth === 0 ? 0 : elementWidth / elementHeight;
51950     };
51951     RenderCamera.prototype._computeCurrentFov = function (zoom) {
51952         if (this._perspective.aspect === 0) {
51953             return 0;
51954         }
51955         if (!this._currentNodeId) {
51956             return this._initialFov;
51957         }
51958         return this._currentPano ?
51959             this._yToFov(1, zoom) :
51960             this._computeVerticalFov(this._currentProjectedPoints, this._renderMode, zoom, this.perspective.aspect);
51961     };
51962     RenderCamera.prototype._computeFov = function () {
51963         this._currentFov = this._computeCurrentFov(this._zoom);
51964         this._previousFov = this._computePreviousFov(this._zoom);
51965         return this._interpolateFov(this._currentFov, this._previousFov, this._alpha);
51966     };
51967     RenderCamera.prototype._computePreviousFov = function (zoom) {
51968         if (this._perspective.aspect === 0) {
51969             return 0;
51970         }
51971         if (!this._currentNodeId) {
51972             return this._initialFov;
51973         }
51974         return !this._previousNodeId ?
51975             this._currentFov :
51976             this._previousPano ?
51977                 this._yToFov(1, zoom) :
51978                 this._computeVerticalFov(this._previousProjectedPoints, this._renderMode, zoom, this.perspective.aspect);
51979     };
51980     RenderCamera.prototype._computeProjectedPoints = function (transform) {
51981         var vertices = [[0.5, 0], [1, 0]];
51982         var directions = [[0.5, 0], [0, 0.5]];
51983         var pointsPerLine = 100;
51984         return Geo_1.Geo.computeProjectedPoints(transform, vertices, directions, pointsPerLine, this._viewportCoords);
51985     };
51986     RenderCamera.prototype._computeRequiredVerticalFov = function (projectedPoint, zoom, aspect) {
51987         var maxY = Math.max(projectedPoint[0] / aspect, projectedPoint[1]);
51988         return this._yToFov(maxY, zoom);
51989     };
51990     RenderCamera.prototype._computeRotation = function (camera) {
51991         var direction = camera.lookat.clone().sub(camera.position);
51992         var up = camera.up.clone();
51993         var phi = this._spatial.azimuthal(direction.toArray(), up.toArray());
51994         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
51995         return { phi: phi, theta: theta };
51996     };
51997     RenderCamera.prototype._computeVerticalFov = function (projectedPoints, renderMode, zoom, aspect) {
51998         var _this = this;
51999         var fovs = projectedPoints
52000             .map(function (projectedPoint) {
52001             return _this._computeRequiredVerticalFov(projectedPoint, zoom, aspect);
52002         });
52003         var fov = renderMode === Render_1.RenderMode.Fill ?
52004             Math.min.apply(Math, fovs) * 0.995 : Math.max.apply(Math, fovs);
52005         return fov;
52006     };
52007     RenderCamera.prototype._yToFov = function (y, zoom) {
52008         return 2 * Math.atan(y / Math.pow(2, zoom)) * 180 / Math.PI;
52009     };
52010     RenderCamera.prototype._interpolateFov = function (v1, v2, alpha) {
52011         return alpha * v1 + (1 - alpha) * v2;
52012     };
52013     RenderCamera.prototype._setFrameId = function (frameId) {
52014         this._frameId = frameId;
52015         if (this._changed) {
52016             this._changed = false;
52017             this._changedForFrame = frameId;
52018         }
52019     };
52020     return RenderCamera;
52021 }());
52022 exports.RenderCamera = RenderCamera;
52023 exports.default = RenderCamera;
52024
52025 },{"../Geo":294,"../Render":297,"../State":298,"three":242}],434:[function(require,module,exports){
52026 "use strict";
52027 Object.defineProperty(exports, "__esModule", { value: true });
52028 /**
52029  * Enumeration for render mode
52030  * @enum {number}
52031  * @readonly
52032  * @description Modes for specifying how rendering is done
52033  * in the viewer. All modes preserves the original aspect
52034  * ratio of the images.
52035  */
52036 var RenderMode;
52037 (function (RenderMode) {
52038     /**
52039      * Displays all content within the viewer.
52040      *
52041      * @description Black bars shown on both
52042      * sides of the content. Bars are shown
52043      * either below and above or to the left
52044      * and right of the content depending on
52045      * the aspect ratio relation between the
52046      * image and the viewer.
52047      */
52048     RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
52049     /**
52050      * Fills the viewer by cropping content.
52051      *
52052      * @description Cropping is done either
52053      * in horizontal or vertical direction
52054      * depending on the aspect ratio relation
52055      * between the image and the viewer.
52056      */
52057     RenderMode[RenderMode["Fill"] = 1] = "Fill";
52058 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
52059 exports.default = RenderMode;
52060
52061 },{}],435:[function(require,module,exports){
52062 "use strict";
52063 Object.defineProperty(exports, "__esModule", { value: true });
52064 var operators_1 = require("rxjs/operators");
52065 var rxjs_1 = require("rxjs");
52066 var Geo_1 = require("../Geo");
52067 var Render_1 = require("../Render");
52068 var RenderService = /** @class */ (function () {
52069     function RenderService(element, currentFrame$, renderMode, renderCamera) {
52070         var _this = this;
52071         this._element = element;
52072         this._currentFrame$ = currentFrame$;
52073         this._spatial = new Geo_1.Spatial();
52074         renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
52075         this._resize$ = new rxjs_1.Subject();
52076         this._renderCameraOperation$ = new rxjs_1.Subject();
52077         this._size$ =
52078             new rxjs_1.BehaviorSubject({
52079                 height: this._element.offsetHeight,
52080                 width: this._element.offsetWidth,
52081             });
52082         this._resize$.pipe(operators_1.map(function () {
52083             return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
52084         }))
52085             .subscribe(this._size$);
52086         this._renderMode$ = new rxjs_1.BehaviorSubject(renderMode);
52087         this._renderCameraHolder$ = this._renderCameraOperation$.pipe(operators_1.startWith(function (rc) {
52088             return rc;
52089         }), operators_1.scan(function (rc, operation) {
52090             return operation(rc);
52091         }, !!renderCamera ? renderCamera : new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode)), operators_1.publishReplay(1), operators_1.refCount());
52092         this._renderCameraFrame$ = this._currentFrame$.pipe(operators_1.withLatestFrom(this._renderCameraHolder$), operators_1.tap(function (_a) {
52093             var frame = _a[0], rc = _a[1];
52094             rc.setFrame(frame);
52095         }), operators_1.map(function (args) {
52096             return args[1];
52097         }), operators_1.publishReplay(1), operators_1.refCount());
52098         this._renderCamera$ = this._renderCameraFrame$.pipe(operators_1.filter(function (rc) {
52099             return rc.changed;
52100         }), operators_1.publishReplay(1), operators_1.refCount());
52101         this._bearing$ = this._renderCamera$.pipe(operators_1.map(function (rc) {
52102             var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(rc.rotation.phi));
52103             return _this._spatial.wrap(bearing, 0, 360);
52104         }), operators_1.publishReplay(1), operators_1.refCount());
52105         this._size$.pipe(operators_1.skip(1), operators_1.map(function (size) {
52106             return function (rc) {
52107                 rc.setSize(size);
52108                 return rc;
52109             };
52110         }))
52111             .subscribe(this._renderCameraOperation$);
52112         this._renderMode$.pipe(operators_1.skip(1), operators_1.map(function (rm) {
52113             return function (rc) {
52114                 rc.setRenderMode(rm);
52115                 return rc;
52116             };
52117         }))
52118             .subscribe(this._renderCameraOperation$);
52119         this._bearing$.subscribe(function () { });
52120         this._renderCameraHolder$.subscribe(function () { });
52121         this._size$.subscribe(function () { });
52122         this._renderMode$.subscribe(function () { });
52123         this._renderCamera$.subscribe(function () { });
52124         this._renderCameraFrame$.subscribe(function () { });
52125     }
52126     Object.defineProperty(RenderService.prototype, "bearing$", {
52127         get: function () {
52128             return this._bearing$;
52129         },
52130         enumerable: true,
52131         configurable: true
52132     });
52133     Object.defineProperty(RenderService.prototype, "element", {
52134         get: function () {
52135             return this._element;
52136         },
52137         enumerable: true,
52138         configurable: true
52139     });
52140     Object.defineProperty(RenderService.prototype, "resize$", {
52141         get: function () {
52142             return this._resize$;
52143         },
52144         enumerable: true,
52145         configurable: true
52146     });
52147     Object.defineProperty(RenderService.prototype, "size$", {
52148         get: function () {
52149             return this._size$;
52150         },
52151         enumerable: true,
52152         configurable: true
52153     });
52154     Object.defineProperty(RenderService.prototype, "renderMode$", {
52155         get: function () {
52156             return this._renderMode$;
52157         },
52158         enumerable: true,
52159         configurable: true
52160     });
52161     Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
52162         get: function () {
52163             return this._renderCameraFrame$;
52164         },
52165         enumerable: true,
52166         configurable: true
52167     });
52168     Object.defineProperty(RenderService.prototype, "renderCamera$", {
52169         get: function () {
52170             return this._renderCamera$;
52171         },
52172         enumerable: true,
52173         configurable: true
52174     });
52175     return RenderService;
52176 }());
52177 exports.RenderService = RenderService;
52178 exports.default = RenderService;
52179
52180
52181 },{"../Geo":294,"../Render":297,"rxjs":43,"rxjs/operators":241}],436:[function(require,module,exports){
52182 "use strict";
52183 Object.defineProperty(exports, "__esModule", { value: true });
52184 var FrameGenerator = /** @class */ (function () {
52185     function FrameGenerator(root) {
52186         if (root.requestAnimationFrame) {
52187             this._cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
52188             this._requestAnimationFrame = root.requestAnimationFrame.bind(root);
52189         }
52190         else if (root.mozRequestAnimationFrame) {
52191             this._cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
52192             this._requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
52193         }
52194         else if (root.webkitRequestAnimationFrame) {
52195             this._cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
52196             this._requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
52197         }
52198         else if (root.msRequestAnimationFrame) {
52199             this._cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
52200             this._requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
52201         }
52202         else if (root.oRequestAnimationFrame) {
52203             this._cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
52204             this._requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
52205         }
52206         else {
52207             this._cancelAnimationFrame = root.clearTimeout.bind(root);
52208             this._requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
52209         }
52210     }
52211     Object.defineProperty(FrameGenerator.prototype, "cancelAnimationFrame", {
52212         get: function () {
52213             return this._cancelAnimationFrame;
52214         },
52215         enumerable: true,
52216         configurable: true
52217     });
52218     Object.defineProperty(FrameGenerator.prototype, "requestAnimationFrame", {
52219         get: function () {
52220             return this._requestAnimationFrame;
52221         },
52222         enumerable: true,
52223         configurable: true
52224     });
52225     return FrameGenerator;
52226 }());
52227 exports.FrameGenerator = FrameGenerator;
52228 exports.default = FrameGenerator;
52229
52230 },{}],437:[function(require,module,exports){
52231 "use strict";
52232 Object.defineProperty(exports, "__esModule", { value: true });
52233 var RotationDelta = /** @class */ (function () {
52234     function RotationDelta(phi, theta) {
52235         this._phi = phi;
52236         this._theta = theta;
52237     }
52238     Object.defineProperty(RotationDelta.prototype, "phi", {
52239         get: function () {
52240             return this._phi;
52241         },
52242         set: function (value) {
52243             this._phi = value;
52244         },
52245         enumerable: true,
52246         configurable: true
52247     });
52248     Object.defineProperty(RotationDelta.prototype, "theta", {
52249         get: function () {
52250             return this._theta;
52251         },
52252         set: function (value) {
52253             this._theta = value;
52254         },
52255         enumerable: true,
52256         configurable: true
52257     });
52258     Object.defineProperty(RotationDelta.prototype, "isZero", {
52259         get: function () {
52260             return this._phi === 0 && this._theta === 0;
52261         },
52262         enumerable: true,
52263         configurable: true
52264     });
52265     RotationDelta.prototype.copy = function (delta) {
52266         this._phi = delta.phi;
52267         this._theta = delta.theta;
52268     };
52269     RotationDelta.prototype.lerp = function (other, alpha) {
52270         this._phi = (1 - alpha) * this._phi + alpha * other.phi;
52271         this._theta = (1 - alpha) * this._theta + alpha * other.theta;
52272     };
52273     RotationDelta.prototype.multiply = function (value) {
52274         this._phi *= value;
52275         this._theta *= value;
52276     };
52277     RotationDelta.prototype.threshold = function (value) {
52278         this._phi = Math.abs(this._phi) > value ? this._phi : 0;
52279         this._theta = Math.abs(this._theta) > value ? this._theta : 0;
52280     };
52281     RotationDelta.prototype.lengthSquared = function () {
52282         return this._phi * this._phi + this._theta * this._theta;
52283     };
52284     RotationDelta.prototype.reset = function () {
52285         this._phi = 0;
52286         this._theta = 0;
52287     };
52288     return RotationDelta;
52289 }());
52290 exports.RotationDelta = RotationDelta;
52291 exports.default = RotationDelta;
52292
52293 },{}],438:[function(require,module,exports){
52294 "use strict";
52295 Object.defineProperty(exports, "__esModule", { value: true });
52296 var State;
52297 (function (State) {
52298     State[State["Earth"] = 0] = "Earth";
52299     State[State["Traversing"] = 1] = "Traversing";
52300     State[State["Waiting"] = 2] = "Waiting";
52301     State[State["WaitingInteractively"] = 3] = "WaitingInteractively";
52302 })(State = exports.State || (exports.State = {}));
52303 exports.default = State;
52304
52305 },{}],439:[function(require,module,exports){
52306 "use strict";
52307 Object.defineProperty(exports, "__esModule", { value: true });
52308 var State_1 = require("../State");
52309 var Geo_1 = require("../Geo");
52310 var StateContext = /** @class */ (function () {
52311     function StateContext(transitionMode) {
52312         this._state = new State_1.TraversingState({
52313             alpha: 1,
52314             camera: new Geo_1.Camera(),
52315             currentIndex: -1,
52316             reference: { alt: 0, lat: 0, lon: 0 },
52317             trajectory: [],
52318             transitionMode: transitionMode == null ? State_1.TransitionMode.Default : transitionMode,
52319             zoom: 0,
52320         });
52321     }
52322     StateContext.prototype.earth = function () {
52323         this._state = this._state.earth();
52324     };
52325     StateContext.prototype.traverse = function () {
52326         this._state = this._state.traverse();
52327     };
52328     StateContext.prototype.wait = function () {
52329         this._state = this._state.wait();
52330     };
52331     StateContext.prototype.waitInteractively = function () {
52332         this._state = this._state.waitInteractively();
52333     };
52334     Object.defineProperty(StateContext.prototype, "state", {
52335         get: function () {
52336             if (this._state instanceof State_1.EarthState) {
52337                 return State_1.State.Earth;
52338             }
52339             else if (this._state instanceof State_1.TraversingState) {
52340                 return State_1.State.Traversing;
52341             }
52342             else if (this._state instanceof State_1.WaitingState) {
52343                 return State_1.State.Waiting;
52344             }
52345             else if (this._state instanceof State_1.InteractiveWaitingState) {
52346                 return State_1.State.WaitingInteractively;
52347             }
52348             throw new Error("Invalid state");
52349         },
52350         enumerable: true,
52351         configurable: true
52352     });
52353     Object.defineProperty(StateContext.prototype, "reference", {
52354         get: function () {
52355             return this._state.reference;
52356         },
52357         enumerable: true,
52358         configurable: true
52359     });
52360     Object.defineProperty(StateContext.prototype, "alpha", {
52361         get: function () {
52362             return this._state.alpha;
52363         },
52364         enumerable: true,
52365         configurable: true
52366     });
52367     Object.defineProperty(StateContext.prototype, "camera", {
52368         get: function () {
52369             return this._state.camera;
52370         },
52371         enumerable: true,
52372         configurable: true
52373     });
52374     Object.defineProperty(StateContext.prototype, "zoom", {
52375         get: function () {
52376             return this._state.zoom;
52377         },
52378         enumerable: true,
52379         configurable: true
52380     });
52381     Object.defineProperty(StateContext.prototype, "currentNode", {
52382         get: function () {
52383             return this._state.currentNode;
52384         },
52385         enumerable: true,
52386         configurable: true
52387     });
52388     Object.defineProperty(StateContext.prototype, "previousNode", {
52389         get: function () {
52390             return this._state.previousNode;
52391         },
52392         enumerable: true,
52393         configurable: true
52394     });
52395     Object.defineProperty(StateContext.prototype, "currentCamera", {
52396         get: function () {
52397             return this._state.currentCamera;
52398         },
52399         enumerable: true,
52400         configurable: true
52401     });
52402     Object.defineProperty(StateContext.prototype, "currentTransform", {
52403         get: function () {
52404             return this._state.currentTransform;
52405         },
52406         enumerable: true,
52407         configurable: true
52408     });
52409     Object.defineProperty(StateContext.prototype, "previousTransform", {
52410         get: function () {
52411             return this._state.previousTransform;
52412         },
52413         enumerable: true,
52414         configurable: true
52415     });
52416     Object.defineProperty(StateContext.prototype, "trajectory", {
52417         get: function () {
52418             return this._state.trajectory;
52419         },
52420         enumerable: true,
52421         configurable: true
52422     });
52423     Object.defineProperty(StateContext.prototype, "currentIndex", {
52424         get: function () {
52425             return this._state.currentIndex;
52426         },
52427         enumerable: true,
52428         configurable: true
52429     });
52430     Object.defineProperty(StateContext.prototype, "lastNode", {
52431         get: function () {
52432             return this._state.trajectory[this._state.trajectory.length - 1];
52433         },
52434         enumerable: true,
52435         configurable: true
52436     });
52437     Object.defineProperty(StateContext.prototype, "nodesAhead", {
52438         get: function () {
52439             return this._state.trajectory.length - 1 - this._state.currentIndex;
52440         },
52441         enumerable: true,
52442         configurable: true
52443     });
52444     Object.defineProperty(StateContext.prototype, "motionless", {
52445         get: function () {
52446             return this._state.motionless;
52447         },
52448         enumerable: true,
52449         configurable: true
52450     });
52451     StateContext.prototype.getCenter = function () {
52452         return this._state.getCenter();
52453     };
52454     StateContext.prototype.setCenter = function (center) {
52455         this._state.setCenter(center);
52456     };
52457     StateContext.prototype.setZoom = function (zoom) {
52458         this._state.setZoom(zoom);
52459     };
52460     StateContext.prototype.update = function (fps) {
52461         this._state.update(fps);
52462     };
52463     StateContext.prototype.append = function (nodes) {
52464         this._state.append(nodes);
52465     };
52466     StateContext.prototype.prepend = function (nodes) {
52467         this._state.prepend(nodes);
52468     };
52469     StateContext.prototype.remove = function (n) {
52470         this._state.remove(n);
52471     };
52472     StateContext.prototype.clear = function () {
52473         this._state.clear();
52474     };
52475     StateContext.prototype.clearPrior = function () {
52476         this._state.clearPrior();
52477     };
52478     StateContext.prototype.cut = function () {
52479         this._state.cut();
52480     };
52481     StateContext.prototype.set = function (nodes) {
52482         this._state.set(nodes);
52483     };
52484     StateContext.prototype.rotate = function (delta) {
52485         this._state.rotate(delta);
52486     };
52487     StateContext.prototype.rotateUnbounded = function (delta) {
52488         this._state.rotateUnbounded(delta);
52489     };
52490     StateContext.prototype.rotateWithoutInertia = function (delta) {
52491         this._state.rotateWithoutInertia(delta);
52492     };
52493     StateContext.prototype.rotateBasic = function (basicRotation) {
52494         this._state.rotateBasic(basicRotation);
52495     };
52496     StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
52497         this._state.rotateBasicUnbounded(basicRotation);
52498     };
52499     StateContext.prototype.rotateBasicWithoutInertia = function (basicRotation) {
52500         this._state.rotateBasicWithoutInertia(basicRotation);
52501     };
52502     StateContext.prototype.rotateToBasic = function (basic) {
52503         this._state.rotateToBasic(basic);
52504     };
52505     StateContext.prototype.move = function (delta) {
52506         this._state.move(delta);
52507     };
52508     StateContext.prototype.moveTo = function (delta) {
52509         this._state.moveTo(delta);
52510     };
52511     StateContext.prototype.zoomIn = function (delta, reference) {
52512         this._state.zoomIn(delta, reference);
52513     };
52514     StateContext.prototype.setSpeed = function (speed) {
52515         this._state.setSpeed(speed);
52516     };
52517     StateContext.prototype.setTransitionMode = function (mode) {
52518         this._state.setTransitionMode(mode);
52519     };
52520     StateContext.prototype.dolly = function (delta) {
52521         this._state.dolly(delta);
52522     };
52523     StateContext.prototype.orbit = function (rotation) {
52524         this._state.orbit(rotation);
52525     };
52526     StateContext.prototype.truck = function (direction) {
52527         this._state.truck(direction);
52528     };
52529     return StateContext;
52530 }());
52531 exports.StateContext = StateContext;
52532
52533 },{"../Geo":294,"../State":298}],440:[function(require,module,exports){
52534 "use strict";
52535 Object.defineProperty(exports, "__esModule", { value: true });
52536 var rxjs_1 = require("rxjs");
52537 var operators_1 = require("rxjs/operators");
52538 var State_1 = require("../State");
52539 var StateService = /** @class */ (function () {
52540     function StateService(transitionMode) {
52541         var _this = this;
52542         this._appendNode$ = new rxjs_1.Subject();
52543         this._start$ = new rxjs_1.Subject();
52544         this._frame$ = new rxjs_1.Subject();
52545         this._fpsSampleRate = 30;
52546         this._contextOperation$ = new rxjs_1.BehaviorSubject(function (context) {
52547             return context;
52548         });
52549         this._context$ = this._contextOperation$.pipe(operators_1.scan(function (context, operation) {
52550             return operation(context);
52551         }, new State_1.StateContext(transitionMode)), operators_1.publishReplay(1), operators_1.refCount());
52552         this._state$ = this._context$.pipe(operators_1.map(function (context) {
52553             return context.state;
52554         }), operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
52555         this._fps$ = this._start$.pipe(operators_1.switchMap(function () {
52556             return _this._frame$.pipe(operators_1.bufferCount(1, _this._fpsSampleRate), operators_1.map(function (frameIds) {
52557                 return new Date().getTime();
52558             }), operators_1.pairwise(), operators_1.map(function (times) {
52559                 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
52560             }), operators_1.startWith(60));
52561         }), operators_1.share());
52562         this._currentState$ = this._frame$.pipe(operators_1.withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
52563             return [frameId, fps, context];
52564         }), operators_1.filter(function (fc) {
52565             return fc[2].currentNode != null;
52566         }), operators_1.tap(function (fc) {
52567             fc[2].update(fc[1]);
52568         }), operators_1.map(function (fc) {
52569             return { fps: fc[1], id: fc[0], state: fc[2] };
52570         }), operators_1.share());
52571         this._lastState$ = this._currentState$.pipe(operators_1.publishReplay(1), operators_1.refCount());
52572         var nodeChanged$ = this._currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (f) {
52573             return f.state.currentNode.key;
52574         }), operators_1.publishReplay(1), operators_1.refCount());
52575         var nodeChangedSubject$ = new rxjs_1.Subject();
52576         nodeChanged$
52577             .subscribe(nodeChangedSubject$);
52578         this._currentKey$ = new rxjs_1.BehaviorSubject(null);
52579         nodeChangedSubject$.pipe(operators_1.map(function (f) {
52580             return f.state.currentNode.key;
52581         }))
52582             .subscribe(this._currentKey$);
52583         this._currentNode$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
52584             return f.state.currentNode;
52585         }), operators_1.publishReplay(1), operators_1.refCount());
52586         this._currentCamera$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
52587             return f.state.currentCamera;
52588         }), operators_1.publishReplay(1), operators_1.refCount());
52589         this._currentTransform$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
52590             return f.state.currentTransform;
52591         }), operators_1.publishReplay(1), operators_1.refCount());
52592         this._reference$ = nodeChangedSubject$.pipe(operators_1.map(function (f) {
52593             return f.state.reference;
52594         }), operators_1.distinctUntilChanged(function (r1, r2) {
52595             return r1.lat === r2.lat && r1.lon === r2.lon;
52596         }, function (reference) {
52597             return { lat: reference.lat, lon: reference.lon };
52598         }), operators_1.publishReplay(1), operators_1.refCount());
52599         this._currentNodeExternal$ = nodeChanged$.pipe(operators_1.map(function (f) {
52600             return f.state.currentNode;
52601         }), operators_1.publishReplay(1), operators_1.refCount());
52602         this._appendNode$.pipe(operators_1.map(function (node) {
52603             return function (context) {
52604                 context.append([node]);
52605                 return context;
52606             };
52607         }))
52608             .subscribe(this._contextOperation$);
52609         this._inMotionOperation$ = new rxjs_1.Subject();
52610         nodeChanged$.pipe(operators_1.map(function (frame) {
52611             return true;
52612         }))
52613             .subscribe(this._inMotionOperation$);
52614         this._inMotionOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.filter(function (moving) {
52615             return moving;
52616         }), operators_1.switchMap(function (moving) {
52617             return _this._currentState$.pipe(operators_1.filter(function (frame) {
52618                 return frame.state.nodesAhead === 0;
52619             }), operators_1.map(function (frame) {
52620                 return [frame.state.camera.clone(), frame.state.zoom];
52621             }), operators_1.pairwise(), operators_1.map(function (pair) {
52622                 var c1 = pair[0][0];
52623                 var c2 = pair[1][0];
52624                 var z1 = pair[0][1];
52625                 var z2 = pair[1][1];
52626                 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
52627             }), operators_1.first(function (changed) {
52628                 return !changed;
52629             }));
52630         }))
52631             .subscribe(this._inMotionOperation$);
52632         this._inMotion$ = this._inMotionOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
52633         this._inTranslationOperation$ = new rxjs_1.Subject();
52634         nodeChanged$.pipe(operators_1.map(function (frame) {
52635             return true;
52636         }))
52637             .subscribe(this._inTranslationOperation$);
52638         this._inTranslationOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.filter(function (inTranslation) {
52639             return inTranslation;
52640         }), operators_1.switchMap(function (inTranslation) {
52641             return _this._currentState$.pipe(operators_1.filter(function (frame) {
52642                 return frame.state.nodesAhead === 0;
52643             }), operators_1.map(function (frame) {
52644                 return frame.state.camera.position.clone();
52645             }), operators_1.pairwise(), operators_1.map(function (pair) {
52646                 return pair[0].distanceToSquared(pair[1]) !== 0;
52647             }), operators_1.first(function (changed) {
52648                 return !changed;
52649             }));
52650         }))
52651             .subscribe(this._inTranslationOperation$);
52652         this._inTranslation$ = this._inTranslationOperation$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
52653         this._state$.subscribe(function () { });
52654         this._currentNode$.subscribe(function () { });
52655         this._currentCamera$.subscribe(function () { });
52656         this._currentTransform$.subscribe(function () { });
52657         this._reference$.subscribe(function () { });
52658         this._currentNodeExternal$.subscribe(function () { });
52659         this._lastState$.subscribe(function () { });
52660         this._inMotion$.subscribe(function () { });
52661         this._inTranslation$.subscribe(function () { });
52662         this._frameId = null;
52663         this._frameGenerator = new State_1.FrameGenerator(window);
52664     }
52665     Object.defineProperty(StateService.prototype, "currentState$", {
52666         get: function () {
52667             return this._currentState$;
52668         },
52669         enumerable: true,
52670         configurable: true
52671     });
52672     Object.defineProperty(StateService.prototype, "currentNode$", {
52673         get: function () {
52674             return this._currentNode$;
52675         },
52676         enumerable: true,
52677         configurable: true
52678     });
52679     Object.defineProperty(StateService.prototype, "currentKey$", {
52680         get: function () {
52681             return this._currentKey$;
52682         },
52683         enumerable: true,
52684         configurable: true
52685     });
52686     Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
52687         get: function () {
52688             return this._currentNodeExternal$;
52689         },
52690         enumerable: true,
52691         configurable: true
52692     });
52693     Object.defineProperty(StateService.prototype, "currentCamera$", {
52694         get: function () {
52695             return this._currentCamera$;
52696         },
52697         enumerable: true,
52698         configurable: true
52699     });
52700     Object.defineProperty(StateService.prototype, "currentTransform$", {
52701         get: function () {
52702             return this._currentTransform$;
52703         },
52704         enumerable: true,
52705         configurable: true
52706     });
52707     Object.defineProperty(StateService.prototype, "state$", {
52708         get: function () {
52709             return this._state$;
52710         },
52711         enumerable: true,
52712         configurable: true
52713     });
52714     Object.defineProperty(StateService.prototype, "reference$", {
52715         get: function () {
52716             return this._reference$;
52717         },
52718         enumerable: true,
52719         configurable: true
52720     });
52721     Object.defineProperty(StateService.prototype, "inMotion$", {
52722         get: function () {
52723             return this._inMotion$;
52724         },
52725         enumerable: true,
52726         configurable: true
52727     });
52728     Object.defineProperty(StateService.prototype, "inTranslation$", {
52729         get: function () {
52730             return this._inTranslation$;
52731         },
52732         enumerable: true,
52733         configurable: true
52734     });
52735     Object.defineProperty(StateService.prototype, "appendNode$", {
52736         get: function () {
52737             return this._appendNode$;
52738         },
52739         enumerable: true,
52740         configurable: true
52741     });
52742     StateService.prototype.earth = function () {
52743         this._inMotionOperation$.next(true);
52744         this._invokeContextOperation(function (context) { context.earth(); });
52745     };
52746     StateService.prototype.traverse = function () {
52747         this._inMotionOperation$.next(true);
52748         this._invokeContextOperation(function (context) { context.traverse(); });
52749     };
52750     StateService.prototype.wait = function () {
52751         this._invokeContextOperation(function (context) { context.wait(); });
52752     };
52753     StateService.prototype.waitInteractively = function () {
52754         this._invokeContextOperation(function (context) { context.waitInteractively(); });
52755     };
52756     StateService.prototype.appendNodes = function (nodes) {
52757         this._invokeContextOperation(function (context) { context.append(nodes); });
52758     };
52759     StateService.prototype.prependNodes = function (nodes) {
52760         this._invokeContextOperation(function (context) { context.prepend(nodes); });
52761     };
52762     StateService.prototype.removeNodes = function (n) {
52763         this._invokeContextOperation(function (context) { context.remove(n); });
52764     };
52765     StateService.prototype.clearNodes = function () {
52766         this._invokeContextOperation(function (context) { context.clear(); });
52767     };
52768     StateService.prototype.clearPriorNodes = function () {
52769         this._invokeContextOperation(function (context) { context.clearPrior(); });
52770     };
52771     StateService.prototype.cutNodes = function () {
52772         this._invokeContextOperation(function (context) { context.cut(); });
52773     };
52774     StateService.prototype.setNodes = function (nodes) {
52775         this._invokeContextOperation(function (context) { context.set(nodes); });
52776     };
52777     StateService.prototype.rotate = function (delta) {
52778         this._inMotionOperation$.next(true);
52779         this._invokeContextOperation(function (context) { context.rotate(delta); });
52780     };
52781     StateService.prototype.rotateUnbounded = function (delta) {
52782         this._inMotionOperation$.next(true);
52783         this._invokeContextOperation(function (context) { context.rotateUnbounded(delta); });
52784     };
52785     StateService.prototype.rotateWithoutInertia = function (delta) {
52786         this._inMotionOperation$.next(true);
52787         this._invokeContextOperation(function (context) { context.rotateWithoutInertia(delta); });
52788     };
52789     StateService.prototype.rotateBasic = function (basicRotation) {
52790         this._inMotionOperation$.next(true);
52791         this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
52792     };
52793     StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
52794         this._inMotionOperation$.next(true);
52795         this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
52796     };
52797     StateService.prototype.rotateBasicWithoutInertia = function (basicRotation) {
52798         this._inMotionOperation$.next(true);
52799         this._invokeContextOperation(function (context) { context.rotateBasicWithoutInertia(basicRotation); });
52800     };
52801     StateService.prototype.rotateToBasic = function (basic) {
52802         this._inMotionOperation$.next(true);
52803         this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
52804     };
52805     StateService.prototype.move = function (delta) {
52806         this._inMotionOperation$.next(true);
52807         this._invokeContextOperation(function (context) { context.move(delta); });
52808     };
52809     StateService.prototype.moveTo = function (position) {
52810         this._inMotionOperation$.next(true);
52811         this._invokeContextOperation(function (context) { context.moveTo(position); });
52812     };
52813     StateService.prototype.dolly = function (delta) {
52814         this._inMotionOperation$.next(true);
52815         this._invokeContextOperation(function (context) { context.dolly(delta); });
52816     };
52817     StateService.prototype.orbit = function (rotation) {
52818         this._inMotionOperation$.next(true);
52819         this._invokeContextOperation(function (context) { context.orbit(rotation); });
52820     };
52821     StateService.prototype.truck = function (direction) {
52822         this._inMotionOperation$.next(true);
52823         this._invokeContextOperation(function (context) { context.truck(direction); });
52824     };
52825     /**
52826      * Change zoom level while keeping the reference point position approximately static.
52827      *
52828      * @parameter {number} delta - Change in zoom level.
52829      * @parameter {Array<number>} reference - Reference point in basic coordinates.
52830      */
52831     StateService.prototype.zoomIn = function (delta, reference) {
52832         this._inMotionOperation$.next(true);
52833         this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
52834     };
52835     StateService.prototype.getCenter = function () {
52836         return this._lastState$.pipe(operators_1.first(), operators_1.map(function (frame) {
52837             return frame.state.getCenter();
52838         }));
52839     };
52840     StateService.prototype.getZoom = function () {
52841         return this._lastState$.pipe(operators_1.first(), operators_1.map(function (frame) {
52842             return frame.state.zoom;
52843         }));
52844     };
52845     StateService.prototype.setCenter = function (center) {
52846         this._inMotionOperation$.next(true);
52847         this._invokeContextOperation(function (context) { context.setCenter(center); });
52848     };
52849     StateService.prototype.setSpeed = function (speed) {
52850         this._invokeContextOperation(function (context) { context.setSpeed(speed); });
52851     };
52852     StateService.prototype.setTransitionMode = function (mode) {
52853         this._invokeContextOperation(function (context) { context.setTransitionMode(mode); });
52854     };
52855     StateService.prototype.setZoom = function (zoom) {
52856         this._inMotionOperation$.next(true);
52857         this._invokeContextOperation(function (context) { context.setZoom(zoom); });
52858     };
52859     StateService.prototype.start = function () {
52860         if (this._frameId == null) {
52861             this._start$.next(null);
52862             this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
52863             this._frame$.next(this._frameId);
52864         }
52865     };
52866     StateService.prototype.stop = function () {
52867         if (this._frameId != null) {
52868             this._frameGenerator.cancelAnimationFrame(this._frameId);
52869             this._frameId = null;
52870         }
52871     };
52872     StateService.prototype._invokeContextOperation = function (action) {
52873         this._contextOperation$
52874             .next(function (context) {
52875             action(context);
52876             return context;
52877         });
52878     };
52879     StateService.prototype._frame = function (time) {
52880         this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
52881         this._frame$.next(this._frameId);
52882     };
52883     return StateService;
52884 }());
52885 exports.StateService = StateService;
52886
52887 },{"../State":298,"rxjs":43,"rxjs/operators":241}],441:[function(require,module,exports){
52888 "use strict";
52889 Object.defineProperty(exports, "__esModule", { value: true });
52890 /**
52891  * Enumeration for transition mode
52892  * @enum {number}
52893  * @readonly
52894  * @description Modes for specifying how transitions
52895  * between nodes are performed.
52896  */
52897 var TransitionMode;
52898 (function (TransitionMode) {
52899     /**
52900      * Default transitions.
52901      *
52902      * @description The viewer dynamically determines
52903      * whether transitions should be performed with or
52904      * without motion and blending for each transition
52905      * based on the underlying data.
52906      */
52907     TransitionMode[TransitionMode["Default"] = 0] = "Default";
52908     /**
52909      * Instantaneous transitions.
52910      *
52911      * @description All transitions are performed
52912      * without motion or blending.
52913      */
52914     TransitionMode[TransitionMode["Instantaneous"] = 1] = "Instantaneous";
52915 })(TransitionMode = exports.TransitionMode || (exports.TransitionMode = {}));
52916 exports.default = TransitionMode;
52917
52918 },{}],442:[function(require,module,exports){
52919 "use strict";
52920 var __extends = (this && this.__extends) || (function () {
52921     var extendStatics = function (d, b) {
52922         extendStatics = Object.setPrototypeOf ||
52923             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
52924             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
52925         return extendStatics(d, b);
52926     }
52927     return function (d, b) {
52928         extendStatics(d, b);
52929         function __() { this.constructor = d; }
52930         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
52931     };
52932 })();
52933 Object.defineProperty(exports, "__esModule", { value: true });
52934 var THREE = require("three");
52935 var State_1 = require("../../State");
52936 var EarthState = /** @class */ (function (_super) {
52937     __extends(EarthState, _super);
52938     function EarthState(state) {
52939         var _this = _super.call(this, state) || this;
52940         var viewingDirection = _this._camera.lookat
52941             .clone()
52942             .sub(_this._camera.position)
52943             .normalize();
52944         _this._camera.lookat.copy(_this._camera.position);
52945         _this._camera.position.z = state.camera.position.z + 20;
52946         _this._camera.position.x = state.camera.position.x - 16 * viewingDirection.x;
52947         _this._camera.position.y = state.camera.position.y - 16 * viewingDirection.y;
52948         _this._camera.up.set(0, 0, 1);
52949         return _this;
52950     }
52951     EarthState.prototype.traverse = function () {
52952         return new State_1.TraversingState(this);
52953     };
52954     EarthState.prototype.wait = function () {
52955         return new State_1.WaitingState(this);
52956     };
52957     EarthState.prototype.waitInteractively = function () {
52958         return new State_1.InteractiveWaitingState(this);
52959     };
52960     EarthState.prototype.dolly = function (delta) {
52961         var camera = this._camera;
52962         var offset = new THREE.Vector3()
52963             .copy(camera.position)
52964             .sub(camera.lookat);
52965         var length = offset.length();
52966         var scaled = length * Math.pow(2, -delta);
52967         var clipped = Math.max(1, Math.min(scaled, 1000));
52968         offset.normalize();
52969         offset.multiplyScalar(clipped);
52970         camera.position.copy(camera.lookat).add(offset);
52971     };
52972     EarthState.prototype.orbit = function (rotation) {
52973         var camera = this._camera;
52974         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
52975         var qInverse = q.clone().inverse();
52976         var offset = new THREE.Vector3();
52977         offset.copy(camera.position).sub(camera.lookat);
52978         offset.applyQuaternion(q);
52979         var length = offset.length();
52980         var phi = Math.atan2(offset.y, offset.x);
52981         phi += rotation.phi;
52982         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
52983         theta += rotation.theta;
52984         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
52985         offset.x = Math.sin(theta) * Math.cos(phi);
52986         offset.y = Math.sin(theta) * Math.sin(phi);
52987         offset.z = Math.cos(theta);
52988         offset.applyQuaternion(qInverse);
52989         camera.position.copy(camera.lookat).add(offset.multiplyScalar(length));
52990     };
52991     EarthState.prototype.truck = function (direction) {
52992         this._camera.position.add(new THREE.Vector3().fromArray(direction));
52993         this._camera.lookat.add(new THREE.Vector3().fromArray(direction));
52994     };
52995     EarthState.prototype.update = function () { };
52996     return EarthState;
52997 }(State_1.StateBase));
52998 exports.EarthState = EarthState;
52999 exports.default = EarthState;
53000
53001
53002 },{"../../State":298,"three":242}],443:[function(require,module,exports){
53003 "use strict";
53004 var __extends = (this && this.__extends) || (function () {
53005     var extendStatics = function (d, b) {
53006         extendStatics = Object.setPrototypeOf ||
53007             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
53008             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
53009         return extendStatics(d, b);
53010     }
53011     return function (d, b) {
53012         extendStatics(d, b);
53013         function __() { this.constructor = d; }
53014         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
53015     };
53016 })();
53017 Object.defineProperty(exports, "__esModule", { value: true });
53018 var THREE = require("three");
53019 var State_1 = require("../../State");
53020 var InteractiveStateBase = /** @class */ (function (_super) {
53021     __extends(InteractiveStateBase, _super);
53022     function InteractiveStateBase(state) {
53023         var _this = _super.call(this, state) || this;
53024         _this._animationSpeed = 1 / 40;
53025         _this._rotationDelta = new State_1.RotationDelta(0, 0);
53026         _this._requestedRotationDelta = null;
53027         _this._basicRotation = [0, 0];
53028         _this._requestedBasicRotation = null;
53029         _this._requestedBasicRotationUnbounded = null;
53030         _this._rotationAcceleration = 0.86;
53031         _this._rotationIncreaseAlpha = 0.97;
53032         _this._rotationDecreaseAlpha = 0.9;
53033         _this._rotationThreshold = 1e-3;
53034         _this._unboundedRotationAlpha = 0.8;
53035         _this._desiredZoom = state.zoom;
53036         _this._minZoom = 0;
53037         _this._maxZoom = 3;
53038         _this._lookatDepth = 10;
53039         _this._desiredLookat = null;
53040         _this._desiredCenter = null;
53041         return _this;
53042     }
53043     InteractiveStateBase.prototype.rotate = function (rotationDelta) {
53044         if (this._currentNode == null) {
53045             return;
53046         }
53047         if (rotationDelta.phi === 0 && rotationDelta.theta === 0) {
53048             return;
53049         }
53050         this._desiredZoom = this._zoom;
53051         this._desiredLookat = null;
53052         this._requestedBasicRotation = null;
53053         if (this._requestedRotationDelta != null) {
53054             this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
53055             this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
53056         }
53057         else {
53058             this._requestedRotationDelta = new State_1.RotationDelta(rotationDelta.phi, rotationDelta.theta);
53059         }
53060     };
53061     InteractiveStateBase.prototype.rotateUnbounded = function (delta) {
53062         if (this._currentNode == null) {
53063             return;
53064         }
53065         this._requestedBasicRotation = null;
53066         this._requestedRotationDelta = null;
53067         this._applyRotation(delta, this._currentCamera);
53068         this._applyRotation(delta, this._previousCamera);
53069         if (!this._desiredLookat) {
53070             return;
53071         }
53072         var q = new THREE.Quaternion().setFromUnitVectors(this._currentCamera.up, new THREE.Vector3(0, 0, 1));
53073         var qInverse = q.clone().inverse();
53074         var offset = new THREE.Vector3()
53075             .copy(this._desiredLookat)
53076             .sub(this._camera.position)
53077             .applyQuaternion(q);
53078         var length = offset.length();
53079         var phi = Math.atan2(offset.y, offset.x);
53080         phi += delta.phi;
53081         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
53082         theta += delta.theta;
53083         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
53084         offset.x = Math.sin(theta) * Math.cos(phi);
53085         offset.y = Math.sin(theta) * Math.sin(phi);
53086         offset.z = Math.cos(theta);
53087         offset.applyQuaternion(qInverse);
53088         this._desiredLookat
53089             .copy(this._camera.position)
53090             .add(offset.multiplyScalar(length));
53091     };
53092     InteractiveStateBase.prototype.rotateWithoutInertia = function (rotationDelta) {
53093         if (this._currentNode == null) {
53094             return;
53095         }
53096         this._desiredZoom = this._zoom;
53097         this._desiredLookat = null;
53098         this._requestedBasicRotation = null;
53099         this._requestedRotationDelta = null;
53100         var threshold = Math.PI / (10 * Math.pow(2, this._zoom));
53101         var delta = {
53102             phi: this._spatial.clamp(rotationDelta.phi, -threshold, threshold),
53103             theta: this._spatial.clamp(rotationDelta.theta, -threshold, threshold),
53104         };
53105         this._applyRotation(delta, this._currentCamera);
53106         this._applyRotation(delta, this._previousCamera);
53107     };
53108     InteractiveStateBase.prototype.rotateBasic = function (basicRotation) {
53109         if (this._currentNode == null) {
53110             return;
53111         }
53112         this._desiredZoom = this._zoom;
53113         this._desiredLookat = null;
53114         this._requestedRotationDelta = null;
53115         if (this._requestedBasicRotation != null) {
53116             this._requestedBasicRotation[0] += basicRotation[0];
53117             this._requestedBasicRotation[1] += basicRotation[1];
53118             var threshold = 0.05 / Math.pow(2, this._zoom);
53119             this._requestedBasicRotation[0] =
53120                 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
53121             this._requestedBasicRotation[1] =
53122                 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
53123         }
53124         else {
53125             this._requestedBasicRotation = basicRotation.slice();
53126         }
53127     };
53128     InteractiveStateBase.prototype.rotateBasicUnbounded = function (basicRotation) {
53129         if (this._currentNode == null) {
53130             return;
53131         }
53132         if (this._requestedBasicRotationUnbounded != null) {
53133             this._requestedBasicRotationUnbounded[0] += basicRotation[0];
53134             this._requestedBasicRotationUnbounded[1] += basicRotation[1];
53135         }
53136         else {
53137             this._requestedBasicRotationUnbounded = basicRotation.slice();
53138         }
53139     };
53140     InteractiveStateBase.prototype.rotateBasicWithoutInertia = function (basic) {
53141         if (this._currentNode == null) {
53142             return;
53143         }
53144         this._desiredZoom = this._zoom;
53145         this._desiredLookat = null;
53146         this._requestedRotationDelta = null;
53147         this._requestedBasicRotation = null;
53148         var threshold = 0.05 / Math.pow(2, this._zoom);
53149         var basicRotation = basic.slice();
53150         basicRotation[0] = this._spatial.clamp(basicRotation[0], -threshold, threshold);
53151         basicRotation[1] = this._spatial.clamp(basicRotation[1], -threshold, threshold);
53152         this._applyRotationBasic(basicRotation);
53153     };
53154     InteractiveStateBase.prototype.rotateToBasic = function (basic) {
53155         if (this._currentNode == null) {
53156             return;
53157         }
53158         this._desiredZoom = this._zoom;
53159         this._desiredLookat = null;
53160         basic[0] = this._spatial.clamp(basic[0], 0, 1);
53161         basic[1] = this._spatial.clamp(basic[1], 0, 1);
53162         var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
53163         this._currentCamera.lookat.fromArray(lookat);
53164     };
53165     InteractiveStateBase.prototype.zoomIn = function (delta, reference) {
53166         if (this._currentNode == null) {
53167             return;
53168         }
53169         this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
53170         var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
53171         var currentCenterX = currentCenter[0];
53172         var currentCenterY = currentCenter[1];
53173         var zoom0 = Math.pow(2, this._zoom);
53174         var zoom1 = Math.pow(2, this._desiredZoom);
53175         var refX = reference[0];
53176         var refY = reference[1];
53177         if (this.currentTransform.gpano != null &&
53178             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
53179             if (refX - currentCenterX > 0.5) {
53180                 refX = refX - 1;
53181             }
53182             else if (currentCenterX - refX > 0.5) {
53183                 refX = 1 + refX;
53184             }
53185         }
53186         var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
53187         var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
53188         var gpano = this.currentTransform.gpano;
53189         if (this._currentNode.fullPano) {
53190             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
53191             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
53192         }
53193         else if (gpano != null &&
53194             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
53195             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
53196             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
53197         }
53198         else {
53199             newCenterX = this._spatial.clamp(newCenterX, 0, 1);
53200             newCenterY = this._spatial.clamp(newCenterY, 0, 1);
53201         }
53202         this._desiredLookat = new THREE.Vector3()
53203             .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
53204     };
53205     InteractiveStateBase.prototype.setCenter = function (center) {
53206         this._desiredLookat = null;
53207         this._requestedRotationDelta = null;
53208         this._requestedBasicRotation = null;
53209         this._desiredZoom = this._zoom;
53210         var clamped = [
53211             this._spatial.clamp(center[0], 0, 1),
53212             this._spatial.clamp(center[1], 0, 1),
53213         ];
53214         if (this._currentNode == null) {
53215             this._desiredCenter = clamped;
53216             return;
53217         }
53218         this._desiredCenter = null;
53219         var currentLookat = new THREE.Vector3()
53220             .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
53221         var previousTransform = this.previousTransform != null ?
53222             this.previousTransform :
53223             this.currentTransform;
53224         var previousLookat = new THREE.Vector3()
53225             .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
53226         this._currentCamera.lookat.copy(currentLookat);
53227         this._previousCamera.lookat.copy(previousLookat);
53228     };
53229     InteractiveStateBase.prototype.setZoom = function (zoom) {
53230         this._desiredLookat = null;
53231         this._requestedRotationDelta = null;
53232         this._requestedBasicRotation = null;
53233         this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
53234         this._desiredZoom = this._zoom;
53235     };
53236     InteractiveStateBase.prototype._applyRotation = function (delta, camera) {
53237         if (camera == null) {
53238             return;
53239         }
53240         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
53241         var qInverse = q.clone().inverse();
53242         var offset = new THREE.Vector3();
53243         offset.copy(camera.lookat).sub(camera.position);
53244         offset.applyQuaternion(q);
53245         var length = offset.length();
53246         var phi = Math.atan2(offset.y, offset.x);
53247         phi += delta.phi;
53248         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
53249         theta += delta.theta;
53250         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
53251         offset.x = Math.sin(theta) * Math.cos(phi);
53252         offset.y = Math.sin(theta) * Math.sin(phi);
53253         offset.z = Math.cos(theta);
53254         offset.applyQuaternion(qInverse);
53255         camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
53256     };
53257     InteractiveStateBase.prototype._applyRotationBasic = function (basicRotation) {
53258         var currentNode = this._currentNode;
53259         var previousNode = this._previousNode != null ?
53260             this.previousNode :
53261             this.currentNode;
53262         var currentCamera = this._currentCamera;
53263         var previousCamera = this._previousCamera;
53264         var currentTransform = this.currentTransform;
53265         var previousTransform = this.previousTransform != null ?
53266             this.previousTransform :
53267             this.currentTransform;
53268         var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
53269         var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
53270         var currentGPano = currentTransform.gpano;
53271         var previousGPano = previousTransform.gpano;
53272         if (currentNode.fullPano) {
53273             currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
53274             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0.05, 0.95);
53275         }
53276         else if (currentGPano != null &&
53277             currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
53278             currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
53279             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
53280         }
53281         else {
53282             currentBasic[0] = this._spatial.clamp(currentBasic[0] + basicRotation[0], 0, 1);
53283             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
53284         }
53285         if (previousNode.fullPano) {
53286             previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
53287             previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0.05, 0.95);
53288         }
53289         else if (previousGPano != null &&
53290             previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
53291             previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
53292             previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0, 1);
53293         }
53294         else {
53295             previousBasic[0] = this._spatial.clamp(previousBasic[0] + basicRotation[0], 0, 1);
53296             previousBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
53297         }
53298         var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
53299         currentCamera.lookat.fromArray(currentLookat);
53300         var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
53301         previousCamera.lookat.fromArray(previousLookat);
53302     };
53303     InteractiveStateBase.prototype._updateZoom = function (animationSpeed) {
53304         var diff = this._desiredZoom - this._zoom;
53305         var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
53306         if (diff === 0) {
53307             return;
53308         }
53309         else if (Math.abs(diff) < 2e-3) {
53310             this._zoom = this._desiredZoom;
53311             if (this._desiredLookat != null) {
53312                 this._desiredLookat = null;
53313             }
53314         }
53315         else {
53316             this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
53317         }
53318     };
53319     InteractiveStateBase.prototype._updateLookat = function (animationSpeed) {
53320         if (this._desiredLookat === null) {
53321             return;
53322         }
53323         var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
53324         if (Math.abs(diff) < 1e-6) {
53325             this._currentCamera.lookat.copy(this._desiredLookat);
53326             this._desiredLookat = null;
53327         }
53328         else {
53329             this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
53330         }
53331     };
53332     InteractiveStateBase.prototype._updateRotation = function () {
53333         if (this._requestedRotationDelta != null) {
53334             var length_1 = this._rotationDelta.lengthSquared();
53335             var requestedLength = this._requestedRotationDelta.lengthSquared();
53336             if (requestedLength > length_1) {
53337                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
53338             }
53339             else {
53340                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
53341             }
53342             this._requestedRotationDelta = null;
53343             return;
53344         }
53345         if (this._rotationDelta.isZero) {
53346             return;
53347         }
53348         var alpha = this.currentNode.fullPano ? 1 : this._alpha;
53349         this._rotationDelta.multiply(this._rotationAcceleration * alpha);
53350         this._rotationDelta.threshold(this._rotationThreshold);
53351     };
53352     InteractiveStateBase.prototype._updateRotationBasic = function () {
53353         if (this._requestedBasicRotation != null) {
53354             var x = this._basicRotation[0];
53355             var y = this._basicRotation[1];
53356             var reqX = this._requestedBasicRotation[0];
53357             var reqY = this._requestedBasicRotation[1];
53358             if (Math.abs(reqX) > Math.abs(x)) {
53359                 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
53360             }
53361             else {
53362                 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
53363             }
53364             if (Math.abs(reqY) > Math.abs(y)) {
53365                 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
53366             }
53367             else {
53368                 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
53369             }
53370             this._requestedBasicRotation = null;
53371             return;
53372         }
53373         if (this._requestedBasicRotationUnbounded != null) {
53374             var reqX = this._requestedBasicRotationUnbounded[0];
53375             var reqY = this._requestedBasicRotationUnbounded[1];
53376             if (Math.abs(reqX) > 0) {
53377                 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
53378             }
53379             if (Math.abs(reqY) > 0) {
53380                 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
53381             }
53382             if (this._desiredLookat != null) {
53383                 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
53384                 desiredBasicLookat[0] += reqX;
53385                 desiredBasicLookat[1] += reqY;
53386                 this._desiredLookat = new THREE.Vector3()
53387                     .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
53388             }
53389             this._requestedBasicRotationUnbounded = null;
53390         }
53391         if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
53392             return;
53393         }
53394         this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
53395         this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
53396         if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
53397             Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
53398             this._basicRotation = [0, 0];
53399         }
53400     };
53401     InteractiveStateBase.prototype._clearRotation = function () {
53402         if (this._currentNode.fullPano) {
53403             return;
53404         }
53405         if (this._requestedRotationDelta != null) {
53406             this._requestedRotationDelta = null;
53407         }
53408         if (!this._rotationDelta.isZero) {
53409             this._rotationDelta.reset();
53410         }
53411         if (this._requestedBasicRotation != null) {
53412             this._requestedBasicRotation = null;
53413         }
53414         if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
53415             this._basicRotation = [0, 0];
53416         }
53417     };
53418     InteractiveStateBase.prototype._setDesiredCenter = function () {
53419         if (this._desiredCenter == null) {
53420             return;
53421         }
53422         var lookatDirection = new THREE.Vector3()
53423             .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
53424             .sub(this._currentCamera.position);
53425         this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
53426         this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
53427         this._desiredCenter = null;
53428     };
53429     InteractiveStateBase.prototype._setDesiredZoom = function () {
53430         this._desiredZoom =
53431             this._currentNode.fullPano || this._previousNode == null ?
53432                 this._zoom : 0;
53433     };
53434     return InteractiveStateBase;
53435 }(State_1.StateBase));
53436 exports.InteractiveStateBase = InteractiveStateBase;
53437 exports.default = InteractiveStateBase;
53438
53439
53440 },{"../../State":298,"three":242}],444:[function(require,module,exports){
53441 "use strict";
53442 var __extends = (this && this.__extends) || (function () {
53443     var extendStatics = function (d, b) {
53444         extendStatics = Object.setPrototypeOf ||
53445             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
53446             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
53447         return extendStatics(d, b);
53448     }
53449     return function (d, b) {
53450         extendStatics(d, b);
53451         function __() { this.constructor = d; }
53452         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
53453     };
53454 })();
53455 Object.defineProperty(exports, "__esModule", { value: true });
53456 var State_1 = require("../../State");
53457 var InteractiveWaitingState = /** @class */ (function (_super) {
53458     __extends(InteractiveWaitingState, _super);
53459     function InteractiveWaitingState(state) {
53460         var _this = _super.call(this, state) || this;
53461         _this._adjustCameras();
53462         _this._motionless = _this._motionlessTransition();
53463         return _this;
53464     }
53465     InteractiveWaitingState.prototype.traverse = function () {
53466         return new State_1.TraversingState(this);
53467     };
53468     InteractiveWaitingState.prototype.wait = function () {
53469         return new State_1.WaitingState(this);
53470     };
53471     InteractiveWaitingState.prototype.prepend = function (nodes) {
53472         _super.prototype.prepend.call(this, nodes);
53473         this._motionless = this._motionlessTransition();
53474     };
53475     InteractiveWaitingState.prototype.set = function (nodes) {
53476         _super.prototype.set.call(this, nodes);
53477         this._motionless = this._motionlessTransition();
53478     };
53479     InteractiveWaitingState.prototype.move = function (delta) {
53480         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
53481     };
53482     InteractiveWaitingState.prototype.moveTo = function (position) {
53483         this._alpha = Math.max(0, Math.min(1, position));
53484     };
53485     InteractiveWaitingState.prototype.update = function (fps) {
53486         this._updateRotation();
53487         if (!this._rotationDelta.isZero) {
53488             this._applyRotation(this._rotationDelta, this._previousCamera);
53489             this._applyRotation(this._rotationDelta, this._currentCamera);
53490         }
53491         this._updateRotationBasic();
53492         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
53493             this._applyRotationBasic(this._basicRotation);
53494         }
53495         var animationSpeed = this._animationSpeed * (60 / fps);
53496         this._updateZoom(animationSpeed);
53497         this._updateLookat(animationSpeed);
53498         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
53499     };
53500     InteractiveWaitingState.prototype._getAlpha = function () {
53501         return this._motionless ? Math.round(this._alpha) : this._alpha;
53502     };
53503     InteractiveWaitingState.prototype._setCurrentCamera = function () {
53504         _super.prototype._setCurrentCamera.call(this);
53505         this._adjustCameras();
53506     };
53507     InteractiveWaitingState.prototype._adjustCameras = function () {
53508         if (this._previousNode == null) {
53509             return;
53510         }
53511         if (this._currentNode.fullPano) {
53512             var lookat = this._camera.lookat.clone().sub(this._camera.position);
53513             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
53514         }
53515         if (this._previousNode.fullPano) {
53516             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
53517             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
53518         }
53519     };
53520     return InteractiveWaitingState;
53521 }(State_1.InteractiveStateBase));
53522 exports.InteractiveWaitingState = InteractiveWaitingState;
53523 exports.default = InteractiveWaitingState;
53524
53525 },{"../../State":298}],445:[function(require,module,exports){
53526 "use strict";
53527 Object.defineProperty(exports, "__esModule", { value: true });
53528 var Error_1 = require("../../Error");
53529 var Geo_1 = require("../../Geo");
53530 var State_1 = require("../../State");
53531 var StateBase = /** @class */ (function () {
53532     function StateBase(state) {
53533         this._spatial = new Geo_1.Spatial();
53534         this._geoCoords = new Geo_1.GeoCoords();
53535         this._referenceThreshold = 0.01;
53536         this._transitionMode = state.transitionMode;
53537         this._reference = state.reference;
53538         this._alpha = state.alpha;
53539         this._camera = state.camera.clone();
53540         this._zoom = state.zoom;
53541         this._currentIndex = state.currentIndex;
53542         this._trajectory = state.trajectory.slice();
53543         this._trajectoryTransforms = [];
53544         this._trajectoryCameras = [];
53545         for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
53546             var node = _a[_i];
53547             var translation = this._nodeToTranslation(node, this._reference);
53548             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, node.cameraProjection);
53549             this._trajectoryTransforms.push(transform);
53550             this._trajectoryCameras.push(new Geo_1.Camera(transform));
53551         }
53552         this._currentNode = this._trajectory.length > 0 ?
53553             this._trajectory[this._currentIndex] :
53554             null;
53555         this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
53556             this._trajectory[this._currentIndex - 1] :
53557             null;
53558         this._currentCamera = this._trajectoryCameras.length > 0 ?
53559             this._trajectoryCameras[this._currentIndex].clone() :
53560             new Geo_1.Camera();
53561         this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
53562             this._trajectoryCameras[this._currentIndex - 1].clone() :
53563             this._currentCamera.clone();
53564     }
53565     Object.defineProperty(StateBase.prototype, "reference", {
53566         get: function () {
53567             return this._reference;
53568         },
53569         enumerable: true,
53570         configurable: true
53571     });
53572     Object.defineProperty(StateBase.prototype, "alpha", {
53573         get: function () {
53574             return this._getAlpha();
53575         },
53576         enumerable: true,
53577         configurable: true
53578     });
53579     Object.defineProperty(StateBase.prototype, "camera", {
53580         get: function () {
53581             return this._camera;
53582         },
53583         enumerable: true,
53584         configurable: true
53585     });
53586     Object.defineProperty(StateBase.prototype, "zoom", {
53587         get: function () {
53588             return this._zoom;
53589         },
53590         enumerable: true,
53591         configurable: true
53592     });
53593     Object.defineProperty(StateBase.prototype, "trajectory", {
53594         get: function () {
53595             return this._trajectory;
53596         },
53597         enumerable: true,
53598         configurable: true
53599     });
53600     Object.defineProperty(StateBase.prototype, "currentIndex", {
53601         get: function () {
53602             return this._currentIndex;
53603         },
53604         enumerable: true,
53605         configurable: true
53606     });
53607     Object.defineProperty(StateBase.prototype, "currentNode", {
53608         get: function () {
53609             return this._currentNode;
53610         },
53611         enumerable: true,
53612         configurable: true
53613     });
53614     Object.defineProperty(StateBase.prototype, "previousNode", {
53615         get: function () {
53616             return this._previousNode;
53617         },
53618         enumerable: true,
53619         configurable: true
53620     });
53621     Object.defineProperty(StateBase.prototype, "currentCamera", {
53622         get: function () {
53623             return this._currentCamera;
53624         },
53625         enumerable: true,
53626         configurable: true
53627     });
53628     Object.defineProperty(StateBase.prototype, "currentTransform", {
53629         get: function () {
53630             return this._trajectoryTransforms.length > 0 ?
53631                 this._trajectoryTransforms[this.currentIndex] : null;
53632         },
53633         enumerable: true,
53634         configurable: true
53635     });
53636     Object.defineProperty(StateBase.prototype, "previousTransform", {
53637         get: function () {
53638             return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
53639                 this._trajectoryTransforms[this.currentIndex - 1] : null;
53640         },
53641         enumerable: true,
53642         configurable: true
53643     });
53644     Object.defineProperty(StateBase.prototype, "motionless", {
53645         get: function () {
53646             return this._motionless;
53647         },
53648         enumerable: true,
53649         configurable: true
53650     });
53651     Object.defineProperty(StateBase.prototype, "transitionMode", {
53652         get: function () {
53653             return this._transitionMode;
53654         },
53655         enumerable: true,
53656         configurable: true
53657     });
53658     StateBase.prototype.earth = function () { throw new Error("Not implemented"); };
53659     StateBase.prototype.traverse = function () { throw new Error("Not implemented"); };
53660     StateBase.prototype.wait = function () { throw new Error("Not implemented"); };
53661     StateBase.prototype.waitInteractively = function () { throw new Error("Not implemented"); };
53662     StateBase.prototype.move = function (delta) { };
53663     StateBase.prototype.moveTo = function (position) { };
53664     StateBase.prototype.rotate = function (delta) { };
53665     StateBase.prototype.rotateUnbounded = function (delta) { };
53666     StateBase.prototype.rotateWithoutInertia = function (delta) { };
53667     StateBase.prototype.rotateBasic = function (basicRotation) { };
53668     StateBase.prototype.rotateBasicUnbounded = function (basicRotation) { };
53669     StateBase.prototype.rotateBasicWithoutInertia = function (basicRotation) { };
53670     StateBase.prototype.rotateToBasic = function (basic) { };
53671     StateBase.prototype.setSpeed = function (speed) { };
53672     StateBase.prototype.zoomIn = function (delta, reference) { };
53673     StateBase.prototype.update = function (fps) { };
53674     StateBase.prototype.setCenter = function (center) { };
53675     StateBase.prototype.setZoom = function (zoom) { };
53676     StateBase.prototype.dolly = function (delta) { };
53677     StateBase.prototype.orbit = function (rotation) { };
53678     StateBase.prototype.truck = function (direction) { };
53679     StateBase.prototype.append = function (nodes) {
53680         if (nodes.length < 1) {
53681             throw Error("Trajectory can not be empty");
53682         }
53683         if (this._currentIndex < 0) {
53684             this.set(nodes);
53685         }
53686         else {
53687             this._trajectory = this._trajectory.concat(nodes);
53688             this._appendToTrajectories(nodes);
53689         }
53690     };
53691     StateBase.prototype.prepend = function (nodes) {
53692         if (nodes.length < 1) {
53693             throw Error("Trajectory can not be empty");
53694         }
53695         this._trajectory = nodes.slice().concat(this._trajectory);
53696         this._currentIndex += nodes.length;
53697         this._setCurrentNode();
53698         var referenceReset = this._setReference(this._currentNode);
53699         if (referenceReset) {
53700             this._setTrajectories();
53701         }
53702         else {
53703             this._prependToTrajectories(nodes);
53704         }
53705         this._setCurrentCamera();
53706     };
53707     StateBase.prototype.remove = function (n) {
53708         if (n < 0) {
53709             throw Error("n must be a positive integer");
53710         }
53711         if (this._currentIndex - 1 < n) {
53712             throw Error("Current and previous nodes can not be removed");
53713         }
53714         for (var i = 0; i < n; i++) {
53715             this._trajectory.shift();
53716             this._trajectoryTransforms.shift();
53717             this._trajectoryCameras.shift();
53718             this._currentIndex--;
53719         }
53720         this._setCurrentNode();
53721     };
53722     StateBase.prototype.clearPrior = function () {
53723         if (this._currentIndex > 0) {
53724             this.remove(this._currentIndex - 1);
53725         }
53726     };
53727     StateBase.prototype.clear = function () {
53728         this.cut();
53729         if (this._currentIndex > 0) {
53730             this.remove(this._currentIndex - 1);
53731         }
53732     };
53733     StateBase.prototype.cut = function () {
53734         while (this._trajectory.length - 1 > this._currentIndex) {
53735             this._trajectory.pop();
53736             this._trajectoryTransforms.pop();
53737             this._trajectoryCameras.pop();
53738         }
53739     };
53740     StateBase.prototype.set = function (nodes) {
53741         this._setTrajectory(nodes);
53742         this._setCurrentNode();
53743         this._setReference(this._currentNode);
53744         this._setTrajectories();
53745         this._setCurrentCamera();
53746     };
53747     StateBase.prototype.getCenter = function () {
53748         return this._currentNode != null ?
53749             this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
53750             [0.5, 0.5];
53751     };
53752     StateBase.prototype.setTransitionMode = function (mode) {
53753         this._transitionMode = mode;
53754     };
53755     StateBase.prototype._getAlpha = function () { return 1; };
53756     StateBase.prototype._setCurrent = function () {
53757         this._setCurrentNode();
53758         var referenceReset = this._setReference(this._currentNode);
53759         if (referenceReset) {
53760             this._setTrajectories();
53761         }
53762         this._setCurrentCamera();
53763     };
53764     StateBase.prototype._setCurrentCamera = function () {
53765         this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
53766         this._previousCamera = this._currentIndex > 0 ?
53767             this._trajectoryCameras[this._currentIndex - 1].clone() :
53768             this._currentCamera.clone();
53769     };
53770     StateBase.prototype._motionlessTransition = function () {
53771         var nodesSet = this._currentNode != null && this._previousNode != null;
53772         return nodesSet && (this._transitionMode === State_1.TransitionMode.Instantaneous || !(this._currentNode.merged &&
53773             this._previousNode.merged &&
53774             this._withinOriginalDistance() &&
53775             this._sameConnectedComponent()));
53776     };
53777     StateBase.prototype._setReference = function (node) {
53778         // do not reset reference if node is within threshold distance
53779         if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
53780             Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
53781             return false;
53782         }
53783         // do not reset reference if previous node exist and transition is with motion
53784         if (this._previousNode != null && !this._motionlessTransition()) {
53785             return false;
53786         }
53787         this._reference.lat = node.latLon.lat;
53788         this._reference.lon = node.latLon.lon;
53789         this._reference.alt = node.alt;
53790         return true;
53791     };
53792     StateBase.prototype._setCurrentNode = function () {
53793         this._currentNode = this._trajectory.length > 0 ?
53794             this._trajectory[this._currentIndex] :
53795             null;
53796         this._previousNode = this._currentIndex > 0 ?
53797             this._trajectory[this._currentIndex - 1] :
53798             null;
53799     };
53800     StateBase.prototype._setTrajectory = function (nodes) {
53801         if (nodes.length < 1) {
53802             throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
53803         }
53804         if (this._currentNode != null) {
53805             this._trajectory = [this._currentNode].concat(nodes);
53806             this._currentIndex = 1;
53807         }
53808         else {
53809             this._trajectory = nodes.slice();
53810             this._currentIndex = 0;
53811         }
53812     };
53813     StateBase.prototype._setTrajectories = function () {
53814         this._trajectoryTransforms.length = 0;
53815         this._trajectoryCameras.length = 0;
53816         this._appendToTrajectories(this._trajectory);
53817     };
53818     StateBase.prototype._appendToTrajectories = function (nodes) {
53819         for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
53820             var node = nodes_1[_i];
53821             if (!node.assetsCached) {
53822                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
53823             }
53824             var translation = this._nodeToTranslation(node, this.reference);
53825             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, node.cameraProjection);
53826             this._trajectoryTransforms.push(transform);
53827             this._trajectoryCameras.push(new Geo_1.Camera(transform));
53828         }
53829     };
53830     StateBase.prototype._prependToTrajectories = function (nodes) {
53831         for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
53832             var node = _a[_i];
53833             if (!node.assetsCached) {
53834                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
53835             }
53836             var translation = this._nodeToTranslation(node, this.reference);
53837             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, node.cameraProjection);
53838             this._trajectoryTransforms.unshift(transform);
53839             this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
53840         }
53841     };
53842     StateBase.prototype._nodeToTranslation = function (node, reference) {
53843         return Geo_1.Geo.computeTranslation({ alt: node.alt, lat: node.latLon.lat, lon: node.latLon.lon }, node.rotation, reference);
53844     };
53845     StateBase.prototype._sameConnectedComponent = function () {
53846         var current = this._currentNode;
53847         var previous = this._previousNode;
53848         return !!current && !!previous &&
53849             current.mergeCC === previous.mergeCC;
53850     };
53851     StateBase.prototype._withinOriginalDistance = function () {
53852         var current = this._currentNode;
53853         var previous = this._previousNode;
53854         if (!current || !previous) {
53855             return true;
53856         }
53857         // 50 km/h moves 28m in 2s
53858         var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
53859         return distance < 25;
53860     };
53861     return StateBase;
53862 }());
53863 exports.StateBase = StateBase;
53864
53865 },{"../../Error":293,"../../Geo":294,"../../State":298}],446:[function(require,module,exports){
53866 "use strict";
53867 var __extends = (this && this.__extends) || (function () {
53868     var extendStatics = function (d, b) {
53869         extendStatics = Object.setPrototypeOf ||
53870             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
53871             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
53872         return extendStatics(d, b);
53873     }
53874     return function (d, b) {
53875         extendStatics(d, b);
53876         function __() { this.constructor = d; }
53877         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
53878     };
53879 })();
53880 Object.defineProperty(exports, "__esModule", { value: true });
53881 var UnitBezier = require("@mapbox/unitbezier");
53882 var State_1 = require("../../State");
53883 var TraversingState = /** @class */ (function (_super) {
53884     __extends(TraversingState, _super);
53885     function TraversingState(state) {
53886         var _this = _super.call(this, state) || this;
53887         _this._adjustCameras();
53888         _this._motionless = _this._motionlessTransition();
53889         _this._baseAlpha = _this._alpha;
53890         _this._speedCoefficient = 1;
53891         _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
53892         _this._useBezier = false;
53893         return _this;
53894     }
53895     TraversingState.prototype.earth = function () {
53896         return new State_1.EarthState(this);
53897     };
53898     TraversingState.prototype.wait = function () {
53899         return new State_1.WaitingState(this);
53900     };
53901     TraversingState.prototype.waitInteractively = function () {
53902         return new State_1.InteractiveWaitingState(this);
53903     };
53904     TraversingState.prototype.append = function (nodes) {
53905         var emptyTrajectory = this._trajectory.length === 0;
53906         if (emptyTrajectory) {
53907             this._resetTransition();
53908         }
53909         _super.prototype.append.call(this, nodes);
53910         if (emptyTrajectory) {
53911             this._setDesiredCenter();
53912             this._setDesiredZoom();
53913         }
53914     };
53915     TraversingState.prototype.prepend = function (nodes) {
53916         var emptyTrajectory = this._trajectory.length === 0;
53917         if (emptyTrajectory) {
53918             this._resetTransition();
53919         }
53920         _super.prototype.prepend.call(this, nodes);
53921         if (emptyTrajectory) {
53922             this._setDesiredCenter();
53923             this._setDesiredZoom();
53924         }
53925     };
53926     TraversingState.prototype.set = function (nodes) {
53927         _super.prototype.set.call(this, nodes);
53928         this._desiredLookat = null;
53929         this._resetTransition();
53930         this._clearRotation();
53931         this._setDesiredCenter();
53932         this._setDesiredZoom();
53933         if (this._trajectory.length < 3) {
53934             this._useBezier = true;
53935         }
53936     };
53937     TraversingState.prototype.setSpeed = function (speed) {
53938         this._speedCoefficient = this._spatial.clamp(speed, 0, 10);
53939     };
53940     TraversingState.prototype.update = function (fps) {
53941         if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
53942             this._currentIndex += 1;
53943             this._useBezier = this._trajectory.length < 3 &&
53944                 this._currentIndex + 1 === this._trajectory.length;
53945             this._setCurrent();
53946             this._resetTransition();
53947             this._clearRotation();
53948             this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
53949             this._desiredLookat = null;
53950         }
53951         var animationSpeed = this._animationSpeed * (60 / fps);
53952         this._baseAlpha = Math.min(1, this._baseAlpha + this._speedCoefficient * animationSpeed);
53953         if (this._useBezier) {
53954             this._alpha = this._unitBezier.solve(this._baseAlpha);
53955         }
53956         else {
53957             this._alpha = this._baseAlpha;
53958         }
53959         this._updateRotation();
53960         if (!this._rotationDelta.isZero) {
53961             this._applyRotation(this._rotationDelta, this._previousCamera);
53962             this._applyRotation(this._rotationDelta, this._currentCamera);
53963         }
53964         this._updateRotationBasic();
53965         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
53966             this._applyRotationBasic(this._basicRotation);
53967         }
53968         this._updateZoom(animationSpeed);
53969         this._updateLookat(animationSpeed);
53970         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
53971     };
53972     TraversingState.prototype._getAlpha = function () {
53973         return this._motionless ? Math.ceil(this._alpha) : this._alpha;
53974     };
53975     TraversingState.prototype._setCurrentCamera = function () {
53976         _super.prototype._setCurrentCamera.call(this);
53977         this._adjustCameras();
53978     };
53979     TraversingState.prototype._adjustCameras = function () {
53980         if (this._previousNode == null) {
53981             return;
53982         }
53983         var lookat = this._camera.lookat.clone().sub(this._camera.position);
53984         this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
53985         if (this._currentNode.fullPano) {
53986             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
53987         }
53988     };
53989     TraversingState.prototype._resetTransition = function () {
53990         this._alpha = 0;
53991         this._baseAlpha = 0;
53992         this._motionless = this._motionlessTransition();
53993     };
53994     return TraversingState;
53995 }(State_1.InteractiveStateBase));
53996 exports.TraversingState = TraversingState;
53997 exports.default = TraversingState;
53998
53999 },{"../../State":298,"@mapbox/unitbezier":2}],447:[function(require,module,exports){
54000 "use strict";
54001 var __extends = (this && this.__extends) || (function () {
54002     var extendStatics = function (d, b) {
54003         extendStatics = Object.setPrototypeOf ||
54004             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
54005             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
54006         return extendStatics(d, b);
54007     }
54008     return function (d, b) {
54009         extendStatics(d, b);
54010         function __() { this.constructor = d; }
54011         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
54012     };
54013 })();
54014 Object.defineProperty(exports, "__esModule", { value: true });
54015 var State_1 = require("../../State");
54016 var WaitingState = /** @class */ (function (_super) {
54017     __extends(WaitingState, _super);
54018     function WaitingState(state) {
54019         var _this = _super.call(this, state) || this;
54020         _this._zoom = 0;
54021         _this._adjustCameras();
54022         _this._motionless = _this._motionlessTransition();
54023         return _this;
54024     }
54025     WaitingState.prototype.traverse = function () {
54026         return new State_1.TraversingState(this);
54027     };
54028     WaitingState.prototype.waitInteractively = function () {
54029         return new State_1.InteractiveWaitingState(this);
54030     };
54031     WaitingState.prototype.prepend = function (nodes) {
54032         _super.prototype.prepend.call(this, nodes);
54033         this._motionless = this._motionlessTransition();
54034     };
54035     WaitingState.prototype.set = function (nodes) {
54036         _super.prototype.set.call(this, nodes);
54037         this._motionless = this._motionlessTransition();
54038     };
54039     WaitingState.prototype.move = function (delta) {
54040         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
54041     };
54042     WaitingState.prototype.moveTo = function (position) {
54043         this._alpha = Math.max(0, Math.min(1, position));
54044     };
54045     WaitingState.prototype.update = function (fps) {
54046         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
54047     };
54048     WaitingState.prototype._getAlpha = function () {
54049         return this._motionless ? Math.round(this._alpha) : this._alpha;
54050     };
54051     WaitingState.prototype._setCurrentCamera = function () {
54052         _super.prototype._setCurrentCamera.call(this);
54053         this._adjustCameras();
54054     };
54055     WaitingState.prototype._adjustCameras = function () {
54056         if (this._previousNode == null) {
54057             return;
54058         }
54059         if (this._currentNode.fullPano) {
54060             var lookat = this._camera.lookat.clone().sub(this._camera.position);
54061             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
54062         }
54063         if (this._previousNode.fullPano) {
54064             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
54065             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
54066         }
54067     };
54068     return WaitingState;
54069 }(State_1.StateBase));
54070 exports.WaitingState = WaitingState;
54071 exports.default = WaitingState;
54072
54073 },{"../../State":298}],448:[function(require,module,exports){
54074 "use strict";
54075 Object.defineProperty(exports, "__esModule", { value: true });
54076 var rxjs_1 = require("rxjs");
54077 /**
54078  * @class ImageTileLoader
54079  *
54080  * @classdesc Represents a loader of image tiles.
54081  */
54082 var ImageTileLoader = /** @class */ (function () {
54083     /**
54084      * Create a new node image tile loader instance.
54085      *
54086      * @param {string} scheme - The URI scheme.
54087      * @param {string} host - The URI host.
54088      * @param {string} [origin] - The origin query param.
54089      */
54090     function ImageTileLoader(scheme, host, origin) {
54091         this._scheme = scheme;
54092         this._host = host;
54093         this._origin = origin != null ? "?origin=" + origin : "";
54094     }
54095     /**
54096      * Retrieve an image tile.
54097      *
54098      * @description Retrieve an image tile by specifying the area
54099      * as well as the scaled size.
54100      *
54101      * @param {string} identifier - The identifier of the image.
54102      * @param {number} x - The top left x pixel coordinate for the tile
54103      * in the original image.
54104      * @param {number} y - The top left y pixel coordinate for the tile
54105      * in the original image.
54106      * @param {number} w - The pixel width of the tile in the original image.
54107      * @param {number} h - The pixel height of the tile in the original image.
54108      * @param {number} scaledW - The scaled width of the returned tile.
54109      * @param {number} scaledH - The scaled height of the returned tile.
54110      */
54111     ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
54112         var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
54113         var url = this._scheme +
54114             "://" +
54115             this._host +
54116             characteristics +
54117             this._origin;
54118         var xmlHTTP = null;
54119         return [rxjs_1.Observable.create(function (subscriber) {
54120                 xmlHTTP = new XMLHttpRequest();
54121                 xmlHTTP.open("GET", url, true);
54122                 xmlHTTP.responseType = "arraybuffer";
54123                 xmlHTTP.timeout = 15000;
54124                 xmlHTTP.onload = function (event) {
54125                     if (xmlHTTP.status !== 200) {
54126                         subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
54127                             ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
54128                         return;
54129                     }
54130                     var image = new Image();
54131                     image.crossOrigin = "Anonymous";
54132                     image.onload = function (e) {
54133                         subscriber.next(image);
54134                         subscriber.complete();
54135                     };
54136                     image.onerror = function (error) {
54137                         subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
54138                     };
54139                     var blob = new Blob([xmlHTTP.response]);
54140                     image.src = window.URL.createObjectURL(blob);
54141                 };
54142                 xmlHTTP.onerror = function (error) {
54143                     subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
54144                 };
54145                 xmlHTTP.ontimeout = function (error) {
54146                     subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
54147                 };
54148                 xmlHTTP.onabort = function (event) {
54149                     subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
54150                 };
54151                 xmlHTTP.send(null);
54152             }),
54153             function () {
54154                 if (xmlHTTP != null) {
54155                     xmlHTTP.abort();
54156                 }
54157             },
54158         ];
54159     };
54160     return ImageTileLoader;
54161 }());
54162 exports.ImageTileLoader = ImageTileLoader;
54163 exports.default = ImageTileLoader;
54164
54165 },{"rxjs":43}],449:[function(require,module,exports){
54166 "use strict";
54167 Object.defineProperty(exports, "__esModule", { value: true });
54168 /**
54169  * @class ImageTileStore
54170  *
54171  * @classdesc Represents a store for image tiles.
54172  */
54173 var ImageTileStore = /** @class */ (function () {
54174     /**
54175      * Create a new node image tile store instance.
54176      */
54177     function ImageTileStore() {
54178         this._images = {};
54179     }
54180     /**
54181      * Add an image tile to the store.
54182      *
54183      * @param {HTMLImageElement} image - The image tile.
54184      * @param {string} key - The identifier for the tile.
54185      * @param {number} level - The level of the tile.
54186      */
54187     ImageTileStore.prototype.addImage = function (image, key, level) {
54188         if (!(level in this._images)) {
54189             this._images[level] = {};
54190         }
54191         this._images[level][key] = image;
54192     };
54193     /**
54194      * Dispose the store.
54195      *
54196      * @description Disposes all cached assets.
54197      */
54198     ImageTileStore.prototype.dispose = function () {
54199         for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
54200             var level = _a[_i];
54201             var levelImages = this._images[level];
54202             for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
54203                 var key = _c[_b];
54204                 window.URL.revokeObjectURL(levelImages[key].src);
54205                 delete levelImages[key];
54206             }
54207             delete this._images[level];
54208         }
54209     };
54210     /**
54211      * Get an image tile from the store.
54212      *
54213      * @param {string} key - The identifier for the tile.
54214      * @param {number} level - The level of the tile.
54215      */
54216     ImageTileStore.prototype.getImage = function (key, level) {
54217         return this._images[level][key];
54218     };
54219     /**
54220      * Check if an image tile exist in the store.
54221      *
54222      * @param {string} key - The identifier for the tile.
54223      * @param {number} level - The level of the tile.
54224      */
54225     ImageTileStore.prototype.hasImage = function (key, level) {
54226         return level in this._images && key in this._images[level];
54227     };
54228     return ImageTileStore;
54229 }());
54230 exports.ImageTileStore = ImageTileStore;
54231 exports.default = ImageTileStore;
54232
54233 },{}],450:[function(require,module,exports){
54234 "use strict";
54235 Object.defineProperty(exports, "__esModule", { value: true });
54236 var Geo_1 = require("../Geo");
54237 /**
54238  * @class RegionOfInterestCalculator
54239  *
54240  * @classdesc Represents a calculator for regions of interest.
54241  */
54242 var RegionOfInterestCalculator = /** @class */ (function () {
54243     function RegionOfInterestCalculator() {
54244         this._viewportCoords = new Geo_1.ViewportCoords();
54245     }
54246     /**
54247      * Compute a region of interest based on the current render camera
54248      * and the viewport size.
54249      *
54250      * @param {RenderCamera} renderCamera - Render camera used for unprojections.
54251      * @param {ISize} size - Viewport size in pixels.
54252      * @param {Transform} transform - Transform used for projections.
54253      *
54254      * @returns {IRegionOfInterest} A region of interest.
54255      */
54256     RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
54257         var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
54258         var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
54259         this._clipBoundingBox(bbox);
54260         var viewportPixelWidth = 2 / size.width;
54261         var viewportPixelHeight = 2 / size.height;
54262         var centralViewportPixel = [
54263             [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
54264             [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
54265             [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
54266             [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
54267         ];
54268         var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
54269         return {
54270             bbox: bbox,
54271             pixelHeight: cpbox.maxY - cpbox.minY,
54272             pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
54273         };
54274     };
54275     RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
54276         var points = [];
54277         var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
54278         var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
54279         for (var side = 0; side < 4; ++side) {
54280             var o = os[side];
54281             var d = ds[side];
54282             for (var i = 0; i < pointsPerSide; ++i) {
54283                 points.push([o[0] + d[0] * i / pointsPerSide,
54284                     o[1] + d[1] * i / pointsPerSide]);
54285             }
54286         }
54287         return points;
54288     };
54289     RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
54290         var _this = this;
54291         var basicPoints = viewportPoints
54292             .map(function (point) {
54293             return _this._viewportCoords
54294                 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
54295         });
54296         if (transform.gpano != null) {
54297             return this._boundingBoxPano(basicPoints);
54298         }
54299         else {
54300             return this._boundingBox(basicPoints);
54301         }
54302     };
54303     RegionOfInterestCalculator.prototype._boundingBox = function (points) {
54304         var bbox = {
54305             maxX: Number.NEGATIVE_INFINITY,
54306             maxY: Number.NEGATIVE_INFINITY,
54307             minX: Number.POSITIVE_INFINITY,
54308             minY: Number.POSITIVE_INFINITY,
54309         };
54310         for (var i = 0; i < points.length; ++i) {
54311             bbox.minX = Math.min(bbox.minX, points[i][0]);
54312             bbox.maxX = Math.max(bbox.maxX, points[i][0]);
54313             bbox.minY = Math.min(bbox.minY, points[i][1]);
54314             bbox.maxY = Math.max(bbox.maxY, points[i][1]);
54315         }
54316         return bbox;
54317     };
54318     RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
54319         var _this = this;
54320         var xs = [];
54321         var ys = [];
54322         for (var i = 0; i < points.length; ++i) {
54323             xs.push(points[i][0]);
54324             ys.push(points[i][1]);
54325         }
54326         xs.sort(function (a, b) { return _this._sign(a - b); });
54327         ys.sort(function (a, b) { return _this._sign(a - b); });
54328         var intervalX = this._intervalPano(xs);
54329         return {
54330             maxX: intervalX[1],
54331             maxY: ys[ys.length - 1],
54332             minX: intervalX[0],
54333             minY: ys[0],
54334         };
54335     };
54336     /**
54337      * Find the max interval between consecutive numbers.
54338      * Assumes numbers are between 0 and 1, sorted and that
54339      * x is equivalent to x + 1.
54340      */
54341     RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
54342         var maxdx = 0;
54343         var maxi = -1;
54344         for (var i = 0; i < xs.length - 1; ++i) {
54345             var dx = xs[i + 1] - xs[i];
54346             if (dx > maxdx) {
54347                 maxdx = dx;
54348                 maxi = i;
54349             }
54350         }
54351         var loopdx = xs[0] + 1 - xs[xs.length - 1];
54352         if (loopdx > maxdx) {
54353             return [xs[0], xs[xs.length - 1]];
54354         }
54355         else {
54356             return [xs[maxi + 1], xs[maxi]];
54357         }
54358     };
54359     RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
54360         bbox.minX = Math.max(0, Math.min(1, bbox.minX));
54361         bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
54362         bbox.minY = Math.max(0, Math.min(1, bbox.minY));
54363         bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
54364     };
54365     RegionOfInterestCalculator.prototype._sign = function (n) {
54366         return n > 0 ? 1 : n < 0 ? -1 : 0;
54367     };
54368     return RegionOfInterestCalculator;
54369 }());
54370 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
54371 exports.default = RegionOfInterestCalculator;
54372
54373 },{"../Geo":294}],451:[function(require,module,exports){
54374 "use strict";
54375 Object.defineProperty(exports, "__esModule", { value: true });
54376 var operators_1 = require("rxjs/operators");
54377 var THREE = require("three");
54378 var rxjs_1 = require("rxjs");
54379 /**
54380  * @class TextureProvider
54381  *
54382  * @classdesc Represents a provider of textures.
54383  */
54384 var TextureProvider = /** @class */ (function () {
54385     /**
54386      * Create a new node texture provider instance.
54387      *
54388      * @param {string} key - The identifier of the image for which to request tiles.
54389      * @param {number} width - The full width of the original image.
54390      * @param {number} height - The full height of the original image.
54391      * @param {number} tileSize - The size used when requesting tiles.
54392      * @param {HTMLImageElement} background - Image to use as background.
54393      * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
54394      * @param {ImageTileStore} imageTileStore - Store for saving tiles.
54395      * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
54396      */
54397     function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
54398         this._disposed = false;
54399         this._key = key;
54400         if (width <= 0 || height <= 0) {
54401             console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
54402         }
54403         this._width = width;
54404         this._height = height;
54405         this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
54406         this._currentLevel = -1;
54407         this._tileSize = tileSize;
54408         this._updated$ = new rxjs_1.Subject();
54409         this._createdSubject$ = new rxjs_1.Subject();
54410         this._created$ = this._createdSubject$.pipe(operators_1.publishReplay(1), operators_1.refCount());
54411         this._createdSubscription = this._created$.subscribe(function () { });
54412         this._hasSubject$ = new rxjs_1.Subject();
54413         this._has$ = this._hasSubject$.pipe(operators_1.startWith(false), operators_1.publishReplay(1), operators_1.refCount());
54414         this._hasSubscription = this._has$.subscribe(function () { });
54415         this._abortFunctions = [];
54416         this._tileSubscriptions = {};
54417         this._renderedCurrentLevelTiles = {};
54418         this._renderedTiles = {};
54419         this._background = background;
54420         this._camera = null;
54421         this._imageTileLoader = imageTileLoader;
54422         this._imageTileStore = imageTileStore;
54423         this._renderer = renderer;
54424         this._renderTarget = null;
54425         this._roi = null;
54426     }
54427     Object.defineProperty(TextureProvider.prototype, "disposed", {
54428         /**
54429          * Get disposed.
54430          *
54431          * @returns {boolean} Value indicating whether provider has
54432          * been disposed.
54433          */
54434         get: function () {
54435             return this._disposed;
54436         },
54437         enumerable: true,
54438         configurable: true
54439     });
54440     Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
54441         /**
54442          * Get hasTexture$.
54443          *
54444          * @returns {Observable<boolean>} Observable emitting
54445          * values indicating when the existance of a texture
54446          * changes.
54447          */
54448         get: function () {
54449             return this._has$;
54450         },
54451         enumerable: true,
54452         configurable: true
54453     });
54454     Object.defineProperty(TextureProvider.prototype, "key", {
54455         /**
54456          * Get key.
54457          *
54458          * @returns {boolean} The identifier of the image for
54459          * which to render textures.
54460          */
54461         get: function () {
54462             return this._key;
54463         },
54464         enumerable: true,
54465         configurable: true
54466     });
54467     Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
54468         /**
54469          * Get textureUpdated$.
54470          *
54471          * @returns {Observable<boolean>} Observable emitting
54472          * values when an existing texture has been updated.
54473          */
54474         get: function () {
54475             return this._updated$;
54476         },
54477         enumerable: true,
54478         configurable: true
54479     });
54480     Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
54481         /**
54482          * Get textureCreated$.
54483          *
54484          * @returns {Observable<boolean>} Observable emitting
54485          * values when a new texture has been created.
54486          */
54487         get: function () {
54488             return this._created$;
54489         },
54490         enumerable: true,
54491         configurable: true
54492     });
54493     /**
54494      * Abort all outstanding image tile requests.
54495      */
54496     TextureProvider.prototype.abort = function () {
54497         for (var key in this._tileSubscriptions) {
54498             if (!this._tileSubscriptions.hasOwnProperty(key)) {
54499                 continue;
54500             }
54501             this._tileSubscriptions[key].unsubscribe();
54502         }
54503         this._tileSubscriptions = {};
54504         for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
54505             var abort = _a[_i];
54506             abort();
54507         }
54508         this._abortFunctions = [];
54509     };
54510     /**
54511      * Dispose the provider.
54512      *
54513      * @description Disposes all cached assets and
54514      * aborts all outstanding image tile requests.
54515      */
54516     TextureProvider.prototype.dispose = function () {
54517         if (this._disposed) {
54518             console.warn("Texture already disposed (" + this._key + ")");
54519             return;
54520         }
54521         this.abort();
54522         if (this._renderTarget != null) {
54523             this._renderTarget.dispose();
54524             this._renderTarget = null;
54525         }
54526         this._imageTileStore.dispose();
54527         this._imageTileStore = null;
54528         this._background = null;
54529         this._camera = null;
54530         this._imageTileLoader = null;
54531         this._renderer = null;
54532         this._roi = null;
54533         this._createdSubscription.unsubscribe();
54534         this._hasSubscription.unsubscribe();
54535         this._disposed = true;
54536     };
54537     /**
54538      * Set the region of interest.
54539      *
54540      * @description When the region of interest is set the
54541      * the tile level is determined and tiles for the region
54542      * are fetched from the store or the loader and renderedLevel
54543      * to the texture.
54544      *
54545      * @param {IRegionOfInterest} roi - Spatial edges to cache.
54546      */
54547     TextureProvider.prototype.setRegionOfInterest = function (roi) {
54548         if (this._width <= 0 || this._height <= 0) {
54549             return;
54550         }
54551         this._roi = roi;
54552         var width = 1 / this._roi.pixelWidth;
54553         var height = 1 / this._roi.pixelHeight;
54554         var size = Math.max(height, width);
54555         var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.ceil(Math.log(size) / Math.log(2))));
54556         if (currentLevel !== this._currentLevel) {
54557             this.abort();
54558             this._currentLevel = currentLevel;
54559             if (!(this._currentLevel in this._renderedTiles)) {
54560                 this._renderedTiles[this._currentLevel] = [];
54561             }
54562             this._renderedCurrentLevelTiles = {};
54563             for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
54564                 var tile = _a[_i];
54565                 this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
54566             }
54567         }
54568         var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
54569         var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
54570         var tiles = this._getTiles(topLeft, bottomRight);
54571         if (this._camera == null) {
54572             this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
54573             this._camera.position.z = 1;
54574             var gl = this._renderer.getContext();
54575             var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
54576             var backgroundSize = Math.max(this._width, this._height);
54577             var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
54578             var targetWidth = Math.floor(scale * this._width);
54579             var targetHeight = Math.floor(scale * this._height);
54580             this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
54581                 depthBuffer: false,
54582                 format: THREE.RGBFormat,
54583                 magFilter: THREE.LinearFilter,
54584                 minFilter: THREE.LinearFilter,
54585                 stencilBuffer: false,
54586             });
54587             this._renderToTarget(0, 0, this._width, this._height, this._background);
54588             this._createdSubject$.next(this._renderTarget.texture);
54589             this._hasSubject$.next(true);
54590         }
54591         this._fetchTiles(tiles);
54592     };
54593     TextureProvider.prototype.setTileSize = function (tileSize) {
54594         this._tileSize = tileSize;
54595     };
54596     /**
54597      * Update the image used as background for the texture.
54598      *
54599      * @param {HTMLImageElement} background - The background image.
54600      */
54601     TextureProvider.prototype.updateBackground = function (background) {
54602         this._background = background;
54603     };
54604     /**
54605      * Retrieve an image tile.
54606      *
54607      * @description Retrieve an image tile and render it to the
54608      * texture. Add the tile to the store and emit to the updated
54609      * observable.
54610      *
54611      * @param {Array<number>} tile - The tile coordinates.
54612      * @param {number} level - The tile level.
54613      * @param {number} x - The top left x pixel coordinate of the tile.
54614      * @param {number} y - The top left y pixel coordinate of the tile.
54615      * @param {number} w - The pixel width of the tile.
54616      * @param {number} h - The pixel height of the tile.
54617      * @param {number} scaledW - The scaled width of the returned tile.
54618      * @param {number} scaledH - The scaled height of the returned tile.
54619      */
54620     TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
54621         var _this = this;
54622         var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
54623         var tile$ = getTile[0];
54624         var abort = getTile[1];
54625         this._abortFunctions.push(abort);
54626         var tileKey = this._tileKey(this._tileSize, tile);
54627         var subscription = tile$
54628             .subscribe(function (image) {
54629             _this._renderToTarget(x, y, w, h, image);
54630             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
54631             _this._removeFromArray(abort, _this._abortFunctions);
54632             _this._setTileRendered(tile, _this._currentLevel);
54633             _this._imageTileStore.addImage(image, tileKey, level);
54634             _this._updated$.next(true);
54635         }, function (error) {
54636             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
54637             _this._removeFromArray(abort, _this._abortFunctions);
54638             console.error(error);
54639         });
54640         if (!subscription.closed) {
54641             this._tileSubscriptions[tileKey] = subscription;
54642         }
54643     };
54644     /**
54645      * Retrieve image tiles.
54646      *
54647      * @description Retrieve a image tiles and render them to the
54648      * texture. Retrieve from store if it exists, otherwise Retrieve
54649      * from loader.
54650      *
54651      * @param {Array<Array<number>>} tiles - Array of tile coordinates to
54652      * retrieve.
54653      */
54654     TextureProvider.prototype._fetchTiles = function (tiles) {
54655         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
54656         for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
54657             var tile = tiles_1[_i];
54658             var tileKey = this._tileKey(this._tileSize, tile);
54659             if (tileKey in this._renderedCurrentLevelTiles ||
54660                 tileKey in this._tileSubscriptions) {
54661                 continue;
54662             }
54663             var tileX = tileSize * tile[0];
54664             var tileY = tileSize * tile[1];
54665             var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
54666             var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
54667             if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
54668                 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
54669                 this._setTileRendered(tile, this._currentLevel);
54670                 this._updated$.next(true);
54671                 continue;
54672             }
54673             var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
54674             var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
54675             this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
54676         }
54677     };
54678     /**
54679      * Get tile coordinates for a point using the current level.
54680      *
54681      * @param {Array<number>} point - Point in basic coordinates.
54682      *
54683      * @returns {Array<number>} x and y tile coodinates.
54684      */
54685     TextureProvider.prototype._getTileCoords = function (point) {
54686         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
54687         var maxX = Math.ceil(this._width / tileSize) - 1;
54688         var maxY = Math.ceil(this._height / tileSize) - 1;
54689         return [
54690             Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
54691             Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
54692         ];
54693     };
54694     /**
54695      * Get tile coordinates for all tiles contained in a bounding
54696      * box.
54697      *
54698      * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
54699      * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
54700      *
54701      * @returns {Array<Array<number>>} Array of x, y tile coodinates.
54702      */
54703     TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
54704         var xs = [];
54705         if (topLeft[0] > bottomRight[0]) {
54706             var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
54707             var maxX = Math.ceil(this._width / tileSize) - 1;
54708             for (var x = topLeft[0]; x <= maxX; x++) {
54709                 xs.push(x);
54710             }
54711             for (var x = 0; x <= bottomRight[0]; x++) {
54712                 xs.push(x);
54713             }
54714         }
54715         else {
54716             for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
54717                 xs.push(x);
54718             }
54719         }
54720         var tiles = [];
54721         for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
54722             var x = xs_1[_i];
54723             for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
54724                 tiles.push([x, y]);
54725             }
54726         }
54727         return tiles;
54728     };
54729     /**
54730      * Remove an item from an array if it exists in array.
54731      *
54732      * @param {T} item - Item to remove.
54733      * @param {Array<T>} array - Array from which item should be removed.
54734      */
54735     TextureProvider.prototype._removeFromArray = function (item, array) {
54736         var index = array.indexOf(item);
54737         if (index !== -1) {
54738             array.splice(index, 1);
54739         }
54740     };
54741     /**
54742      * Remove an item from a dictionary.
54743      *
54744      * @param {string} key - Key of the item to remove.
54745      * @param {Object} dict - Dictionary from which item should be removed.
54746      */
54747     TextureProvider.prototype._removeFromDictionary = function (key, dict) {
54748         if (key in dict) {
54749             delete dict[key];
54750         }
54751     };
54752     /**
54753      * Render an image tile to the target texture.
54754      *
54755      * @param {number} x - The top left x pixel coordinate of the tile.
54756      * @param {number} y - The top left y pixel coordinate of the tile.
54757      * @param {number} w - The pixel width of the tile.
54758      * @param {number} h - The pixel height of the tile.
54759      * @param {HTMLImageElement} background - The image tile to render.
54760      */
54761     TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
54762         var texture = new THREE.Texture(image);
54763         texture.minFilter = THREE.LinearFilter;
54764         texture.needsUpdate = true;
54765         var geometry = new THREE.PlaneGeometry(w, h);
54766         var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
54767         var mesh = new THREE.Mesh(geometry, material);
54768         mesh.position.x = -this._width / 2 + x + w / 2;
54769         mesh.position.y = this._height / 2 - y - h / 2;
54770         var scene = new THREE.Scene();
54771         scene.add(mesh);
54772         this._renderer.render(scene, this._camera, this._renderTarget);
54773         this._renderer.setRenderTarget(undefined);
54774         scene.remove(mesh);
54775         geometry.dispose();
54776         material.dispose();
54777         texture.dispose();
54778     };
54779     /**
54780      * Mark a tile as rendered.
54781      *
54782      * @description Clears tiles marked as rendered in other
54783      * levels of the tile pyramid  if they were rendered on
54784      * top of or below the tile.
54785      *
54786      * @param {Arrary<number>} tile - The tile coordinates.
54787      * @param {number} level - Tile level of the tile coordinates.
54788      */
54789     TextureProvider.prototype._setTileRendered = function (tile, level) {
54790         var otherLevels = Object.keys(this._renderedTiles)
54791             .map(function (key) {
54792             return parseInt(key, 10);
54793         })
54794             .filter(function (renderedLevel) {
54795             return renderedLevel !== level;
54796         });
54797         for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
54798             var otherLevel = otherLevels_1[_i];
54799             var scale = Math.pow(2, otherLevel - level);
54800             if (otherLevel < level) {
54801                 var x = Math.floor(scale * tile[0]);
54802                 var y = Math.floor(scale * tile[1]);
54803                 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
54804                     var otherTile = _b[_a];
54805                     if (otherTile[0] === x && otherTile[1] === y) {
54806                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
54807                         this._renderedTiles[otherLevel].splice(index, 1);
54808                     }
54809                 }
54810             }
54811             else {
54812                 var startX = scale * tile[0];
54813                 var endX = startX + scale - 1;
54814                 var startY = scale * tile[1];
54815                 var endY = startY + scale - 1;
54816                 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
54817                     var otherTile = _d[_c];
54818                     if (otherTile[0] >= startX && otherTile[0] <= endX &&
54819                         otherTile[1] >= startY && otherTile[1] <= endY) {
54820                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
54821                         this._renderedTiles[otherLevel].splice(index, 1);
54822                     }
54823                 }
54824             }
54825             if (this._renderedTiles[otherLevel].length === 0) {
54826                 delete this._renderedTiles[otherLevel];
54827             }
54828         }
54829         this._renderedTiles[level].push(tile);
54830         this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
54831     };
54832     /**
54833      * Create a tile key from a tile coordinates.
54834      *
54835      * @description Tile keys are used as a hash for
54836      * storing the tile in a dictionary.
54837      *
54838      * @param {number} tileSize - The tile size.
54839      * @param {Arrary<number>} tile - The tile coordinates.
54840      */
54841     TextureProvider.prototype._tileKey = function (tileSize, tile) {
54842         return tileSize + "-" + tile[0] + "-" + tile[1];
54843     };
54844     return TextureProvider;
54845 }());
54846 exports.TextureProvider = TextureProvider;
54847 exports.default = TextureProvider;
54848
54849 },{"rxjs":43,"rxjs/operators":241,"three":242}],452:[function(require,module,exports){
54850 "use strict";
54851 Object.defineProperty(exports, "__esModule", { value: true });
54852 var DOM = /** @class */ (function () {
54853     function DOM(doc) {
54854         this._document = !!doc ? doc : document;
54855     }
54856     Object.defineProperty(DOM.prototype, "document", {
54857         get: function () {
54858             return this._document;
54859         },
54860         enumerable: true,
54861         configurable: true
54862     });
54863     DOM.prototype.createElement = function (tagName, className, container) {
54864         var element = this._document.createElement(tagName);
54865         if (!!className) {
54866             element.className = className;
54867         }
54868         if (!!container) {
54869             container.appendChild(element);
54870         }
54871         return element;
54872     };
54873     return DOM;
54874 }());
54875 exports.DOM = DOM;
54876 exports.default = DOM;
54877
54878 },{}],453:[function(require,module,exports){
54879 "use strict";
54880 Object.defineProperty(exports, "__esModule", { value: true });
54881 var EventEmitter = /** @class */ (function () {
54882     function EventEmitter() {
54883         this._events = {};
54884     }
54885     /**
54886      * Subscribe to an event by its name.
54887      * @param {string }eventType - The name of the event to subscribe to.
54888      * @param {any} fn - The handler called when the event occurs.
54889      */
54890     EventEmitter.prototype.on = function (eventType, fn) {
54891         this._events[eventType] = this._events[eventType] || [];
54892         this._events[eventType].push(fn);
54893         return;
54894     };
54895     /**
54896      * Unsubscribe from an event by its name.
54897      * @param {string} eventType - The name of the event to subscribe to.
54898      * @param {any} fn - The handler to remove.
54899      */
54900     EventEmitter.prototype.off = function (eventType, fn) {
54901         if (!eventType) {
54902             this._events = {};
54903             return;
54904         }
54905         if (!this._listens(eventType)) {
54906             var idx = this._events[eventType].indexOf(fn);
54907             if (idx >= 0) {
54908                 this._events[eventType].splice(idx, 1);
54909             }
54910             if (this._events[eventType].length) {
54911                 delete this._events[eventType];
54912             }
54913         }
54914         else {
54915             delete this._events[eventType];
54916         }
54917         return;
54918     };
54919     EventEmitter.prototype.fire = function (eventType, data) {
54920         if (!this._listens(eventType)) {
54921             return;
54922         }
54923         for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
54924             var fn = _a[_i];
54925             fn.call(this, data);
54926         }
54927         return;
54928     };
54929     EventEmitter.prototype._listens = function (eventType) {
54930         return !!(this._events && this._events[eventType]);
54931     };
54932     return EventEmitter;
54933 }());
54934 exports.EventEmitter = EventEmitter;
54935 exports.default = EventEmitter;
54936
54937 },{}],454:[function(require,module,exports){
54938 "use strict";
54939 Object.defineProperty(exports, "__esModule", { value: true });
54940 var Viewer_1 = require("../Viewer");
54941 var Settings = /** @class */ (function () {
54942     function Settings() {
54943     }
54944     Settings.setOptions = function (options) {
54945         Settings._baseImageSize = options.baseImageSize != null ?
54946             options.baseImageSize :
54947             Viewer_1.ImageSize.Size640;
54948         Settings._basePanoramaSize = options.basePanoramaSize != null ?
54949             options.basePanoramaSize :
54950             Viewer_1.ImageSize.Size2048;
54951         Settings._maxImageSize = options.maxImageSize != null ?
54952             options.maxImageSize :
54953             Viewer_1.ImageSize.Size2048;
54954     };
54955     Object.defineProperty(Settings, "baseImageSize", {
54956         get: function () {
54957             return Settings._baseImageSize;
54958         },
54959         enumerable: true,
54960         configurable: true
54961     });
54962     Object.defineProperty(Settings, "basePanoramaSize", {
54963         get: function () {
54964             return Settings._basePanoramaSize;
54965         },
54966         enumerable: true,
54967         configurable: true
54968     });
54969     Object.defineProperty(Settings, "maxImageSize", {
54970         get: function () {
54971             return Settings._maxImageSize;
54972         },
54973         enumerable: true,
54974         configurable: true
54975     });
54976     return Settings;
54977 }());
54978 exports.Settings = Settings;
54979 exports.default = Settings;
54980
54981 },{"../Viewer":302}],455:[function(require,module,exports){
54982 "use strict";
54983 Object.defineProperty(exports, "__esModule", { value: true });
54984 function isBrowser() {
54985     return typeof window !== "undefined" && typeof document !== "undefined";
54986 }
54987 exports.isBrowser = isBrowser;
54988 function isArraySupported() {
54989     return !!(Array.prototype &&
54990         Array.prototype.filter &&
54991         Array.prototype.indexOf &&
54992         Array.prototype.map &&
54993         Array.prototype.reverse);
54994 }
54995 exports.isArraySupported = isArraySupported;
54996 function isFunctionSupported() {
54997     return !!(Function.prototype && Function.prototype.bind);
54998 }
54999 exports.isFunctionSupported = isFunctionSupported;
55000 function isJSONSupported() {
55001     return "JSON" in window && "parse" in JSON && "stringify" in JSON;
55002 }
55003 exports.isJSONSupported = isJSONSupported;
55004 function isObjectSupported() {
55005     return !!(Object.keys &&
55006         Object.assign);
55007 }
55008 exports.isObjectSupported = isObjectSupported;
55009 function isBlobSupported() {
55010     return "Blob" in window && "URL" in window;
55011 }
55012 exports.isBlobSupported = isBlobSupported;
55013 var isWebGLSupportedCache = undefined;
55014 function isWebGLSupportedCached() {
55015     if (isWebGLSupportedCache === undefined) {
55016         isWebGLSupportedCache = isWebGLSupported();
55017     }
55018     return isWebGLSupportedCache;
55019 }
55020 exports.isWebGLSupportedCached = isWebGLSupportedCached;
55021 function isWebGLSupported() {
55022     var webGLContextAttributes = {
55023         alpha: false,
55024         antialias: false,
55025         depth: true,
55026         failIfMajorPerformanceCaveat: false,
55027         premultipliedAlpha: true,
55028         preserveDrawingBuffer: false,
55029         stencil: true,
55030     };
55031     var canvas = document.createElement("canvas");
55032     var context = canvas.getContext("webgl", webGLContextAttributes) ||
55033         canvas.getContext("experimental-webgl", webGLContextAttributes);
55034     if (!context) {
55035         return false;
55036     }
55037     var requiredExtensions = [
55038         "OES_standard_derivatives",
55039     ];
55040     var supportedExtensions = context.getSupportedExtensions();
55041     for (var _i = 0, requiredExtensions_1 = requiredExtensions; _i < requiredExtensions_1.length; _i++) {
55042         var requiredExtension = requiredExtensions_1[_i];
55043         if (supportedExtensions.indexOf(requiredExtension) === -1) {
55044             return false;
55045         }
55046     }
55047     return true;
55048 }
55049 exports.isWebGLSupported = isWebGLSupported;
55050
55051 },{}],456:[function(require,module,exports){
55052 "use strict";
55053 Object.defineProperty(exports, "__esModule", { value: true });
55054 var Urls = /** @class */ (function () {
55055     function Urls() {
55056     }
55057     Object.defineProperty(Urls, "explore", {
55058         get: function () {
55059             return Urls._scheme + "://" + Urls._exploreHost;
55060         },
55061         enumerable: true,
55062         configurable: true
55063     });
55064     Object.defineProperty(Urls, "origin", {
55065         get: function () {
55066             return Urls._origin;
55067         },
55068         enumerable: true,
55069         configurable: true
55070     });
55071     Object.defineProperty(Urls, "tileScheme", {
55072         get: function () {
55073             return Urls._scheme;
55074         },
55075         enumerable: true,
55076         configurable: true
55077     });
55078     Object.defineProperty(Urls, "tileDomain", {
55079         get: function () {
55080             return Urls._imageTileHost;
55081         },
55082         enumerable: true,
55083         configurable: true
55084     });
55085     Urls.clusterReconstruction = function (key) {
55086         return Urls._scheme + "://" + Urls._clusterReconstructionHost + "/" + key + "/v1.0/aligned.jsonz";
55087     };
55088     Urls.exporeImage = function (key) {
55089         return Urls._scheme + "://" + Urls._exploreHost + "/app/?pKey=" + key + "&focus=photo";
55090     };
55091     Urls.exporeUser = function (username) {
55092         return Urls._scheme + "://" + Urls._exploreHost + "/app/user/" + username;
55093     };
55094     Urls.falcorModel = function (clientId) {
55095         return Urls._scheme + "://" + Urls._apiHost + "/v3/model.json?client_id=" + clientId;
55096     };
55097     Urls.protoMesh = function (key) {
55098         return Urls._scheme + "://" + Urls._meshHost + "/v2/mesh/" + key;
55099     };
55100     Urls.thumbnail = function (key, size, origin) {
55101         var query = !!origin ? "?origin=" + origin : "";
55102         return Urls._scheme + "://" + Urls._imageHost + "/" + key + "/thumb-" + size + ".jpg" + query;
55103     };
55104     Urls.setOptions = function (options) {
55105         if (!options) {
55106             return;
55107         }
55108         if (!!options.apiHost) {
55109             Urls._apiHost = options.apiHost;
55110         }
55111         if (!!options.clusterReconstructionHost) {
55112             Urls._clusterReconstructionHost = options.clusterReconstructionHost;
55113         }
55114         if (!!options.exploreHost) {
55115             Urls._exploreHost = options.exploreHost;
55116         }
55117         if (!!options.imageHost) {
55118             Urls._imageHost = options.imageHost;
55119         }
55120         if (!!options.imageTileHost) {
55121             Urls._imageTileHost = options.imageTileHost;
55122         }
55123         if (!!options.meshHost) {
55124             Urls._meshHost = options.meshHost;
55125         }
55126         if (!!options.scheme) {
55127             Urls._scheme = options.scheme;
55128         }
55129     };
55130     Urls._apiHost = "a.mapillary.com";
55131     Urls._clusterReconstructionHost = "cluster-reconstructions.mapillary.com";
55132     Urls._exploreHost = "www.mapillary.com";
55133     Urls._imageHost = "images.mapillary.com";
55134     Urls._imageTileHost = "loris.mapillary.com";
55135     Urls._meshHost = "meshes.mapillary.com";
55136     Urls._origin = "mapillary.webgl";
55137     Urls._scheme = "https";
55138     return Urls;
55139 }());
55140 exports.Urls = Urls;
55141 exports.default = Urls;
55142
55143 },{}],457:[function(require,module,exports){
55144 "use strict";
55145 Object.defineProperty(exports, "__esModule", { value: true });
55146 /**
55147  * Enumeration for alignments
55148  * @enum {number}
55149  * @readonly
55150  */
55151 var Alignment;
55152 (function (Alignment) {
55153     /**
55154      * Align to bottom
55155      */
55156     Alignment[Alignment["Bottom"] = 0] = "Bottom";
55157     /**
55158      * Align to bottom left
55159      */
55160     Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft";
55161     /**
55162      * Align to bottom right
55163      */
55164     Alignment[Alignment["BottomRight"] = 2] = "BottomRight";
55165     /**
55166      * Align to center
55167      */
55168     Alignment[Alignment["Center"] = 3] = "Center";
55169     /**
55170      * Align to left
55171      */
55172     Alignment[Alignment["Left"] = 4] = "Left";
55173     /**
55174      * Align to right
55175      */
55176     Alignment[Alignment["Right"] = 5] = "Right";
55177     /**
55178      * Align to top
55179      */
55180     Alignment[Alignment["Top"] = 6] = "Top";
55181     /**
55182      * Align to top left
55183      */
55184     Alignment[Alignment["TopLeft"] = 7] = "TopLeft";
55185     /**
55186      * Align to top right
55187      */
55188     Alignment[Alignment["TopRight"] = 8] = "TopRight";
55189 })(Alignment = exports.Alignment || (exports.Alignment = {}));
55190 exports.default = Alignment;
55191
55192 },{}],458:[function(require,module,exports){
55193 "use strict";
55194 Object.defineProperty(exports, "__esModule", { value: true });
55195 var rxjs_1 = require("rxjs");
55196 var operators_1 = require("rxjs/operators");
55197 var Graph_1 = require("../Graph");
55198 var CacheService = /** @class */ (function () {
55199     function CacheService(graphService, stateService) {
55200         this._graphService = graphService;
55201         this._stateService = stateService;
55202         this._started = false;
55203     }
55204     Object.defineProperty(CacheService.prototype, "started", {
55205         get: function () {
55206             return this._started;
55207         },
55208         enumerable: true,
55209         configurable: true
55210     });
55211     CacheService.prototype.start = function () {
55212         var _this = this;
55213         if (this._started) {
55214             return;
55215         }
55216         this._uncacheSubscription = this._stateService.currentState$.pipe(operators_1.distinctUntilChanged(undefined, function (frame) {
55217             return frame.state.currentNode.key;
55218         }), operators_1.map(function (frame) {
55219             var trajectory = frame.state.trajectory;
55220             var trajectoryKeys = trajectory
55221                 .map(function (n) {
55222                 return n.key;
55223             });
55224             var sequenceKey = trajectory[trajectory.length - 1].sequenceKey;
55225             return [trajectoryKeys, sequenceKey];
55226         }), operators_1.bufferCount(1, 5), operators_1.withLatestFrom(this._graphService.graphMode$), operators_1.switchMap(function (_a) {
55227             var keepBuffer = _a[0], graphMode = _a[1];
55228             var keepKeys = keepBuffer[0][0];
55229             var keepSequenceKey = graphMode === Graph_1.GraphMode.Sequence ?
55230                 keepBuffer[0][1] : undefined;
55231             return _this._graphService.uncache$(keepKeys, keepSequenceKey);
55232         }))
55233             .subscribe(function () { });
55234         this._cacheNodeSubscription = this._graphService.graphMode$.pipe(operators_1.skip(1), operators_1.withLatestFrom(this._stateService.currentState$), operators_1.switchMap(function (_a) {
55235             var mode = _a[0], frame = _a[1];
55236             return mode === Graph_1.GraphMode.Sequence ?
55237                 _this._keyToEdges(frame.state.currentNode.key, function (node) {
55238                     return node.sequenceEdges$;
55239                 }) :
55240                 rxjs_1.from(frame.state.trajectory
55241                     .map(function (node) {
55242                     return node.key;
55243                 })
55244                     .slice(frame.state.currentIndex)).pipe(operators_1.mergeMap(function (key) {
55245                     return _this._keyToEdges(key, function (node) {
55246                         return node.spatialEdges$;
55247                     });
55248                 }, 6));
55249         }))
55250             .subscribe(function () { });
55251         this._started = true;
55252     };
55253     CacheService.prototype.stop = function () {
55254         if (!this._started) {
55255             return;
55256         }
55257         this._uncacheSubscription.unsubscribe();
55258         this._uncacheSubscription = null;
55259         this._cacheNodeSubscription.unsubscribe();
55260         this._cacheNodeSubscription = null;
55261         this._started = false;
55262     };
55263     CacheService.prototype._keyToEdges = function (key, nodeToEdgeMap) {
55264         return this._graphService.cacheNode$(key).pipe(operators_1.switchMap(nodeToEdgeMap), operators_1.first(function (status) {
55265             return status.cached;
55266         }), operators_1.timeout(15000), operators_1.catchError(function (error) {
55267             console.error("Failed to cache edges (" + key + ").", error);
55268             return rxjs_1.empty();
55269         }));
55270     };
55271     return CacheService;
55272 }());
55273 exports.CacheService = CacheService;
55274 exports.default = CacheService;
55275
55276 },{"../Graph":295,"rxjs":43,"rxjs/operators":241}],459:[function(require,module,exports){
55277 "use strict";
55278 Object.defineProperty(exports, "__esModule", { value: true });
55279 var operators_1 = require("rxjs/operators");
55280 var Component_1 = require("../Component");
55281 var ComponentController = /** @class */ (function () {
55282     function ComponentController(container, navigator, observer, key, options, componentService) {
55283         var _this = this;
55284         this._container = container;
55285         this._observer = observer;
55286         this._navigator = navigator;
55287         this._options = options != null ? options : {};
55288         this._key = key;
55289         this._navigable = key == null;
55290         this._componentService = !!componentService ?
55291             componentService :
55292             new Component_1.ComponentService(this._container, this._navigator);
55293         this._coverComponent = this._componentService.getCover();
55294         this._initializeComponents();
55295         if (key) {
55296             this._initilizeCoverComponent();
55297             this._subscribeCoverComponent();
55298         }
55299         else {
55300             this._navigator.movedToKey$.pipe(operators_1.first(function (k) {
55301                 return k != null;
55302             }))
55303                 .subscribe(function (k) {
55304                 _this._key = k;
55305                 _this._componentService.deactivateCover();
55306                 _this._coverComponent.configure({ key: _this._key, state: Component_1.CoverState.Hidden });
55307                 _this._subscribeCoverComponent();
55308                 _this._navigator.stateService.start();
55309                 _this._navigator.cacheService.start();
55310                 _this._navigator.panService.start();
55311                 _this._observer.startEmit();
55312             });
55313         }
55314     }
55315     Object.defineProperty(ComponentController.prototype, "navigable", {
55316         get: function () {
55317             return this._navigable;
55318         },
55319         enumerable: true,
55320         configurable: true
55321     });
55322     ComponentController.prototype.get = function (name) {
55323         return this._componentService.get(name);
55324     };
55325     ComponentController.prototype.activate = function (name) {
55326         this._componentService.activate(name);
55327     };
55328     ComponentController.prototype.activateCover = function () {
55329         this._coverComponent.configure({ state: Component_1.CoverState.Visible });
55330     };
55331     ComponentController.prototype.deactivate = function (name) {
55332         this._componentService.deactivate(name);
55333     };
55334     ComponentController.prototype.deactivateCover = function () {
55335         this._coverComponent.configure({ state: Component_1.CoverState.Loading });
55336     };
55337     ComponentController.prototype._initializeComponents = function () {
55338         var options = this._options;
55339         this._uFalse(options.background, "background");
55340         this._uFalse(options.debug, "debug");
55341         this._uFalse(options.image, "image");
55342         this._uFalse(options.marker, "marker");
55343         this._uFalse(options.navigation, "navigation");
55344         this._uFalse(options.popup, "popup");
55345         this._uFalse(options.route, "route");
55346         this._uFalse(options.slider, "slider");
55347         this._uFalse(options.spatialData, "spatialData");
55348         this._uFalse(options.tag, "tag");
55349         this._uTrue(options.attribution, "attribution");
55350         this._uTrue(options.bearing, "bearing");
55351         this._uTrue(options.cache, "cache");
55352         this._uTrue(options.direction, "direction");
55353         this._uTrue(options.imagePlane, "imagePlane");
55354         this._uTrue(options.keyboard, "keyboard");
55355         this._uTrue(options.loading, "loading");
55356         this._uTrue(options.mouse, "mouse");
55357         this._uTrue(options.sequence, "sequence");
55358         this._uTrue(options.stats, "stats");
55359         this._uTrue(options.zoom, "zoom");
55360     };
55361     ComponentController.prototype._initilizeCoverComponent = function () {
55362         var options = this._options;
55363         this._coverComponent.configure({ key: this._key });
55364         if (options.cover === undefined || options.cover) {
55365             this.activateCover();
55366         }
55367         else {
55368             this.deactivateCover();
55369         }
55370     };
55371     ComponentController.prototype._setNavigable = function (navigable) {
55372         if (this._navigable === navigable) {
55373             return;
55374         }
55375         this._navigable = navigable;
55376         this._observer.navigable$.next(navigable);
55377     };
55378     ComponentController.prototype._subscribeCoverComponent = function () {
55379         var _this = this;
55380         this._coverComponent.configuration$.pipe(operators_1.distinctUntilChanged(undefined, function (c) {
55381             return c.state;
55382         }))
55383             .subscribe(function (conf) {
55384             if (conf.state === Component_1.CoverState.Loading) {
55385                 _this._navigator.stateService.currentKey$.pipe(operators_1.first(), operators_1.switchMap(function (key) {
55386                     var keyChanged = key == null || key !== conf.key;
55387                     if (keyChanged) {
55388                         _this._setNavigable(false);
55389                     }
55390                     return keyChanged ?
55391                         _this._navigator.moveToKey$(conf.key) :
55392                         _this._navigator.stateService.currentNode$.pipe(operators_1.first());
55393                 }))
55394                     .subscribe(function () {
55395                     _this._navigator.stateService.start();
55396                     _this._navigator.cacheService.start();
55397                     _this._navigator.panService.start();
55398                     _this._observer.startEmit();
55399                     _this._coverComponent.configure({ state: Component_1.CoverState.Hidden });
55400                     _this._componentService.deactivateCover();
55401                     _this._setNavigable(true);
55402                 }, function (error) {
55403                     console.error("Failed to deactivate cover.", error);
55404                     _this._coverComponent.configure({ state: Component_1.CoverState.Visible });
55405                 });
55406             }
55407             else if (conf.state === Component_1.CoverState.Visible) {
55408                 _this._observer.stopEmit();
55409                 _this._navigator.stateService.stop();
55410                 _this._navigator.cacheService.stop();
55411                 _this._navigator.playService.stop();
55412                 _this._navigator.panService.stop();
55413                 _this._componentService.activateCover();
55414                 _this._setNavigable(conf.key == null);
55415             }
55416         });
55417     };
55418     ComponentController.prototype._uFalse = function (option, name) {
55419         if (option === undefined) {
55420             this._componentService.deactivate(name);
55421             return;
55422         }
55423         if (typeof option === "boolean") {
55424             if (option) {
55425                 this._componentService.activate(name);
55426             }
55427             else {
55428                 this._componentService.deactivate(name);
55429             }
55430             return;
55431         }
55432         this._componentService.configure(name, option);
55433         this._componentService.activate(name);
55434     };
55435     ComponentController.prototype._uTrue = function (option, name) {
55436         if (option === undefined) {
55437             this._componentService.activate(name);
55438             return;
55439         }
55440         if (typeof option === "boolean") {
55441             if (option) {
55442                 this._componentService.activate(name);
55443             }
55444             else {
55445                 this._componentService.deactivate(name);
55446             }
55447             return;
55448         }
55449         this._componentService.configure(name, option);
55450         this._componentService.activate(name);
55451     };
55452     return ComponentController;
55453 }());
55454 exports.ComponentController = ComponentController;
55455
55456 },{"../Component":291,"rxjs/operators":241}],460:[function(require,module,exports){
55457 "use strict";
55458 Object.defineProperty(exports, "__esModule", { value: true });
55459 var Render_1 = require("../Render");
55460 var Utils_1 = require("../Utils");
55461 var Viewer_1 = require("../Viewer");
55462 var Container = /** @class */ (function () {
55463     function Container(id, stateService, options, dom) {
55464         this.id = id;
55465         this._dom = !!dom ? dom : new Utils_1.DOM();
55466         this._container = this._dom.document.getElementById(id);
55467         if (!this._container) {
55468             throw new Error("Container '" + id + "' not found.");
55469         }
55470         this._container.classList.add("mapillary-js");
55471         this._canvasContainer = this._dom.createElement("div", "mapillary-js-interactive", this._container);
55472         this._domContainer = this._dom.createElement("div", "mapillary-js-dom", this._container);
55473         this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
55474         this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService, this._dom);
55475         this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$);
55476         this.keyboardService = new Viewer_1.KeyboardService(this._canvasContainer);
55477         this.mouseService = new Viewer_1.MouseService(this._container, this._canvasContainer, this._domContainer, document);
55478         this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer);
55479         this.spriteService = new Viewer_1.SpriteService(options.sprite);
55480     }
55481     Object.defineProperty(Container.prototype, "element", {
55482         get: function () {
55483             return this._container;
55484         },
55485         enumerable: true,
55486         configurable: true
55487     });
55488     Object.defineProperty(Container.prototype, "canvasContainer", {
55489         get: function () {
55490             return this._canvasContainer;
55491         },
55492         enumerable: true,
55493         configurable: true
55494     });
55495     Object.defineProperty(Container.prototype, "domContainer", {
55496         get: function () {
55497             return this._domContainer;
55498         },
55499         enumerable: true,
55500         configurable: true
55501     });
55502     return Container;
55503 }());
55504 exports.Container = Container;
55505 exports.default = Container;
55506
55507 },{"../Render":297,"../Utils":301,"../Viewer":302}],461:[function(require,module,exports){
55508 "use strict";
55509 Object.defineProperty(exports, "__esModule", { value: true });
55510 /**
55511  * Enumeration for image sizes
55512  * @enum {number}
55513  * @readonly
55514  * @description Image sizes in pixels for the long side of the image.
55515  */
55516 var ImageSize;
55517 (function (ImageSize) {
55518     /**
55519      * 320 pixels image size
55520      */
55521     ImageSize[ImageSize["Size320"] = 320] = "Size320";
55522     /**
55523      * 640 pixels image size
55524      */
55525     ImageSize[ImageSize["Size640"] = 640] = "Size640";
55526     /**
55527      * 1024 pixels image size
55528      */
55529     ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
55530     /**
55531      * 2048 pixels image size
55532      */
55533     ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
55534 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
55535
55536 },{}],462:[function(require,module,exports){
55537 "use strict";
55538 Object.defineProperty(exports, "__esModule", { value: true });
55539 var rxjs_1 = require("rxjs");
55540 var KeyboardService = /** @class */ (function () {
55541     function KeyboardService(canvasContainer) {
55542         this._keyDown$ = rxjs_1.fromEvent(canvasContainer, "keydown");
55543         this._keyUp$ = rxjs_1.fromEvent(canvasContainer, "keyup");
55544     }
55545     Object.defineProperty(KeyboardService.prototype, "keyDown$", {
55546         get: function () {
55547             return this._keyDown$;
55548         },
55549         enumerable: true,
55550         configurable: true
55551     });
55552     Object.defineProperty(KeyboardService.prototype, "keyUp$", {
55553         get: function () {
55554             return this._keyUp$;
55555         },
55556         enumerable: true,
55557         configurable: true
55558     });
55559     return KeyboardService;
55560 }());
55561 exports.KeyboardService = KeyboardService;
55562 exports.default = KeyboardService;
55563
55564 },{"rxjs":43}],463:[function(require,module,exports){
55565 "use strict";
55566 Object.defineProperty(exports, "__esModule", { value: true });
55567 var operators_1 = require("rxjs/operators");
55568 var rxjs_1 = require("rxjs");
55569 var LoadingService = /** @class */ (function () {
55570     function LoadingService() {
55571         this._loadersSubject$ = new rxjs_1.Subject();
55572         this._loaders$ = this._loadersSubject$.pipe(operators_1.scan(function (loaders, loader) {
55573             if (loader.task !== undefined) {
55574                 loaders[loader.task] = loader.loading;
55575             }
55576             return loaders;
55577         }, {}), operators_1.startWith({}), operators_1.publishReplay(1), operators_1.refCount());
55578     }
55579     Object.defineProperty(LoadingService.prototype, "loading$", {
55580         get: function () {
55581             return this._loaders$.pipe(operators_1.map(function (loaders) {
55582                 for (var key in loaders) {
55583                     if (!loaders.hasOwnProperty(key)) {
55584                         continue;
55585                     }
55586                     if (loaders[key]) {
55587                         return true;
55588                     }
55589                 }
55590                 return false;
55591             }), operators_1.debounceTime(100), operators_1.distinctUntilChanged());
55592         },
55593         enumerable: true,
55594         configurable: true
55595     });
55596     LoadingService.prototype.taskLoading$ = function (task) {
55597         return this._loaders$.pipe(operators_1.map(function (loaders) {
55598             return !!loaders[task];
55599         }), operators_1.debounceTime(100), operators_1.distinctUntilChanged());
55600     };
55601     LoadingService.prototype.startLoading = function (task) {
55602         this._loadersSubject$.next({ loading: true, task: task });
55603     };
55604     LoadingService.prototype.stopLoading = function (task) {
55605         this._loadersSubject$.next({ loading: false, task: task });
55606     };
55607     return LoadingService;
55608 }());
55609 exports.LoadingService = LoadingService;
55610 exports.default = LoadingService;
55611
55612 },{"rxjs":43,"rxjs/operators":241}],464:[function(require,module,exports){
55613 "use strict";
55614 Object.defineProperty(exports, "__esModule", { value: true });
55615 var rxjs_1 = require("rxjs");
55616 var operators_1 = require("rxjs/operators");
55617 var MouseService = /** @class */ (function () {
55618     function MouseService(container, canvasContainer, domContainer, doc) {
55619         var _this = this;
55620         this._activeSubject$ = new rxjs_1.BehaviorSubject(false);
55621         this._active$ = this._activeSubject$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
55622         this._claimMouse$ = new rxjs_1.Subject();
55623         this._claimWheel$ = new rxjs_1.Subject();
55624         this._deferPixelClaims$ = new rxjs_1.Subject();
55625         this._deferPixels$ = this._deferPixelClaims$.pipe(operators_1.scan(function (claims, claim) {
55626             if (claim.deferPixels == null) {
55627                 delete claims[claim.name];
55628             }
55629             else {
55630                 claims[claim.name] = claim.deferPixels;
55631             }
55632             return claims;
55633         }, {}), operators_1.map(function (claims) {
55634             var deferPixelMax = -1;
55635             for (var key in claims) {
55636                 if (!claims.hasOwnProperty(key)) {
55637                     continue;
55638                 }
55639                 var deferPixels = claims[key];
55640                 if (deferPixels > deferPixelMax) {
55641                     deferPixelMax = deferPixels;
55642                 }
55643             }
55644             return deferPixelMax;
55645         }), operators_1.startWith(-1), operators_1.publishReplay(1), operators_1.refCount());
55646         this._deferPixels$.subscribe(function () { });
55647         this._documentMouseMove$ = rxjs_1.fromEvent(doc, "mousemove");
55648         this._documentMouseUp$ = rxjs_1.fromEvent(doc, "mouseup");
55649         this._mouseDown$ = rxjs_1.fromEvent(canvasContainer, "mousedown");
55650         this._mouseLeave$ = rxjs_1.fromEvent(canvasContainer, "mouseleave");
55651         this._mouseMove$ = rxjs_1.fromEvent(canvasContainer, "mousemove");
55652         this._mouseUp$ = rxjs_1.fromEvent(canvasContainer, "mouseup");
55653         this._mouseOut$ = rxjs_1.fromEvent(canvasContainer, "mouseout");
55654         this._mouseOver$ = rxjs_1.fromEvent(canvasContainer, "mouseover");
55655         this._domMouseDown$ = rxjs_1.fromEvent(domContainer, "mousedown");
55656         this._domMouseMove$ = rxjs_1.fromEvent(domContainer, "mousemove");
55657         this._click$ = rxjs_1.fromEvent(canvasContainer, "click");
55658         this._contextMenu$ = rxjs_1.fromEvent(canvasContainer, "contextmenu");
55659         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) {
55660             var event1 = events[0];
55661             var event2 = events[1];
55662             var event3 = events[2];
55663             return event1.type === "click" &&
55664                 event2.type === "click" &&
55665                 event3.type === "dblclick" &&
55666                 event1.target.parentNode === canvasContainer &&
55667                 event2.target.parentNode === canvasContainer;
55668         }), operators_1.map(function (events) {
55669             return events[2];
55670         }), operators_1.share());
55671         rxjs_1.merge(this._domMouseDown$, this._domMouseMove$, this._dblClick$, this._contextMenu$)
55672             .subscribe(function (event) {
55673             event.preventDefault();
55674         });
55675         this._mouseWheel$ = rxjs_1.merge(rxjs_1.fromEvent(canvasContainer, "wheel"), rxjs_1.fromEvent(domContainer, "wheel")).pipe(operators_1.share());
55676         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) {
55677             // fire context menu on mouse up both on mac and windows
55678             return events[0].type === "mousedown" &&
55679                 events[1].type === "contextmenu" &&
55680                 events[2].type === "mouseup";
55681         }), operators_1.map(function (events) {
55682             return events[1];
55683         }), operators_1.share());
55684         var dragStop$ = rxjs_1.merge(rxjs_1.fromEvent(window, "blur"), this._documentMouseUp$.pipe(operators_1.filter(function (e) {
55685             return e.button === 0;
55686         }))).pipe(operators_1.share());
55687         var mouseDragInitiate$ = this._createMouseDragInitiate$(this._mouseDown$, dragStop$, true).pipe(operators_1.share());
55688         this._mouseDragStart$ = this._createMouseDragStart$(mouseDragInitiate$).pipe(operators_1.share());
55689         this._mouseDrag$ = this._createMouseDrag$(mouseDragInitiate$, dragStop$).pipe(operators_1.share());
55690         this._mouseDragEnd$ = this._createMouseDragEnd$(this._mouseDragStart$, dragStop$).pipe(operators_1.share());
55691         var domMouseDragInitiate$ = this._createMouseDragInitiate$(this._domMouseDown$, dragStop$, false).pipe(operators_1.share());
55692         this._domMouseDragStart$ = this._createMouseDragStart$(domMouseDragInitiate$).pipe(operators_1.share());
55693         this._domMouseDrag$ = this._createMouseDrag$(domMouseDragInitiate$, dragStop$).pipe(operators_1.share());
55694         this._domMouseDragEnd$ = this._createMouseDragEnd$(this._domMouseDragStart$, dragStop$).pipe(operators_1.share());
55695         this._proximateClick$ = this._mouseDown$.pipe(operators_1.switchMap(function (mouseDown) {
55696             return _this._click$.pipe(operators_1.takeUntil(_this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$)), operators_1.take(1));
55697         }), operators_1.share());
55698         this._staticClick$ = this._mouseDown$.pipe(operators_1.switchMap(function (e) {
55699             return _this._click$.pipe(operators_1.takeUntil(_this._documentMouseMove$), operators_1.take(1));
55700         }), operators_1.share());
55701         this._mouseDragStart$.subscribe();
55702         this._mouseDrag$.subscribe();
55703         this._mouseDragEnd$.subscribe();
55704         this._domMouseDragStart$.subscribe();
55705         this._domMouseDrag$.subscribe();
55706         this._domMouseDragEnd$.subscribe();
55707         this._staticClick$.subscribe();
55708         this._mouseOwner$ = this._createOwner$(this._claimMouse$).pipe(operators_1.publishReplay(1), operators_1.refCount());
55709         this._wheelOwner$ = this._createOwner$(this._claimWheel$).pipe(operators_1.publishReplay(1), operators_1.refCount());
55710         this._mouseOwner$.subscribe(function () { });
55711         this._wheelOwner$.subscribe(function () { });
55712     }
55713     Object.defineProperty(MouseService.prototype, "active$", {
55714         get: function () {
55715             return this._active$;
55716         },
55717         enumerable: true,
55718         configurable: true
55719     });
55720     Object.defineProperty(MouseService.prototype, "activate$", {
55721         get: function () {
55722             return this._activeSubject$;
55723         },
55724         enumerable: true,
55725         configurable: true
55726     });
55727     Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
55728         get: function () {
55729             return this._documentMouseMove$;
55730         },
55731         enumerable: true,
55732         configurable: true
55733     });
55734     Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
55735         get: function () {
55736             return this._documentMouseUp$;
55737         },
55738         enumerable: true,
55739         configurable: true
55740     });
55741     Object.defineProperty(MouseService.prototype, "domMouseDragStart$", {
55742         get: function () {
55743             return this._domMouseDragStart$;
55744         },
55745         enumerable: true,
55746         configurable: true
55747     });
55748     Object.defineProperty(MouseService.prototype, "domMouseDrag$", {
55749         get: function () {
55750             return this._domMouseDrag$;
55751         },
55752         enumerable: true,
55753         configurable: true
55754     });
55755     Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", {
55756         get: function () {
55757             return this._domMouseDragEnd$;
55758         },
55759         enumerable: true,
55760         configurable: true
55761     });
55762     Object.defineProperty(MouseService.prototype, "domMouseDown$", {
55763         get: function () {
55764             return this._domMouseDown$;
55765         },
55766         enumerable: true,
55767         configurable: true
55768     });
55769     Object.defineProperty(MouseService.prototype, "domMouseMove$", {
55770         get: function () {
55771             return this._domMouseMove$;
55772         },
55773         enumerable: true,
55774         configurable: true
55775     });
55776     Object.defineProperty(MouseService.prototype, "mouseOwner$", {
55777         get: function () {
55778             return this._mouseOwner$;
55779         },
55780         enumerable: true,
55781         configurable: true
55782     });
55783     Object.defineProperty(MouseService.prototype, "mouseDown$", {
55784         get: function () {
55785             return this._mouseDown$;
55786         },
55787         enumerable: true,
55788         configurable: true
55789     });
55790     Object.defineProperty(MouseService.prototype, "mouseMove$", {
55791         get: function () {
55792             return this._mouseMove$;
55793         },
55794         enumerable: true,
55795         configurable: true
55796     });
55797     Object.defineProperty(MouseService.prototype, "mouseLeave$", {
55798         get: function () {
55799             return this._mouseLeave$;
55800         },
55801         enumerable: true,
55802         configurable: true
55803     });
55804     Object.defineProperty(MouseService.prototype, "mouseOut$", {
55805         get: function () {
55806             return this._mouseOut$;
55807         },
55808         enumerable: true,
55809         configurable: true
55810     });
55811     Object.defineProperty(MouseService.prototype, "mouseOver$", {
55812         get: function () {
55813             return this._mouseOver$;
55814         },
55815         enumerable: true,
55816         configurable: true
55817     });
55818     Object.defineProperty(MouseService.prototype, "mouseUp$", {
55819         get: function () {
55820             return this._mouseUp$;
55821         },
55822         enumerable: true,
55823         configurable: true
55824     });
55825     Object.defineProperty(MouseService.prototype, "click$", {
55826         get: function () {
55827             return this._click$;
55828         },
55829         enumerable: true,
55830         configurable: true
55831     });
55832     Object.defineProperty(MouseService.prototype, "dblClick$", {
55833         get: function () {
55834             return this._dblClick$;
55835         },
55836         enumerable: true,
55837         configurable: true
55838     });
55839     Object.defineProperty(MouseService.prototype, "contextMenu$", {
55840         get: function () {
55841             return this._consistentContextMenu$;
55842         },
55843         enumerable: true,
55844         configurable: true
55845     });
55846     Object.defineProperty(MouseService.prototype, "mouseWheel$", {
55847         get: function () {
55848             return this._mouseWheel$;
55849         },
55850         enumerable: true,
55851         configurable: true
55852     });
55853     Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
55854         get: function () {
55855             return this._mouseDragStart$;
55856         },
55857         enumerable: true,
55858         configurable: true
55859     });
55860     Object.defineProperty(MouseService.prototype, "mouseDrag$", {
55861         get: function () {
55862             return this._mouseDrag$;
55863         },
55864         enumerable: true,
55865         configurable: true
55866     });
55867     Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
55868         get: function () {
55869             return this._mouseDragEnd$;
55870         },
55871         enumerable: true,
55872         configurable: true
55873     });
55874     Object.defineProperty(MouseService.prototype, "proximateClick$", {
55875         get: function () {
55876             return this._proximateClick$;
55877         },
55878         enumerable: true,
55879         configurable: true
55880     });
55881     Object.defineProperty(MouseService.prototype, "staticClick$", {
55882         get: function () {
55883             return this._staticClick$;
55884         },
55885         enumerable: true,
55886         configurable: true
55887     });
55888     MouseService.prototype.claimMouse = function (name, zindex) {
55889         this._claimMouse$.next({ name: name, zindex: zindex });
55890     };
55891     MouseService.prototype.unclaimMouse = function (name) {
55892         this._claimMouse$.next({ name: name, zindex: null });
55893     };
55894     MouseService.prototype.deferPixels = function (name, deferPixels) {
55895         this._deferPixelClaims$.next({ name: name, deferPixels: deferPixels });
55896     };
55897     MouseService.prototype.undeferPixels = function (name) {
55898         this._deferPixelClaims$.next({ name: name, deferPixels: null });
55899     };
55900     MouseService.prototype.claimWheel = function (name, zindex) {
55901         this._claimWheel$.next({ name: name, zindex: zindex });
55902     };
55903     MouseService.prototype.unclaimWheel = function (name) {
55904         this._claimWheel$.next({ name: name, zindex: null });
55905     };
55906     MouseService.prototype.filtered$ = function (name, observable$) {
55907         return this._filtered(name, observable$, this._mouseOwner$);
55908     };
55909     MouseService.prototype.filteredWheel$ = function (name, observable$) {
55910         return this._filtered(name, observable$, this._wheelOwner$);
55911     };
55912     MouseService.prototype._createDeferredMouseMove$ = function (origin, mouseMove$) {
55913         return mouseMove$.pipe(operators_1.map(function (mouseMove) {
55914             var deltaX = mouseMove.clientX - origin.clientX;
55915             var deltaY = mouseMove.clientY - origin.clientY;
55916             return [mouseMove, Math.sqrt(deltaX * deltaX + deltaY * deltaY)];
55917         }), operators_1.withLatestFrom(this._deferPixels$), operators_1.filter(function (_a) {
55918             var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
55919             return delta > deferPixels;
55920         }), operators_1.map(function (_a) {
55921             var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
55922             return mouseMove;
55923         }));
55924     };
55925     MouseService.prototype._createMouseDrag$ = function (mouseDragStartInitiate$, stop$) {
55926         var _this = this;
55927         return mouseDragStartInitiate$.pipe(operators_1.map(function (_a) {
55928             var mouseDown = _a[0], mouseMove = _a[1];
55929             return mouseMove;
55930         }), operators_1.switchMap(function (mouseMove) {
55931             return rxjs_1.concat(rxjs_1.of(mouseMove), _this._documentMouseMove$).pipe(operators_1.takeUntil(stop$));
55932         }));
55933     };
55934     MouseService.prototype._createMouseDragEnd$ = function (mouseDragStart$, stop$) {
55935         return mouseDragStart$.pipe(operators_1.switchMap(function (event) {
55936             return stop$.pipe(operators_1.first());
55937         }));
55938     };
55939     MouseService.prototype._createMouseDragStart$ = function (mouseDragStartInitiate$) {
55940         return mouseDragStartInitiate$.pipe(operators_1.map(function (_a) {
55941             var mouseDown = _a[0], mouseMove = _a[1];
55942             return mouseDown;
55943         }));
55944     };
55945     MouseService.prototype._createMouseDragInitiate$ = function (mouseDown$, stop$, defer) {
55946         var _this = this;
55947         return mouseDown$.pipe(operators_1.filter(function (mouseDown) {
55948             return mouseDown.button === 0;
55949         }), operators_1.switchMap(function (mouseDown) {
55950             return rxjs_1.combineLatest(rxjs_1.of(mouseDown), defer ?
55951                 _this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$) :
55952                 _this._documentMouseMove$).pipe(operators_1.takeUntil(stop$), operators_1.take(1));
55953         }));
55954     };
55955     MouseService.prototype._createOwner$ = function (claim$) {
55956         return claim$.pipe(operators_1.scan(function (claims, claim) {
55957             if (claim.zindex == null) {
55958                 delete claims[claim.name];
55959             }
55960             else {
55961                 claims[claim.name] = claim.zindex;
55962             }
55963             return claims;
55964         }, {}), operators_1.map(function (claims) {
55965             var owner = null;
55966             var zIndexMax = -1;
55967             for (var name_1 in claims) {
55968                 if (!claims.hasOwnProperty(name_1)) {
55969                     continue;
55970                 }
55971                 if (claims[name_1] > zIndexMax) {
55972                     zIndexMax = claims[name_1];
55973                     owner = name_1;
55974                 }
55975             }
55976             return owner;
55977         }), operators_1.startWith(null));
55978     };
55979     MouseService.prototype._filtered = function (name, observable$, owner$) {
55980         return observable$.pipe(operators_1.withLatestFrom(owner$), operators_1.filter(function (_a) {
55981             var item = _a[0], owner = _a[1];
55982             return owner === name;
55983         }), operators_1.map(function (_a) {
55984             var item = _a[0], owner = _a[1];
55985             return item;
55986         }));
55987     };
55988     return MouseService;
55989 }());
55990 exports.MouseService = MouseService;
55991 exports.default = MouseService;
55992
55993 },{"rxjs":43,"rxjs/operators":241}],465:[function(require,module,exports){
55994 "use strict";
55995 Object.defineProperty(exports, "__esModule", { value: true });
55996 var rxjs_1 = require("rxjs");
55997 var operators_1 = require("rxjs/operators");
55998 var API_1 = require("../API");
55999 var Graph_1 = require("../Graph");
56000 var Edge_1 = require("../Edge");
56001 var Error_1 = require("../Error");
56002 var State_1 = require("../State");
56003 var Viewer_1 = require("../Viewer");
56004 var PanService_1 = require("./PanService");
56005 var Navigator = /** @class */ (function () {
56006     function Navigator(clientId, options, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService, playService, panService) {
56007         this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
56008         this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
56009         this._graphService = graphService != null ?
56010             graphService :
56011             new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
56012         this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
56013         this._loadingName = "navigator";
56014         this._stateService = stateService != null ? stateService : new State_1.StateService(options.transitionMode);
56015         this._cacheService = cacheService != null ?
56016             cacheService :
56017             new Viewer_1.CacheService(this._graphService, this._stateService);
56018         this._playService = playService != null ?
56019             playService :
56020             new Viewer_1.PlayService(this._graphService, this._stateService);
56021         this._panService = panService != null ?
56022             panService :
56023             new PanService_1.PanService(this._graphService, this._stateService, options.combinedPanning);
56024         this._keyRequested$ = new rxjs_1.BehaviorSubject(null);
56025         this._movedToKey$ = new rxjs_1.BehaviorSubject(null);
56026         this._request$ = null;
56027         this._requestSubscription = null;
56028         this._nodeRequestSubscription = null;
56029     }
56030     Object.defineProperty(Navigator.prototype, "apiV3", {
56031         get: function () {
56032             return this._apiV3;
56033         },
56034         enumerable: true,
56035         configurable: true
56036     });
56037     Object.defineProperty(Navigator.prototype, "cacheService", {
56038         get: function () {
56039             return this._cacheService;
56040         },
56041         enumerable: true,
56042         configurable: true
56043     });
56044     Object.defineProperty(Navigator.prototype, "graphService", {
56045         get: function () {
56046             return this._graphService;
56047         },
56048         enumerable: true,
56049         configurable: true
56050     });
56051     Object.defineProperty(Navigator.prototype, "imageLoadingService", {
56052         get: function () {
56053             return this._imageLoadingService;
56054         },
56055         enumerable: true,
56056         configurable: true
56057     });
56058     Object.defineProperty(Navigator.prototype, "loadingService", {
56059         get: function () {
56060             return this._loadingService;
56061         },
56062         enumerable: true,
56063         configurable: true
56064     });
56065     Object.defineProperty(Navigator.prototype, "movedToKey$", {
56066         get: function () {
56067             return this._movedToKey$;
56068         },
56069         enumerable: true,
56070         configurable: true
56071     });
56072     Object.defineProperty(Navigator.prototype, "panService", {
56073         get: function () {
56074             return this._panService;
56075         },
56076         enumerable: true,
56077         configurable: true
56078     });
56079     Object.defineProperty(Navigator.prototype, "playService", {
56080         get: function () {
56081             return this._playService;
56082         },
56083         enumerable: true,
56084         configurable: true
56085     });
56086     Object.defineProperty(Navigator.prototype, "stateService", {
56087         get: function () {
56088             return this._stateService;
56089         },
56090         enumerable: true,
56091         configurable: true
56092     });
56093     Navigator.prototype.moveToKey$ = function (key) {
56094         this._abortRequest("to key " + key);
56095         this._loadingService.startLoading(this._loadingName);
56096         var node$ = this._moveToKey$(key);
56097         return this._makeRequest$(node$);
56098     };
56099     Navigator.prototype.moveDir$ = function (direction) {
56100         var _this = this;
56101         this._abortRequest("in dir " + Edge_1.EdgeDirection[direction]);
56102         this._loadingService.startLoading(this._loadingName);
56103         var node$ = this.stateService.currentNode$.pipe(operators_1.first(), operators_1.mergeMap(function (node) {
56104             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
56105                 node.sequenceEdges$ :
56106                 node.spatialEdges$).pipe(operators_1.first(), operators_1.map(function (status) {
56107                 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
56108                     var edge = _a[_i];
56109                     if (edge.data.direction === direction) {
56110                         return edge.to;
56111                     }
56112                 }
56113                 return null;
56114             }));
56115         }), operators_1.mergeMap(function (directionKey) {
56116             if (directionKey == null) {
56117                 _this._loadingService.stopLoading(_this._loadingName);
56118                 return rxjs_1.throwError(new Error("Direction (" + direction + ") does not exist for current node."));
56119             }
56120             return _this._moveToKey$(directionKey);
56121         }));
56122         return this._makeRequest$(node$);
56123     };
56124     Navigator.prototype.moveCloseTo$ = function (lat, lon) {
56125         var _this = this;
56126         this._abortRequest("to lat " + lat + ", lon " + lon);
56127         this._loadingService.startLoading(this._loadingName);
56128         var node$ = this.apiV3.imageCloseTo$(lat, lon).pipe(operators_1.mergeMap(function (fullNode) {
56129             if (fullNode == null) {
56130                 _this._loadingService.stopLoading(_this._loadingName);
56131                 return rxjs_1.throwError(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
56132             }
56133             return _this._moveToKey$(fullNode.key);
56134         }));
56135         return this._makeRequest$(node$);
56136     };
56137     Navigator.prototype.setFilter$ = function (filter) {
56138         var _this = this;
56139         this._stateService.clearNodes();
56140         return this._movedToKey$.pipe(operators_1.first(), operators_1.mergeMap(function (key) {
56141             if (key != null) {
56142                 return _this._trajectoryKeys$().pipe(operators_1.mergeMap(function (keys) {
56143                     return _this._graphService.setFilter$(filter).pipe(operators_1.mergeMap(function () {
56144                         return _this._cacheKeys$(keys);
56145                     }));
56146                 }), operators_1.last());
56147             }
56148             return _this._keyRequested$.pipe(operators_1.first(), operators_1.mergeMap(function (requestedKey) {
56149                 if (requestedKey != null) {
56150                     return _this._graphService.setFilter$(filter).pipe(operators_1.mergeMap(function () {
56151                         return _this._graphService.cacheNode$(requestedKey);
56152                     }));
56153                 }
56154                 return _this._graphService.setFilter$(filter).pipe(operators_1.map(function () {
56155                     return undefined;
56156                 }));
56157             }));
56158         }), operators_1.map(function (node) {
56159             return undefined;
56160         }));
56161     };
56162     Navigator.prototype.setToken$ = function (token) {
56163         var _this = this;
56164         this._abortRequest("to set token");
56165         this._stateService.clearNodes();
56166         return this._movedToKey$.pipe(operators_1.first(), operators_1.tap(function (key) {
56167             _this._apiV3.setToken(token);
56168         }), operators_1.mergeMap(function (key) {
56169             return key == null ?
56170                 _this._graphService.reset$([]) :
56171                 _this._trajectoryKeys$().pipe(operators_1.mergeMap(function (keys) {
56172                     return _this._graphService.reset$(keys).pipe(operators_1.mergeMap(function () {
56173                         return _this._cacheKeys$(keys);
56174                     }));
56175                 }), operators_1.last(), operators_1.map(function (node) {
56176                     return undefined;
56177                 }));
56178         }));
56179     };
56180     Navigator.prototype._cacheKeys$ = function (keys) {
56181         var _this = this;
56182         var cacheNodes$ = keys
56183             .map(function (key) {
56184             return _this._graphService.cacheNode$(key);
56185         });
56186         return rxjs_1.from(cacheNodes$).pipe(operators_1.mergeAll());
56187     };
56188     Navigator.prototype._abortRequest = function (reason) {
56189         if (this._requestSubscription != null) {
56190             this._requestSubscription.unsubscribe();
56191             this._requestSubscription = null;
56192         }
56193         if (this._nodeRequestSubscription != null) {
56194             this._nodeRequestSubscription.unsubscribe();
56195             this._nodeRequestSubscription = null;
56196         }
56197         if (this._request$ != null) {
56198             if (!(this._request$.isStopped || this._request$.hasError)) {
56199                 this._request$.error(new Error_1.AbortMapillaryError("Request aborted by a subsequent request " + reason + "."));
56200             }
56201             this._request$ = null;
56202         }
56203     };
56204     Navigator.prototype._makeRequest$ = function (node$) {
56205         var _this = this;
56206         var request$ = new rxjs_1.ReplaySubject(1);
56207         this._requestSubscription = request$
56208             .subscribe(undefined, function () { });
56209         this._request$ = request$;
56210         this._nodeRequestSubscription = node$
56211             .subscribe(function (node) {
56212             _this._request$ = null;
56213             request$.next(node);
56214             request$.complete();
56215         }, function (error) {
56216             _this._request$ = null;
56217             request$.error(error);
56218         });
56219         return request$;
56220     };
56221     Navigator.prototype._moveToKey$ = function (key) {
56222         var _this = this;
56223         this._keyRequested$.next(key);
56224         return this._graphService.cacheNode$(key).pipe(operators_1.tap(function (node) {
56225             _this._stateService.setNodes([node]);
56226             _this._movedToKey$.next(node.key);
56227         }), operators_1.finalize(function () {
56228             _this._loadingService.stopLoading(_this._loadingName);
56229         }));
56230     };
56231     Navigator.prototype._trajectoryKeys$ = function () {
56232         return this._stateService.currentState$.pipe(operators_1.first(), operators_1.map(function (frame) {
56233             return frame.state.trajectory
56234                 .map(function (node) {
56235                 return node.key;
56236             });
56237         }));
56238     };
56239     return Navigator;
56240 }());
56241 exports.Navigator = Navigator;
56242 exports.default = Navigator;
56243
56244 },{"../API":290,"../Edge":292,"../Error":293,"../Graph":295,"../State":298,"../Viewer":302,"./PanService":467,"rxjs":43,"rxjs/operators":241}],466:[function(require,module,exports){
56245 "use strict";
56246 Object.defineProperty(exports, "__esModule", { value: true });
56247 var rxjs_1 = require("rxjs");
56248 var operators_1 = require("rxjs/operators");
56249 var Viewer_1 = require("../Viewer");
56250 var Observer = /** @class */ (function () {
56251     function Observer(eventEmitter, navigator, container) {
56252         var _this = this;
56253         this._container = container;
56254         this._eventEmitter = eventEmitter;
56255         this._navigator = navigator;
56256         this._projection = new Viewer_1.Projection();
56257         this._started = false;
56258         this._navigable$ = new rxjs_1.Subject();
56259         // navigable and loading should always emit, also when cover is activated.
56260         this._navigable$
56261             .subscribe(function (navigable) {
56262             _this._eventEmitter.fire(Viewer_1.Viewer.navigablechanged, navigable);
56263         });
56264         this._navigator.loadingService.loading$
56265             .subscribe(function (loading) {
56266             _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
56267         });
56268     }
56269     Object.defineProperty(Observer.prototype, "started", {
56270         get: function () {
56271             return this._started;
56272         },
56273         enumerable: true,
56274         configurable: true
56275     });
56276     Object.defineProperty(Observer.prototype, "navigable$", {
56277         get: function () {
56278             return this._navigable$;
56279         },
56280         enumerable: true,
56281         configurable: true
56282     });
56283     Object.defineProperty(Observer.prototype, "projection", {
56284         get: function () {
56285             return this._projection;
56286         },
56287         enumerable: true,
56288         configurable: true
56289     });
56290     Observer.prototype.project$ = function (latLon) {
56291         var _this = this;
56292         return rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentNode$, this._navigator.stateService.reference$).pipe(operators_1.first(), operators_1.map(function (_a) {
56293             var render = _a[0], node = _a[1], reference = _a[2];
56294             if (_this._projection.distanceBetweenLatLons(latLon, node.latLon) > 1000) {
56295                 return null;
56296             }
56297             var canvasPoint = _this._projection.latLonToCanvas(latLon, _this._container.element, render, reference);
56298             return !!canvasPoint ?
56299                 [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])] :
56300                 null;
56301         }));
56302     };
56303     Observer.prototype.projectBasic$ = function (basicPoint) {
56304         var _this = this;
56305         return rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$).pipe(operators_1.first(), operators_1.map(function (_a) {
56306             var render = _a[0], transform = _a[1];
56307             var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform);
56308             return !!canvasPoint ?
56309                 [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])] :
56310                 null;
56311         }));
56312     };
56313     Observer.prototype.startEmit = function () {
56314         var _this = this;
56315         if (this._started) {
56316             return;
56317         }
56318         this._started = true;
56319         this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
56320             .subscribe(function (node) {
56321             _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
56322         });
56323         this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$.pipe(operators_1.switchMap(function (node) {
56324             return node.sequenceEdges$;
56325         }))
56326             .subscribe(function (status) {
56327             _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
56328         });
56329         this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$.pipe(operators_1.switchMap(function (node) {
56330             return node.spatialEdges$;
56331         }))
56332             .subscribe(function (status) {
56333             _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
56334         });
56335         this._moveSubscription = rxjs_1.combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$).pipe(operators_1.map(function (values) {
56336             return values[0] || values[1] || values[2];
56337         }), operators_1.distinctUntilChanged())
56338             .subscribe(function (started) {
56339             if (started) {
56340                 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
56341             }
56342             else {
56343                 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
56344             }
56345         });
56346         this._bearingSubscription = this._container.renderService.bearing$.pipe(operators_1.auditTime(100), operators_1.distinctUntilChanged(function (b1, b2) {
56347             return Math.abs(b2 - b1) < 1;
56348         }))
56349             .subscribe(function (bearing) {
56350             _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
56351         });
56352         var mouseMove$ = this._container.mouseService.active$.pipe(operators_1.switchMap(function (active) {
56353             return active ?
56354                 rxjs_1.empty() :
56355                 _this._container.mouseService.mouseMove$;
56356         }));
56357         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) {
56358             var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
56359             var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform);
56360             return {
56361                 basicPoint: unprojection.basicPoint,
56362                 latLon: unprojection.latLon,
56363                 originalEvent: event,
56364                 pixelPoint: unprojection.pixelPoint,
56365                 target: _this._eventEmitter,
56366                 type: type,
56367             };
56368         }))
56369             .subscribe(function (event) {
56370             _this._eventEmitter.fire(event.type, event);
56371         });
56372         this._positionSubscription = this._container.renderService.renderCamera$.pipe(operators_1.distinctUntilChanged(function (_a, _b) {
56373             var x1 = _a[0], y1 = _a[1];
56374             var x2 = _b[0], y2 = _b[1];
56375             return _this._closeTo(x1, x2, 1e-2) &&
56376                 _this._closeTo(y1, y2, 1e-2);
56377         }, function (rc) {
56378             return rc.camera.position.toArray();
56379         }))
56380             .subscribe(function () {
56381             _this._eventEmitter.fire(Viewer_1.Viewer.positionchanged, {
56382                 target: _this._eventEmitter,
56383                 type: Viewer_1.Viewer.positionchanged,
56384             });
56385         });
56386         this._povSubscription = this._container.renderService.renderCamera$.pipe(operators_1.distinctUntilChanged(function (_a, _b) {
56387             var phi1 = _a[0], theta1 = _a[1];
56388             var phi2 = _b[0], theta2 = _b[1];
56389             return _this._closeTo(phi1, phi2, 1e-3) &&
56390                 _this._closeTo(theta1, theta2, 1e-3);
56391         }, function (rc) {
56392             return [rc.rotation.phi, rc.rotation.theta];
56393         }))
56394             .subscribe(function () {
56395             _this._eventEmitter.fire(Viewer_1.Viewer.povchanged, {
56396                 target: _this._eventEmitter,
56397                 type: Viewer_1.Viewer.povchanged,
56398             });
56399         });
56400         this._fovSubscription = this._container.renderService.renderCamera$.pipe(operators_1.distinctUntilChanged(function (fov1, fov2) {
56401             return _this._closeTo(fov1, fov2, 1e-2);
56402         }, function (rc) {
56403             return rc.perspective.fov;
56404         }))
56405             .subscribe(function () {
56406             _this._eventEmitter.fire(Viewer_1.Viewer.fovchanged, {
56407                 target: _this._eventEmitter,
56408                 type: Viewer_1.Viewer.fovchanged,
56409             });
56410         });
56411     };
56412     Observer.prototype.stopEmit = function () {
56413         if (!this.started) {
56414             return;
56415         }
56416         this._started = false;
56417         this._bearingSubscription.unsubscribe();
56418         this._currentNodeSubscription.unsubscribe();
56419         this._fovSubscription.unsubscribe();
56420         this._moveSubscription.unsubscribe();
56421         this._positionSubscription.unsubscribe();
56422         this._povSubscription.unsubscribe();
56423         this._sequenceEdgesSubscription.unsubscribe();
56424         this._spatialEdgesSubscription.unsubscribe();
56425         this._viewerMouseEventSubscription.unsubscribe();
56426         this._bearingSubscription = null;
56427         this._currentNodeSubscription = null;
56428         this._fovSubscription = null;
56429         this._moveSubscription = null;
56430         this._positionSubscription = null;
56431         this._povSubscription = null;
56432         this._sequenceEdgesSubscription = null;
56433         this._spatialEdgesSubscription = null;
56434         this._viewerMouseEventSubscription = null;
56435     };
56436     Observer.prototype.unproject$ = function (canvasPoint) {
56437         var _this = this;
56438         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) {
56439             var render = _a[0], reference = _a[1], transform = _a[2];
56440             var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform);
56441             return unprojection.latLon;
56442         }));
56443     };
56444     Observer.prototype.unprojectBasic$ = function (canvasPoint) {
56445         var _this = this;
56446         return rxjs_1.combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$).pipe(operators_1.first(), operators_1.map(function (_a) {
56447             var render = _a[0], transform = _a[1];
56448             return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform);
56449         }));
56450     };
56451     Observer.prototype._closeTo = function (v1, v2, absoluteTolerance) {
56452         return Math.abs(v1 - v2) <= absoluteTolerance;
56453     };
56454     Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
56455         return mouseEvent$.pipe(operators_1.map(function (event) {
56456             return [type, event];
56457         }));
56458     };
56459     return Observer;
56460 }());
56461 exports.Observer = Observer;
56462 exports.default = Observer;
56463
56464 },{"../Viewer":302,"rxjs":43,"rxjs/operators":241}],467:[function(require,module,exports){
56465 "use strict";
56466 Object.defineProperty(exports, "__esModule", { value: true });
56467 var rxjs_1 = require("rxjs");
56468 var operators_1 = require("rxjs/operators");
56469 var Geo = require("../geo/Geo");
56470 var GeoCoords_1 = require("../geo/GeoCoords");
56471 var GraphCalculator_1 = require("../graph/GraphCalculator");
56472 var Spatial_1 = require("../geo/Spatial");
56473 var Transform_1 = require("../geo/Transform");
56474 var ViewportCoords_1 = require("../geo/ViewportCoords");
56475 var PanMode;
56476 (function (PanMode) {
56477     PanMode[PanMode["Disabled"] = 0] = "Disabled";
56478     PanMode[PanMode["Enabled"] = 1] = "Enabled";
56479     PanMode[PanMode["Started"] = 2] = "Started";
56480 })(PanMode || (PanMode = {}));
56481 var PanService = /** @class */ (function () {
56482     function PanService(graphService, stateService, enabled, geoCoords, graphCalculator, spatial, viewportCoords) {
56483         this._graphService = graphService;
56484         this._stateService = stateService;
56485         this._geoCoords = !!geoCoords ? geoCoords : new GeoCoords_1.default();
56486         this._graphCalculator = !!graphCalculator ? graphCalculator : new GraphCalculator_1.default(this._geoCoords);
56487         this._spatial = !!spatial ? spatial : new Spatial_1.default();
56488         this._viewportCoords = !!viewportCoords ? viewportCoords : new ViewportCoords_1.default();
56489         this._mode = enabled !== false ? PanMode.Enabled : PanMode.Disabled;
56490         this._panNodesSubject$ = new rxjs_1.Subject();
56491         this._panNodes$ = this._panNodesSubject$.pipe(operators_1.startWith([]), operators_1.publishReplay(1), operators_1.refCount());
56492         this._panNodes$.subscribe();
56493     }
56494     Object.defineProperty(PanService.prototype, "panNodes$", {
56495         get: function () {
56496             return this._panNodes$;
56497         },
56498         enumerable: true,
56499         configurable: true
56500     });
56501     PanService.prototype.enable = function () {
56502         if (this._mode !== PanMode.Disabled) {
56503             return;
56504         }
56505         this._mode = PanMode.Enabled;
56506         this.start();
56507     };
56508     PanService.prototype.disable = function () {
56509         if (this._mode === PanMode.Disabled) {
56510             return;
56511         }
56512         this.stop();
56513         this._mode = PanMode.Disabled;
56514     };
56515     PanService.prototype.start = function () {
56516         var _this = this;
56517         if (this._mode !== PanMode.Enabled) {
56518             return;
56519         }
56520         var panNodes$ = this._stateService.currentNode$.pipe(operators_1.switchMap(function (current) {
56521             if (!current.merged) {
56522                 return rxjs_1.of([]);
56523             }
56524             var current$ = rxjs_1.of(current);
56525             var bounds = _this._graphCalculator.boundingBoxCorners(current.latLon, 20);
56526             var adjacent$ = _this._graphService
56527                 .cacheBoundingBox$(bounds[0], bounds[1]).pipe(operators_1.catchError(function (error) {
56528                 console.error("Failed to cache periphery bounding box (" + current.key + ")", error);
56529                 return rxjs_1.empty();
56530             }), operators_1.map(function (nodes) {
56531                 if (current.pano) {
56532                     return [];
56533                 }
56534                 var potential = [];
56535                 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
56536                     var node = nodes_1[_i];
56537                     if (node.key === current.key) {
56538                         continue;
56539                     }
56540                     if (node.mergeCC !== current.mergeCC) {
56541                         continue;
56542                     }
56543                     if (node.pano) {
56544                         continue;
56545                     }
56546                     if (_this._distance(node, current) > 4) {
56547                         continue;
56548                     }
56549                     potential.push(node);
56550                 }
56551                 return potential;
56552             }));
56553             return rxjs_1.combineLatest(current$, adjacent$).pipe(operators_1.withLatestFrom(_this._stateService.reference$), operators_1.map(function (_a) {
56554                 var _b = _a[0], cn = _b[0], adjacent = _b[1], reference = _a[1];
56555                 var currentDirection = _this._spatial.viewingDirection(cn.rotation);
56556                 var currentTranslation = Geo.computeTranslation({ lat: cn.latLon.lat, lon: cn.latLon.lon, alt: cn.alt }, cn.rotation, reference);
56557                 var currentTransform = _this._createTransform(cn, currentTranslation);
56558                 var currentAzimuthal = _this._spatial.wrap(_this._spatial.azimuthal(currentDirection.toArray(), currentTransform.upVector().toArray()), 0, 2 * Math.PI);
56559                 var currentProjectedPoints = _this._computeProjectedPoints(currentTransform);
56560                 var currentHFov = _this._computeHorizontalFov(currentProjectedPoints) / 180 * Math.PI;
56561                 var preferredOverlap = Math.PI / 8;
56562                 var left = undefined;
56563                 var right = undefined;
56564                 for (var _i = 0, adjacent_1 = adjacent; _i < adjacent_1.length; _i++) {
56565                     var a = adjacent_1[_i];
56566                     var translation = Geo.computeTranslation({ lat: a.latLon.lat, lon: a.latLon.lon, alt: a.alt }, a.rotation, reference);
56567                     var transform = _this._createTransform(a, translation);
56568                     var projectedPoints = _this._computeProjectedPoints(transform);
56569                     var hFov = _this._computeHorizontalFov(projectedPoints) / 180 * Math.PI;
56570                     var direction = _this._spatial.viewingDirection(a.rotation);
56571                     var azimuthal = _this._spatial.wrap(_this._spatial.azimuthal(direction.toArray(), transform.upVector().toArray()), 0, 2 * Math.PI);
56572                     var directionChange = _this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
56573                     var overlap = Number.NEGATIVE_INFINITY;
56574                     if (directionChange > 0) {
56575                         if (currentAzimuthal > azimuthal) {
56576                             overlap = currentAzimuthal - 2 * Math.PI + currentHFov / 2 - (azimuthal - hFov / 2);
56577                         }
56578                         else {
56579                             overlap = currentAzimuthal + currentHFov / 2 - (azimuthal - hFov / 2);
56580                         }
56581                     }
56582                     else {
56583                         if (currentAzimuthal < azimuthal) {
56584                             overlap = azimuthal + hFov / 2 - (currentAzimuthal + 2 * Math.PI - currentHFov / 2);
56585                         }
56586                         else {
56587                             overlap = azimuthal + hFov / 2 - (currentAzimuthal - currentHFov / 2);
56588                         }
56589                     }
56590                     var nonOverlap = Math.abs(hFov - overlap);
56591                     var distanceCost = _this._distance(a, cn);
56592                     var timeCost = Math.min(_this._timeDifference(a, cn), 4);
56593                     var overlapCost = 20 * Math.abs(overlap - preferredOverlap);
56594                     var fovCost = Math.min(5, 1 / Math.min(hFov / currentHFov, 1));
56595                     var nonOverlapCost = overlap > 0 ? -2 * nonOverlap : 0;
56596                     var cost = distanceCost + timeCost + overlapCost + fovCost + nonOverlapCost;
56597                     if (overlap > 0 &&
56598                         overlap < 0.5 * currentHFov &&
56599                         overlap < 0.5 * hFov &&
56600                         nonOverlap > 0.5 * currentHFov) {
56601                         if (directionChange > 0) {
56602                             if (!left) {
56603                                 left = [cost, a, transform, hFov];
56604                             }
56605                             else {
56606                                 if (cost < left[0]) {
56607                                     left = [cost, a, transform, hFov];
56608                                 }
56609                             }
56610                         }
56611                         else {
56612                             if (!right) {
56613                                 right = [cost, a, transform, hFov];
56614                             }
56615                             else {
56616                                 if (cost < right[0]) {
56617                                     right = [cost, a, transform, hFov];
56618                                 }
56619                             }
56620                         }
56621                     }
56622                 }
56623                 var panNodes = [];
56624                 if (!!left) {
56625                     panNodes.push([left[1], left[2], left[3]]);
56626                 }
56627                 if (!!right) {
56628                     panNodes.push([right[1], right[2], right[3]]);
56629                 }
56630                 return panNodes;
56631             }), operators_1.startWith([]));
56632         }));
56633         this._panNodesSubscription = this._stateService.currentState$.pipe(operators_1.map(function (frame) {
56634             return frame.state.nodesAhead > 0;
56635         }), operators_1.distinctUntilChanged(), operators_1.switchMap(function (traversing) {
56636             return traversing ? rxjs_1.of([]) : panNodes$;
56637         }))
56638             .subscribe(function (panNodes) {
56639             _this._panNodesSubject$.next(panNodes);
56640         });
56641         this._mode = PanMode.Started;
56642     };
56643     PanService.prototype.stop = function () {
56644         if (this._mode !== PanMode.Started) {
56645             return;
56646         }
56647         this._panNodesSubscription.unsubscribe();
56648         this._panNodesSubject$.next([]);
56649         this._mode = PanMode.Enabled;
56650     };
56651     PanService.prototype._distance = function (node, reference) {
56652         var _a = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, reference.latLon.lat, reference.latLon.lon, reference.alt), x = _a[0], y = _a[1], z = _a[2];
56653         return Math.sqrt(x * x + y * y + z * z);
56654     };
56655     PanService.prototype._timeDifference = function (node, reference) {
56656         return Math.abs(node.capturedAt - reference.capturedAt) / (1000 * 60 * 60 * 24 * 30);
56657     };
56658     PanService.prototype._createTransform = function (node, translation) {
56659         return new Transform_1.Transform(node.orientation, node.width, node.height, node.focal, node.scale, node.gpano, node.rotation, translation, node.assetsCached ? node.image : undefined, undefined, node.ck1, node.ck2, node.cameraProjection);
56660     };
56661     PanService.prototype._computeProjectedPoints = function (transform) {
56662         var vertices = [[1, 0]];
56663         var directions = [[0, 0.5]];
56664         var pointsPerLine = 20;
56665         return Geo.computeProjectedPoints(transform, vertices, directions, pointsPerLine, this._viewportCoords);
56666     };
56667     PanService.prototype._computeHorizontalFov = function (projectedPoints) {
56668         var _this = this;
56669         var fovs = projectedPoints
56670             .map(function (projectedPoint) {
56671             return _this._coordToFov(projectedPoint[0]);
56672         });
56673         var fov = Math.min.apply(Math, fovs);
56674         return fov;
56675     };
56676     PanService.prototype._coordToFov = function (x) {
56677         return 2 * Math.atan(x) * 180 / Math.PI;
56678     };
56679     return PanService;
56680 }());
56681 exports.PanService = PanService;
56682
56683 },{"../geo/Geo":409,"../geo/GeoCoords":410,"../geo/Spatial":412,"../geo/Transform":413,"../geo/ViewportCoords":414,"../graph/GraphCalculator":417,"rxjs":43,"rxjs/operators":241}],468:[function(require,module,exports){
56684 "use strict";
56685 Object.defineProperty(exports, "__esModule", { value: true });
56686 var rxjs_1 = require("rxjs");
56687 var operators_1 = require("rxjs/operators");
56688 var Edge_1 = require("../Edge");
56689 var Graph_1 = require("../Graph");
56690 var PlayService = /** @class */ (function () {
56691     function PlayService(graphService, stateService, graphCalculator) {
56692         this._graphService = graphService;
56693         this._stateService = stateService;
56694         this._graphCalculator = !!graphCalculator ? graphCalculator : new Graph_1.GraphCalculator();
56695         this._directionSubject$ = new rxjs_1.Subject();
56696         this._direction$ = this._directionSubject$.pipe(operators_1.startWith(Edge_1.EdgeDirection.Next), operators_1.publishReplay(1), operators_1.refCount());
56697         this._direction$.subscribe();
56698         this._playing = false;
56699         this._playingSubject$ = new rxjs_1.Subject();
56700         this._playing$ = this._playingSubject$.pipe(operators_1.startWith(this._playing), operators_1.publishReplay(1), operators_1.refCount());
56701         this._playing$.subscribe();
56702         this._speed = 0.5;
56703         this._speedSubject$ = new rxjs_1.Subject();
56704         this._speed$ = this._speedSubject$.pipe(operators_1.startWith(this._speed), operators_1.publishReplay(1), operators_1.refCount());
56705         this._speed$.subscribe();
56706         this._nodesAhead = this._mapNodesAhead(this._mapSpeed(this._speed));
56707         this._bridging$ = null;
56708     }
56709     Object.defineProperty(PlayService.prototype, "playing", {
56710         get: function () {
56711             return this._playing;
56712         },
56713         enumerable: true,
56714         configurable: true
56715     });
56716     Object.defineProperty(PlayService.prototype, "direction$", {
56717         get: function () {
56718             return this._direction$;
56719         },
56720         enumerable: true,
56721         configurable: true
56722     });
56723     Object.defineProperty(PlayService.prototype, "playing$", {
56724         get: function () {
56725             return this._playing$;
56726         },
56727         enumerable: true,
56728         configurable: true
56729     });
56730     Object.defineProperty(PlayService.prototype, "speed$", {
56731         get: function () {
56732             return this._speed$;
56733         },
56734         enumerable: true,
56735         configurable: true
56736     });
56737     PlayService.prototype.play = function () {
56738         var _this = this;
56739         if (this._playing) {
56740             return;
56741         }
56742         this._stateService.cutNodes();
56743         var stateSpeed = this._setSpeed(this._speed);
56744         this._stateService.setSpeed(stateSpeed);
56745         this._graphModeSubscription = this._speed$.pipe(operators_1.map(function (speed) {
56746             return speed > PlayService.sequenceSpeed ? Graph_1.GraphMode.Sequence : Graph_1.GraphMode.Spatial;
56747         }), operators_1.distinctUntilChanged())
56748             .subscribe(function (mode) {
56749             _this._graphService.setGraphMode(mode);
56750         });
56751         this._cacheSubscription = rxjs_1.combineLatest(this._stateService.currentNode$.pipe(operators_1.map(function (node) {
56752             return [node.sequenceKey, node.key];
56753         }), operators_1.distinctUntilChanged(undefined, function (_a) {
56754             var sequenceKey = _a[0], nodeKey = _a[1];
56755             return sequenceKey;
56756         })), this._graphService.graphMode$, this._direction$).pipe(operators_1.switchMap(function (_a) {
56757             var _b = _a[0], sequenceKey = _b[0], nodeKey = _b[1], mode = _a[1], direction = _a[2];
56758             if (direction !== Edge_1.EdgeDirection.Next && direction !== Edge_1.EdgeDirection.Prev) {
56759                 return rxjs_1.of([undefined, direction]);
56760             }
56761             var sequence$ = (mode === Graph_1.GraphMode.Sequence ?
56762                 _this._graphService.cacheSequenceNodes$(sequenceKey, nodeKey) :
56763                 _this._graphService.cacheSequence$(sequenceKey)).pipe(operators_1.retry(3), operators_1.catchError(function (error) {
56764                 console.error(error);
56765                 return rxjs_1.of(undefined);
56766             }));
56767             return rxjs_1.combineLatest(sequence$, rxjs_1.of(direction));
56768         }), operators_1.switchMap(function (_a) {
56769             var sequence = _a[0], direction = _a[1];
56770             if (sequence === undefined) {
56771                 return rxjs_1.empty();
56772             }
56773             var sequenceKeys = sequence.keys.slice();
56774             if (direction === Edge_1.EdgeDirection.Prev) {
56775                 sequenceKeys.reverse();
56776             }
56777             return _this._stateService.currentState$.pipe(operators_1.map(function (frame) {
56778                 return [frame.state.trajectory[frame.state.trajectory.length - 1].key, frame.state.nodesAhead];
56779             }), operators_1.scan(function (_a, _b) {
56780                 var lastRequestKey = _a[0], previousRequestKeys = _a[1];
56781                 var lastTrajectoryKey = _b[0], nodesAhead = _b[1];
56782                 if (lastRequestKey === undefined) {
56783                     lastRequestKey = lastTrajectoryKey;
56784                 }
56785                 var lastIndex = sequenceKeys.length - 1;
56786                 if (nodesAhead >= _this._nodesAhead || sequenceKeys[lastIndex] === lastRequestKey) {
56787                     return [lastRequestKey, []];
56788                 }
56789                 var current = sequenceKeys.indexOf(lastTrajectoryKey);
56790                 var start = sequenceKeys.indexOf(lastRequestKey) + 1;
56791                 var end = Math.min(lastIndex, current + _this._nodesAhead - nodesAhead) + 1;
56792                 if (end <= start) {
56793                     return [lastRequestKey, []];
56794                 }
56795                 return [sequenceKeys[end - 1], sequenceKeys.slice(start, end)];
56796             }, [undefined, []]), operators_1.mergeMap(function (_a) {
56797                 var lastRequestKey = _a[0], newRequestKeys = _a[1];
56798                 return rxjs_1.from(newRequestKeys);
56799             }));
56800         }), operators_1.mergeMap(function (key) {
56801             return _this._graphService.cacheNode$(key).pipe(operators_1.catchError(function () {
56802                 return rxjs_1.empty();
56803             }));
56804         }, 6))
56805             .subscribe();
56806         this._playingSubscription = this._stateService.currentState$.pipe(operators_1.filter(function (frame) {
56807             return frame.state.nodesAhead < _this._nodesAhead;
56808         }), operators_1.distinctUntilChanged(undefined, function (frame) {
56809             return frame.state.lastNode.key;
56810         }), operators_1.map(function (frame) {
56811             var lastNode = frame.state.lastNode;
56812             var trajectory = frame.state.trajectory;
56813             var increasingTime = undefined;
56814             for (var i = trajectory.length - 2; i >= 0; i--) {
56815                 var node = trajectory[i];
56816                 if (node.sequenceKey !== lastNode.sequenceKey) {
56817                     break;
56818                 }
56819                 if (node.capturedAt !== lastNode.capturedAt) {
56820                     increasingTime = node.capturedAt < lastNode.capturedAt;
56821                     break;
56822                 }
56823             }
56824             return [frame.state.lastNode, increasingTime];
56825         }), operators_1.withLatestFrom(this._direction$), operators_1.switchMap(function (_a) {
56826             var _b = _a[0], node = _b[0], increasingTime = _b[1], direction = _a[1];
56827             return rxjs_1.zip(([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
56828                 node.sequenceEdges$ :
56829                 node.spatialEdges$).pipe(operators_1.first(function (status) {
56830                 return status.cached;
56831             }), operators_1.timeout(15000)), rxjs_1.of(direction)).pipe(operators_1.map(function (_a) {
56832                 var s = _a[0], d = _a[1];
56833                 for (var _i = 0, _b = s.edges; _i < _b.length; _i++) {
56834                     var edge = _b[_i];
56835                     if (edge.data.direction === d) {
56836                         return edge.to;
56837                     }
56838                 }
56839                 return null;
56840             }), operators_1.switchMap(function (key) {
56841                 return key != null ?
56842                     _this._graphService.cacheNode$(key) :
56843                     _this._bridge$(node, increasingTime).pipe(operators_1.filter(function (n) {
56844                         return !!n;
56845                     }));
56846             }));
56847         }))
56848             .subscribe(function (node) {
56849             _this._stateService.appendNodes([node]);
56850         }, function (error) {
56851             console.error(error);
56852             _this.stop();
56853         });
56854         this._clearSubscription = this._stateService.currentNode$.pipe(operators_1.bufferCount(1, 10))
56855             .subscribe(function (nodes) {
56856             _this._stateService.clearPriorNodes();
56857         });
56858         this._setPlaying(true);
56859         var currentLastNodes$ = this._stateService.currentState$.pipe(operators_1.map(function (frame) {
56860             return frame.state;
56861         }), operators_1.distinctUntilChanged(function (_a, _b) {
56862             var kc1 = _a[0], kl1 = _a[1];
56863             var kc2 = _b[0], kl2 = _b[1];
56864             return kc1 === kc2 && kl1 === kl2;
56865         }, function (state) {
56866             return [state.currentNode.key, state.lastNode.key];
56867         }), operators_1.filter(function (state) {
56868             return state.currentNode.key === state.lastNode.key &&
56869                 state.currentIndex === state.trajectory.length - 1;
56870         }), operators_1.map(function (state) {
56871             return state.currentNode;
56872         }));
56873         this._stopSubscription = rxjs_1.combineLatest(currentLastNodes$, this._direction$).pipe(operators_1.switchMap(function (_a) {
56874             var node = _a[0], direction = _a[1];
56875             var edgeStatus$ = ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
56876                 node.sequenceEdges$ :
56877                 node.spatialEdges$).pipe(operators_1.first(function (status) {
56878                 return status.cached;
56879             }), operators_1.timeout(15000), operators_1.catchError(function (error) {
56880                 console.error(error);
56881                 return rxjs_1.of({ cached: false, edges: [] });
56882             }));
56883             return rxjs_1.combineLatest(rxjs_1.of(direction), edgeStatus$).pipe(operators_1.map(function (_a) {
56884                 var d = _a[0], es = _a[1];
56885                 for (var _i = 0, _b = es.edges; _i < _b.length; _i++) {
56886                     var edge = _b[_i];
56887                     if (edge.data.direction === d) {
56888                         return true;
56889                     }
56890                 }
56891                 return false;
56892             }));
56893         }), operators_1.mergeMap(function (hasEdge) {
56894             if (hasEdge || !_this._bridging$) {
56895                 return rxjs_1.of(hasEdge);
56896             }
56897             return _this._bridging$.pipe(operators_1.map(function (node) {
56898                 return node != null;
56899             }), operators_1.catchError(function (error) {
56900                 console.error(error);
56901                 return rxjs_1.of(false);
56902             }));
56903         }), operators_1.first(function (hasEdge) {
56904             return !hasEdge;
56905         }))
56906             .subscribe(undefined, undefined, function () { _this.stop(); });
56907         if (this._stopSubscription.closed) {
56908             this._stopSubscription = null;
56909         }
56910     };
56911     PlayService.prototype.setDirection = function (direction) {
56912         this._directionSubject$.next(direction);
56913     };
56914     PlayService.prototype.setSpeed = function (speed) {
56915         speed = Math.max(0, Math.min(1, speed));
56916         if (speed === this._speed) {
56917             return;
56918         }
56919         var stateSpeed = this._setSpeed(speed);
56920         if (this._playing) {
56921             this._stateService.setSpeed(stateSpeed);
56922         }
56923         this._speedSubject$.next(this._speed);
56924     };
56925     PlayService.prototype.stop = function () {
56926         if (!this._playing) {
56927             return;
56928         }
56929         if (!!this._stopSubscription) {
56930             if (!this._stopSubscription.closed) {
56931                 this._stopSubscription.unsubscribe();
56932             }
56933             this._stopSubscription = null;
56934         }
56935         this._graphModeSubscription.unsubscribe();
56936         this._graphModeSubscription = null;
56937         this._cacheSubscription.unsubscribe();
56938         this._cacheSubscription = null;
56939         this._playingSubscription.unsubscribe();
56940         this._playingSubscription = null;
56941         this._clearSubscription.unsubscribe();
56942         this._clearSubscription = null;
56943         this._stateService.setSpeed(1);
56944         this._stateService.cutNodes();
56945         this._graphService.setGraphMode(Graph_1.GraphMode.Spatial);
56946         this._setPlaying(false);
56947     };
56948     PlayService.prototype._bridge$ = function (node, increasingTime) {
56949         var _this = this;
56950         if (increasingTime === undefined) {
56951             return rxjs_1.of(null);
56952         }
56953         var boundingBox = this._graphCalculator.boundingBoxCorners(node.latLon, 25);
56954         this._bridging$ = this._graphService.cacheBoundingBox$(boundingBox[0], boundingBox[1]).pipe(operators_1.mergeMap(function (nodes) {
56955             var nextNode = null;
56956             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
56957                 var n = nodes_1[_i];
56958                 if (n.sequenceKey === node.sequenceKey ||
56959                     !n.cameraUuid ||
56960                     n.cameraUuid !== node.cameraUuid ||
56961                     n.capturedAt === node.capturedAt ||
56962                     n.capturedAt > node.capturedAt !== increasingTime) {
56963                     continue;
56964                 }
56965                 var delta = Math.abs(n.capturedAt - node.capturedAt);
56966                 if (delta > 15000) {
56967                     continue;
56968                 }
56969                 if (!nextNode || delta < Math.abs(nextNode.capturedAt - node.capturedAt)) {
56970                     nextNode = n;
56971                 }
56972             }
56973             return !!nextNode ?
56974                 _this._graphService.cacheNode$(nextNode.key) :
56975                 rxjs_1.of(null);
56976         }), operators_1.finalize(function () {
56977             _this._bridging$ = null;
56978         }), operators_1.publish(), operators_1.refCount());
56979         return this._bridging$;
56980     };
56981     PlayService.prototype._mapSpeed = function (speed) {
56982         var x = 2 * speed - 1;
56983         return Math.pow(10, x) - 0.2 * x;
56984     };
56985     PlayService.prototype._mapNodesAhead = function (stateSpeed) {
56986         return Math.round(Math.max(10, Math.min(50, 8 + 6 * stateSpeed)));
56987     };
56988     PlayService.prototype._setPlaying = function (playing) {
56989         this._playing = playing;
56990         this._playingSubject$.next(playing);
56991     };
56992     PlayService.prototype._setSpeed = function (speed) {
56993         this._speed = speed;
56994         var stateSpeed = this._mapSpeed(this._speed);
56995         this._nodesAhead = this._mapNodesAhead(stateSpeed);
56996         return stateSpeed;
56997     };
56998     PlayService.sequenceSpeed = 0.54;
56999     return PlayService;
57000 }());
57001 exports.PlayService = PlayService;
57002 exports.default = PlayService;
57003
57004 },{"../Edge":292,"../Graph":295,"rxjs":43,"rxjs/operators":241}],469:[function(require,module,exports){
57005 "use strict";
57006 Object.defineProperty(exports, "__esModule", { value: true });
57007 var THREE = require("three");
57008 var Geo_1 = require("../Geo");
57009 var Spatial_1 = require("../geo/Spatial");
57010 var Projection = /** @class */ (function () {
57011     function Projection(geoCoords, viewportCoords, spatial) {
57012         this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
57013         this._spatial = !!spatial ? spatial : new Spatial_1.default();
57014         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
57015     }
57016     Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) {
57017         return this._viewportCoords
57018             .basicToCanvasSafe(basicPoint[0], basicPoint[1], container, transform, render.perspective);
57019     };
57020     Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) {
57021         var basicPoint = this._viewportCoords
57022             .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective);
57023         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
57024             basicPoint = null;
57025         }
57026         return basicPoint;
57027     };
57028     Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) {
57029         var pixelPoint = this._viewportCoords.canvasPosition(event, container);
57030         return this.canvasToUnprojection(pixelPoint, container, render, reference, transform);
57031     };
57032     Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) {
57033         var canvasX = canvasPoint[0];
57034         var canvasY = canvasPoint[1];
57035         var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
57036         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
57037             .unproject(render.perspective);
57038         var basicPoint = transform.projectBasic(point3d.toArray());
57039         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
57040             basicPoint = null;
57041         }
57042         var direction3d = point3d.clone().sub(render.camera.position).normalize();
57043         var dist = -2 / direction3d.z;
57044         var latLon = null;
57045         if (dist > 0 && dist < 100 && !!basicPoint) {
57046             var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
57047             var latLonArray = this._geoCoords
57048                 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
57049                 .slice(0, 2);
57050             latLon = { lat: latLonArray[0], lon: latLonArray[1] };
57051         }
57052         var unprojection = {
57053             basicPoint: basicPoint,
57054             latLon: latLon,
57055             pixelPoint: [canvasX, canvasY],
57056         };
57057         return unprojection;
57058     };
57059     Projection.prototype.cameraToLatLon = function (render, reference) {
57060         var position = render.camera.position;
57061         var _a = this._geoCoords.enuToGeodetic(position.x, position.y, position.z, reference.lat, reference.lon, reference.alt), lat = _a[0], lon = _a[1];
57062         return { lat: lat, lon: lon };
57063     };
57064     Projection.prototype.latLonToCanvas = function (latLon, container, render, reference) {
57065         var point3d = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, reference.lat, reference.lon, reference.alt);
57066         var canvas = this._viewportCoords.projectToCanvasSafe(point3d, container, render.perspective);
57067         return canvas;
57068     };
57069     Projection.prototype.distanceBetweenLatLons = function (latLon1, latLon2) {
57070         return this._spatial.distanceFromLatLon(latLon1.lat, latLon1.lon, latLon2.lat, latLon2.lon);
57071     };
57072     return Projection;
57073 }());
57074 exports.Projection = Projection;
57075 exports.default = Projection;
57076
57077 },{"../Geo":294,"../geo/Spatial":412,"three":242}],470:[function(require,module,exports){
57078 "use strict";
57079 Object.defineProperty(exports, "__esModule", { value: true });
57080 var operators_1 = require("rxjs/operators");
57081 var THREE = require("three");
57082 var vd = require("virtual-dom");
57083 var rxjs_1 = require("rxjs");
57084 var Viewer_1 = require("../Viewer");
57085 var SpriteAtlas = /** @class */ (function () {
57086     function SpriteAtlas() {
57087     }
57088     Object.defineProperty(SpriteAtlas.prototype, "json", {
57089         set: function (value) {
57090             this._json = value;
57091         },
57092         enumerable: true,
57093         configurable: true
57094     });
57095     Object.defineProperty(SpriteAtlas.prototype, "image", {
57096         set: function (value) {
57097             this._image = value;
57098             this._texture = new THREE.Texture(this._image);
57099             this._texture.minFilter = THREE.NearestFilter;
57100         },
57101         enumerable: true,
57102         configurable: true
57103     });
57104     Object.defineProperty(SpriteAtlas.prototype, "loaded", {
57105         get: function () {
57106             return !!(this._image && this._json);
57107         },
57108         enumerable: true,
57109         configurable: true
57110     });
57111     SpriteAtlas.prototype.getGLSprite = function (name) {
57112         if (!this.loaded) {
57113             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
57114         }
57115         var definition = this._json[name];
57116         if (!definition) {
57117             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
57118             return new THREE.Object3D();
57119         }
57120         var texture = this._texture.clone();
57121         texture.needsUpdate = true;
57122         var width = this._image.width;
57123         var height = this._image.height;
57124         texture.offset.x = definition.x / width;
57125         texture.offset.y = (height - definition.y - definition.height) / height;
57126         texture.repeat.x = definition.width / width;
57127         texture.repeat.y = definition.height / height;
57128         var material = new THREE.SpriteMaterial({ map: texture });
57129         return new THREE.Sprite(material);
57130     };
57131     SpriteAtlas.prototype.getDOMSprite = function (name, float) {
57132         if (!this.loaded) {
57133             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
57134         }
57135         if (float == null) {
57136             float = Viewer_1.Alignment.Center;
57137         }
57138         var definition = this._json[name];
57139         if (!definition) {
57140             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
57141             return vd.h("div", {}, []);
57142         }
57143         var clipTop = definition.y;
57144         var clipRigth = definition.x + definition.width;
57145         var clipBottom = definition.y + definition.height;
57146         var clipLeft = definition.x;
57147         var left = -definition.x;
57148         var top = -definition.y;
57149         var height = this._image.height;
57150         var width = this._image.width;
57151         switch (float) {
57152             case Viewer_1.Alignment.Bottom:
57153             case Viewer_1.Alignment.Center:
57154             case Viewer_1.Alignment.Top:
57155                 left -= definition.width / 2;
57156                 break;
57157             case Viewer_1.Alignment.BottomLeft:
57158             case Viewer_1.Alignment.Left:
57159             case Viewer_1.Alignment.TopLeft:
57160                 left -= definition.width;
57161                 break;
57162             case Viewer_1.Alignment.BottomRight:
57163             case Viewer_1.Alignment.Right:
57164             case Viewer_1.Alignment.TopRight:
57165             default:
57166                 break;
57167         }
57168         switch (float) {
57169             case Viewer_1.Alignment.Center:
57170             case Viewer_1.Alignment.Left:
57171             case Viewer_1.Alignment.Right:
57172                 top -= definition.height / 2;
57173                 break;
57174             case Viewer_1.Alignment.Top:
57175             case Viewer_1.Alignment.TopLeft:
57176             case Viewer_1.Alignment.TopRight:
57177                 top -= definition.height;
57178                 break;
57179             case Viewer_1.Alignment.Bottom:
57180             case Viewer_1.Alignment.BottomLeft:
57181             case Viewer_1.Alignment.BottomRight:
57182             default:
57183                 break;
57184         }
57185         var pixelRatioInverse = 1 / definition.pixelRatio;
57186         clipTop *= pixelRatioInverse;
57187         clipRigth *= pixelRatioInverse;
57188         clipBottom *= pixelRatioInverse;
57189         clipLeft *= pixelRatioInverse;
57190         left *= pixelRatioInverse;
57191         top *= pixelRatioInverse;
57192         height *= pixelRatioInverse;
57193         width *= pixelRatioInverse;
57194         var properties = {
57195             src: this._image.src,
57196             style: {
57197                 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
57198                 height: height + "px",
57199                 left: left + "px",
57200                 position: "absolute",
57201                 top: top + "px",
57202                 width: width + "px",
57203             },
57204         };
57205         return vd.h("img", properties, []);
57206     };
57207     return SpriteAtlas;
57208 }());
57209 var SpriteService = /** @class */ (function () {
57210     function SpriteService(sprite) {
57211         var _this = this;
57212         this._retina = window.devicePixelRatio > 1;
57213         this._spriteAtlasOperation$ = new rxjs_1.Subject();
57214         this._spriteAtlas$ = this._spriteAtlasOperation$.pipe(operators_1.startWith(function (atlas) {
57215             return atlas;
57216         }), operators_1.scan(function (atlas, operation) {
57217             return operation(atlas);
57218         }, new SpriteAtlas()), operators_1.publishReplay(1), operators_1.refCount());
57219         this._spriteAtlas$.subscribe(function () { });
57220         if (sprite == null) {
57221             return;
57222         }
57223         var format = this._retina ? "@2x" : "";
57224         var imageXmlHTTP = new XMLHttpRequest();
57225         imageXmlHTTP.open("GET", sprite + format + ".png", true);
57226         imageXmlHTTP.responseType = "arraybuffer";
57227         imageXmlHTTP.onload = function () {
57228             var image = new Image();
57229             image.onload = function () {
57230                 _this._spriteAtlasOperation$.next(function (atlas) {
57231                     atlas.image = image;
57232                     return atlas;
57233                 });
57234             };
57235             var blob = new Blob([imageXmlHTTP.response]);
57236             image.src = window.URL.createObjectURL(blob);
57237         };
57238         imageXmlHTTP.onerror = function (error) {
57239             console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
57240         };
57241         imageXmlHTTP.send();
57242         var jsonXmlHTTP = new XMLHttpRequest();
57243         jsonXmlHTTP.open("GET", sprite + format + ".json", true);
57244         jsonXmlHTTP.responseType = "text";
57245         jsonXmlHTTP.onload = function () {
57246             var json = JSON.parse(jsonXmlHTTP.response);
57247             _this._spriteAtlasOperation$.next(function (atlas) {
57248                 atlas.json = json;
57249                 return atlas;
57250             });
57251         };
57252         jsonXmlHTTP.onerror = function (error) {
57253             console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
57254         };
57255         jsonXmlHTTP.send();
57256     }
57257     Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
57258         get: function () {
57259             return this._spriteAtlas$;
57260         },
57261         enumerable: true,
57262         configurable: true
57263     });
57264     return SpriteService;
57265 }());
57266 exports.SpriteService = SpriteService;
57267 exports.default = SpriteService;
57268
57269
57270 },{"../Viewer":302,"rxjs":43,"rxjs/operators":241,"three":242,"virtual-dom":247}],471:[function(require,module,exports){
57271 "use strict";
57272 Object.defineProperty(exports, "__esModule", { value: true });
57273 var rxjs_1 = require("rxjs");
57274 var operators_1 = require("rxjs/operators");
57275 var TouchService = /** @class */ (function () {
57276     function TouchService(canvasContainer, domContainer) {
57277         var _this = this;
57278         this._activeSubject$ = new rxjs_1.BehaviorSubject(false);
57279         this._active$ = this._activeSubject$.pipe(operators_1.distinctUntilChanged(), operators_1.publishReplay(1), operators_1.refCount());
57280         rxjs_1.fromEvent(domContainer, "touchmove")
57281             .subscribe(function (event) {
57282             event.preventDefault();
57283         });
57284         this._touchStart$ = rxjs_1.fromEvent(canvasContainer, "touchstart");
57285         this._touchMove$ = rxjs_1.fromEvent(canvasContainer, "touchmove");
57286         this._touchEnd$ = rxjs_1.fromEvent(canvasContainer, "touchend");
57287         this._touchCancel$ = rxjs_1.fromEvent(canvasContainer, "touchcancel");
57288         var tapStart$ = this._touchStart$.pipe(operators_1.filter(function (te) {
57289             return te.touches.length === 1 && te.targetTouches.length === 1;
57290         }), operators_1.share());
57291         this._doubleTap$ = tapStart$.pipe(operators_1.bufferWhen(function () {
57292             return tapStart$.pipe(operators_1.first(), operators_1.switchMap(function (event) {
57293                 return rxjs_1.merge(rxjs_1.timer(300), tapStart$).pipe(operators_1.take(1));
57294             }));
57295         }), operators_1.filter(function (events) {
57296             return events.length === 2;
57297         }), operators_1.map(function (events) {
57298             return events[events.length - 1];
57299         }), operators_1.share());
57300         this._doubleTap$
57301             .subscribe(function (event) {
57302             event.preventDefault();
57303         });
57304         this._singleTouchMove$ = this._touchMove$.pipe(operators_1.filter(function (te) {
57305             return te.touches.length === 1 && te.targetTouches.length === 1;
57306         }), operators_1.share());
57307         var singleTouchStart$ = rxjs_1.merge(this._touchStart$, this._touchEnd$, this._touchCancel$).pipe(operators_1.filter(function (te) {
57308             return te.touches.length === 1 && te.targetTouches.length === 1;
57309         }));
57310         var multipleTouchStart$ = rxjs_1.merge(this._touchStart$, this._touchEnd$, this._touchCancel$).pipe(operators_1.filter(function (te) {
57311             return te.touches.length >= 1;
57312         }));
57313         var touchStop$ = rxjs_1.merge(this._touchEnd$, this._touchCancel$).pipe(operators_1.filter(function (te) {
57314             return te.touches.length === 0;
57315         }));
57316         this._singleTouchDragStart$ = singleTouchStart$.pipe(operators_1.mergeMap(function (e) {
57317             return _this._singleTouchMove$.pipe(operators_1.takeUntil(rxjs_1.merge(touchStop$, multipleTouchStart$)), operators_1.take(1));
57318         }));
57319         this._singleTouchDragEnd$ = singleTouchStart$.pipe(operators_1.mergeMap(function (e) {
57320             return rxjs_1.merge(touchStop$, multipleTouchStart$).pipe(operators_1.first());
57321         }));
57322         this._singleTouchDrag$ = singleTouchStart$.pipe(operators_1.switchMap(function (te) {
57323             return _this._singleTouchMove$.pipe(operators_1.skip(1), operators_1.takeUntil(rxjs_1.merge(multipleTouchStart$, touchStop$)));
57324         }));
57325         var touchesChanged$ = rxjs_1.merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
57326         this._pinchStart$ = touchesChanged$.pipe(operators_1.filter(function (te) {
57327             return te.touches.length === 2 && te.targetTouches.length === 2;
57328         }));
57329         this._pinchEnd$ = touchesChanged$.pipe(operators_1.filter(function (te) {
57330             return te.touches.length !== 2 || te.targetTouches.length !== 2;
57331         }));
57332         this._pinchOperation$ = new rxjs_1.Subject();
57333         this._pinch$ = this._pinchOperation$.pipe(operators_1.scan(function (pinch, operation) {
57334             return operation(pinch);
57335         }, {
57336             changeX: 0,
57337             changeY: 0,
57338             clientX: 0,
57339             clientY: 0,
57340             distance: 0,
57341             distanceChange: 0,
57342             distanceX: 0,
57343             distanceY: 0,
57344             originalEvent: null,
57345             pageX: 0,
57346             pageY: 0,
57347             screenX: 0,
57348             screenY: 0,
57349             touch1: null,
57350             touch2: null,
57351         }));
57352         this._touchMove$.pipe(operators_1.filter(function (te) {
57353             return te.touches.length === 2 && te.targetTouches.length === 2;
57354         }), operators_1.map(function (te) {
57355             return function (previous) {
57356                 var touch1 = te.touches[0];
57357                 var touch2 = te.touches[1];
57358                 var minX = Math.min(touch1.clientX, touch2.clientX);
57359                 var maxX = Math.max(touch1.clientX, touch2.clientX);
57360                 var minY = Math.min(touch1.clientY, touch2.clientY);
57361                 var maxY = Math.max(touch1.clientY, touch2.clientY);
57362                 var centerClientX = minX + (maxX - minX) / 2;
57363                 var centerClientY = minY + (maxY - minY) / 2;
57364                 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
57365                 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
57366                 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
57367                 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
57368                 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
57369                 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
57370                 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
57371                 var distanceChange = distance - previous.distance;
57372                 var changeX = distanceX - previous.distanceX;
57373                 var changeY = distanceY - previous.distanceY;
57374                 var current = {
57375                     changeX: changeX,
57376                     changeY: changeY,
57377                     clientX: centerClientX,
57378                     clientY: centerClientY,
57379                     distance: distance,
57380                     distanceChange: distanceChange,
57381                     distanceX: distanceX,
57382                     distanceY: distanceY,
57383                     originalEvent: te,
57384                     pageX: centerPageX,
57385                     pageY: centerPageY,
57386                     screenX: centerScreenX,
57387                     screenY: centerScreenY,
57388                     touch1: touch1,
57389                     touch2: touch2,
57390                 };
57391                 return current;
57392             };
57393         }))
57394             .subscribe(this._pinchOperation$);
57395         this._pinchChange$ = this._pinchStart$.pipe(operators_1.switchMap(function (te) {
57396             return _this._pinch$.pipe(operators_1.skip(1), operators_1.takeUntil(_this._pinchEnd$));
57397         }));
57398     }
57399     Object.defineProperty(TouchService.prototype, "active$", {
57400         get: function () {
57401             return this._active$;
57402         },
57403         enumerable: true,
57404         configurable: true
57405     });
57406     Object.defineProperty(TouchService.prototype, "activate$", {
57407         get: function () {
57408             return this._activeSubject$;
57409         },
57410         enumerable: true,
57411         configurable: true
57412     });
57413     Object.defineProperty(TouchService.prototype, "doubleTap$", {
57414         get: function () {
57415             return this._doubleTap$;
57416         },
57417         enumerable: true,
57418         configurable: true
57419     });
57420     Object.defineProperty(TouchService.prototype, "touchStart$", {
57421         get: function () {
57422             return this._touchStart$;
57423         },
57424         enumerable: true,
57425         configurable: true
57426     });
57427     Object.defineProperty(TouchService.prototype, "touchMove$", {
57428         get: function () {
57429             return this._touchMove$;
57430         },
57431         enumerable: true,
57432         configurable: true
57433     });
57434     Object.defineProperty(TouchService.prototype, "touchEnd$", {
57435         get: function () {
57436             return this._touchEnd$;
57437         },
57438         enumerable: true,
57439         configurable: true
57440     });
57441     Object.defineProperty(TouchService.prototype, "touchCancel$", {
57442         get: function () {
57443             return this._touchCancel$;
57444         },
57445         enumerable: true,
57446         configurable: true
57447     });
57448     Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
57449         get: function () {
57450             return this._singleTouchDragStart$;
57451         },
57452         enumerable: true,
57453         configurable: true
57454     });
57455     Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
57456         get: function () {
57457             return this._singleTouchDrag$;
57458         },
57459         enumerable: true,
57460         configurable: true
57461     });
57462     Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
57463         get: function () {
57464             return this._singleTouchDragEnd$;
57465         },
57466         enumerable: true,
57467         configurable: true
57468     });
57469     Object.defineProperty(TouchService.prototype, "pinch$", {
57470         get: function () {
57471             return this._pinchChange$;
57472         },
57473         enumerable: true,
57474         configurable: true
57475     });
57476     Object.defineProperty(TouchService.prototype, "pinchStart$", {
57477         get: function () {
57478             return this._pinchStart$;
57479         },
57480         enumerable: true,
57481         configurable: true
57482     });
57483     Object.defineProperty(TouchService.prototype, "pinchEnd$", {
57484         get: function () {
57485             return this._pinchEnd$;
57486         },
57487         enumerable: true,
57488         configurable: true
57489     });
57490     return TouchService;
57491 }());
57492 exports.TouchService = TouchService;
57493
57494 },{"rxjs":43,"rxjs/operators":241}],472:[function(require,module,exports){
57495 "use strict";
57496 var __extends = (this && this.__extends) || (function () {
57497     var extendStatics = function (d, b) {
57498         extendStatics = Object.setPrototypeOf ||
57499             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
57500             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
57501         return extendStatics(d, b);
57502     }
57503     return function (d, b) {
57504         extendStatics(d, b);
57505         function __() { this.constructor = d; }
57506         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
57507     };
57508 })();
57509 Object.defineProperty(exports, "__esModule", { value: true });
57510 var rxjs_1 = require("rxjs");
57511 var operators_1 = require("rxjs/operators");
57512 var when = require("when");
57513 var Viewer_1 = require("../Viewer");
57514 var Utils_1 = require("../Utils");
57515 /**
57516  * @class Viewer
57517  *
57518  * @classdesc The Viewer object represents the navigable image viewer.
57519  * Create a Viewer by specifying a container, client ID, image key and
57520  * other options. The viewer exposes methods and events for programmatic
57521  * interaction.
57522  *
57523  * In the case of asynchronous methods, MapillaryJS returns promises to
57524  * the results. Notifications are always emitted through JavaScript events.
57525  *
57526  * The viewer works with a few different coordinate systems.
57527  *
57528  * Container pixel coordinates
57529  *
57530  * Pixel coordinates are coordinates on the viewer container. The origin is
57531  * in the top left corner of the container. The axes are
57532  * directed according to the following for a viewer container with a width
57533  * of 640 pixels and height of 480 pixels.
57534  *
57535  * ```
57536  * (0,0)                          (640, 0)
57537  *      +------------------------>
57538  *      |
57539  *      |
57540  *      |
57541  *      v                        +
57542  * (0, 480)                       (640, 480)
57543  * ```
57544  *
57545  * Basic image coordinates
57546  *
57547  * Basic image coordinates represents points in the original image adjusted for
57548  * orientation. They range from 0 to 1 on both axes. The origin is in the top left
57549  * corner of the image and the axes are directed
57550  * according to the following for all image types.
57551  *
57552  * ```
57553  * (0,0)                          (1, 0)
57554  *      +------------------------>
57555  *      |
57556  *      |
57557  *      |
57558  *      v                        +
57559  * (0, 1)                         (1, 1)
57560  * ```
57561  *
57562  * For every camera viewing direction it is possible to convert between these
57563  * two coordinate systems for the current node. The image can be panned and
57564  * zoomed independently of the size of the viewer container resulting in
57565  * different conversion results for different viewing directions.
57566  */
57567 var Viewer = /** @class */ (function (_super) {
57568     __extends(Viewer, _super);
57569     /**
57570      * Create a new viewer instance.
57571      *
57572      * @description It is possible to initialize the viewer with or
57573      * without a key.
57574      *
57575      * When you want to show a specific image in the viewer from
57576      * the start you should initialize it with a key.
57577      *
57578      * When you do not know the first image key at implementation
57579      * time, e.g. in a map-viewer application you should initialize
57580      * the viewer without a key and call `moveToKey` instead.
57581      *
57582      * When initializing with a key the viewer is bound to that key
57583      * until the node for that key has been successfully loaded.
57584      * Also, a cover with the image of the key will be shown.
57585      * If the data for that key can not be loaded because the key is
57586      * faulty or other errors occur it is not possible to navigate
57587      * to another key because the viewer is not navigable. The viewer
57588      * becomes navigable when the data for the key has been loaded and
57589      * the image is shown in the viewer. This way of initializing
57590      * the viewer is mostly for embedding in blog posts and similar
57591      * where one wants to show a specific image initially.
57592      *
57593      * If the viewer is initialized without a key (with null or
57594      * undefined) it is not bound to any particular key and it is
57595      * possible to move to any key with `viewer.moveToKey("<my-image-key>")`.
57596      * If the first move to a key fails it is possible to move to another
57597      * key. The viewer will show a black background until a move
57598      * succeeds. This way of intitializing is suited for a map-viewer
57599      * application when the initial key is not known at implementation
57600      * time.
57601      *
57602      * @param {string} id - Required `id` of a DOM element which will
57603      * be transformed into the viewer.
57604      * @param {string} clientId - Required `Mapillary API ClientID`. Can
57605      * be obtained from https://www.mapillary.com/app/settings/developers.
57606      * @param {string} key - Optional `image-key` to start from. The key
57607      * can be any Mapillary image. If a key is provided the viewer is
57608      * bound to that key until it has been fully loaded. If null is provided
57609      * no image is loaded at viewer initialization and the viewer is not
57610      * bound to any particular key. Any image can then be navigated to
57611      * with e.g. `viewer.moveToKey("<my-image-key>")`.
57612      * @param {IViewerOptions} options - Optional configuration object
57613      * specifing Viewer's and the components' initial setup.
57614      * @param {string} token - Optional bearer token for API requests of
57615      * protected resources.
57616      *
57617      * @example
57618      * ```
57619      * var viewer = new Mapillary.Viewer("<element-id>", "<client-id>", "<image-key>");
57620      * ```
57621      */
57622     function Viewer(id, clientId, key, options, token) {
57623         var _this = _super.call(this) || this;
57624         options = options != null ? options : {};
57625         Utils_1.Settings.setOptions(options);
57626         Utils_1.Urls.setOptions(options.url);
57627         _this._navigator = new Viewer_1.Navigator(clientId, options, token);
57628         _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
57629         _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
57630         _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
57631         return _this;
57632     }
57633     Object.defineProperty(Viewer.prototype, "isNavigable", {
57634         /**
57635          * Return a boolean indicating if the viewer is in a navigable state.
57636          *
57637          * @description The navigable state indicates if the viewer supports
57638          * moving, i.e. calling the {@link moveToKey}, {@link moveDir}
57639          * and {@link moveCloseTo} methods or changing the authentication state,
57640          * i.e. calling {@link setAuthToken}. The viewer will not be in a navigable
57641          * state if the cover is activated and the viewer has been supplied a key.
57642          * When the cover is deactivated or the viewer is activated without being
57643          * supplied a key it will be navigable.
57644          *
57645          * @returns {boolean} Boolean indicating whether the viewer is navigable.
57646          */
57647         get: function () {
57648             return this._componentController.navigable;
57649         },
57650         enumerable: true,
57651         configurable: true
57652     });
57653     /**
57654      * Activate the combined panning functionality.
57655      *
57656      * @description The combined panning functionality is active by default.
57657      */
57658     Viewer.prototype.activateCombinedPanning = function () {
57659         this._navigator.panService.enable();
57660     };
57661     /**
57662      * Activate a component.
57663      *
57664      * @param {string} name - Name of the component which will become active.
57665      *
57666      * @example
57667      * ```
57668      * viewer.activateComponent("marker");
57669      * ```
57670      */
57671     Viewer.prototype.activateComponent = function (name) {
57672         this._componentController.activate(name);
57673     };
57674     /**
57675      * Activate the cover (deactivates all other components).
57676      */
57677     Viewer.prototype.activateCover = function () {
57678         this._componentController.activateCover();
57679     };
57680     /**
57681      * Deactivate the combined panning functionality.
57682      *
57683      * @description Deactivating the combined panning functionality
57684      * could be needed in scenarios involving sequence only navigation.
57685      */
57686     Viewer.prototype.deactivateCombinedPanning = function () {
57687         this._navigator.panService.disable();
57688     };
57689     /**
57690      * Deactivate a component.
57691      *
57692      * @param {string} name - Name of component which become inactive.
57693      *
57694      * @example
57695      * ```
57696      * viewer.deactivateComponent("mouse");
57697      * ```
57698      */
57699     Viewer.prototype.deactivateComponent = function (name) {
57700         this._componentController.deactivate(name);
57701     };
57702     /**
57703      * Deactivate the cover (activates all components marked as active).
57704      */
57705     Viewer.prototype.deactivateCover = function () {
57706         this._componentController.deactivateCover();
57707     };
57708     /**
57709      * Get the bearing of the current viewer camera.
57710      *
57711      * @description The bearing depends on how the camera
57712      * is currently rotated and does not correspond
57713      * to the compass angle of the current node if the view
57714      * has been panned.
57715      *
57716      * Bearing is measured in degrees clockwise with respect to
57717      * north.
57718      *
57719      * @returns {Promise<number>} Promise to the bearing
57720      * of the current viewer camera.
57721      *
57722      * @example
57723      * ```
57724      * viewer.getBearing().then((b) => { console.log(b); });
57725      * ```
57726      */
57727     Viewer.prototype.getBearing = function () {
57728         var _this = this;
57729         return when.promise(function (resolve, reject) {
57730             _this._container.renderService.bearing$.pipe(operators_1.first())
57731                 .subscribe(function (bearing) {
57732                 resolve(bearing);
57733             }, function (error) {
57734                 reject(error);
57735             });
57736         });
57737     };
57738     /**
57739      * Returns the HTML element containing the viewer's <canvas> element.
57740      *
57741      * @description This is the element to which event bindings for viewer
57742      * interactivity (such as panning and zooming) are attached.
57743      *
57744      * @returns {HTMLElement} The container viewer's <canvas> element.
57745      */
57746     Viewer.prototype.getCanvasContainer = function () {
57747         return this._container.canvasContainer;
57748     };
57749     /**
57750      * Get the basic coordinates of the current image that is
57751      * at the center of the viewport.
57752      *
57753      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
57754      * and have the origin point, (0, 0), at the top left corner and the
57755      * maximum value, (1, 1), at the bottom right corner of the original
57756      * image.
57757      *
57758      * @returns {Promise<number[]>} Promise to the basic coordinates
57759      * of the current image at the center for the viewport.
57760      *
57761      * @example
57762      * ```
57763      * viewer.getCenter().then((c) => { console.log(c); });
57764      * ```
57765      */
57766     Viewer.prototype.getCenter = function () {
57767         var _this = this;
57768         return when.promise(function (resolve, reject) {
57769             _this._navigator.stateService.getCenter()
57770                 .subscribe(function (center) {
57771                 resolve(center);
57772             }, function (error) {
57773                 reject(error);
57774             });
57775         });
57776     };
57777     /**
57778      * Get a component.
57779      *
57780      * @param {string} name - Name of component.
57781      * @returns {Component} The requested component.
57782      *
57783      * @example
57784      * ```
57785      * var mouseComponent = viewer.getComponent("mouse");
57786      * ```
57787      */
57788     Viewer.prototype.getComponent = function (name) {
57789         return this._componentController.get(name);
57790     };
57791     /**
57792      * Returns the viewer's containing HTML element.
57793      *
57794      * @returns {HTMLElement} The viewer's container.
57795      */
57796     Viewer.prototype.getContainer = function () {
57797         return this._container.element;
57798     };
57799     /**
57800      * Get the viewer's current vertical field of view.
57801      *
57802      * @description The vertical field of view rendered on the viewer canvas
57803      * measured in degrees.
57804      *
57805      * @returns {Promise<number>} Promise to the current field of view
57806      * of the viewer camera.
57807      *
57808      * @example
57809      * ```
57810      * viewer.getFieldOfView().then((fov) => { console.log(fov); });
57811      * ```
57812      */
57813     Viewer.prototype.getFieldOfView = function () {
57814         var _this = this;
57815         return when.promise(function (resolve, reject) {
57816             _this._container.renderService.renderCamera$.pipe(operators_1.first())
57817                 .subscribe(function (rc) {
57818                 resolve(rc.perspective.fov);
57819             }, function (error) {
57820                 reject(error);
57821             });
57822         });
57823     };
57824     /**
57825      * Get the viewer's current point of view.
57826      *
57827      * @returns {Promise<IPointOfView>} Promise to the current point of view
57828      * of the viewer camera.
57829      *
57830      * @example
57831      * ```
57832      * viewer.getPointOfView().then((pov) => { console.log(pov); });
57833      * ```
57834      */
57835     Viewer.prototype.getPointOfView = function () {
57836         var _this = this;
57837         return when.promise(function (resolve, reject) {
57838             rxjs_1.combineLatest(_this._container.renderService.renderCamera$, _this._container.renderService.bearing$).pipe(operators_1.first())
57839                 .subscribe(function (_a) {
57840                 var rc = _a[0], bearing = _a[1];
57841                 resolve({
57842                     bearing: bearing,
57843                     tilt: rc.getTilt(),
57844                 });
57845             }, function (error) {
57846                 reject(error);
57847             });
57848         });
57849     };
57850     /**
57851      * Get the viewer's current position
57852      *
57853      * @returns {Promise<ILatLon>} Promise to the viewers's current
57854      * position.
57855      *
57856      * @example
57857      * ```
57858      * viewer.getPosition().then((pos) => { console.log(pos); });
57859      * ```
57860      */
57861     Viewer.prototype.getPosition = function () {
57862         var _this = this;
57863         return when.promise(function (resolve, reject) {
57864             rxjs_1.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.reference$).pipe(operators_1.first())
57865                 .subscribe(function (_a) {
57866                 var render = _a[0], reference = _a[1];
57867                 resolve(_this._observer.projection.cameraToLatLon(render, reference));
57868             }, function (error) {
57869                 reject(error);
57870             });
57871         });
57872     };
57873     /**
57874      * Get the image's current zoom level.
57875      *
57876      * @returns {Promise<number>} Promise to the viewers's current
57877      * zoom level.
57878      *
57879      * @example
57880      * ```
57881      * viewer.getZoom().then((z) => { console.log(z); });
57882      * ```
57883      */
57884     Viewer.prototype.getZoom = function () {
57885         var _this = this;
57886         return when.promise(function (resolve, reject) {
57887             _this._navigator.stateService.getZoom()
57888                 .subscribe(function (zoom) {
57889                 resolve(zoom);
57890             }, function (error) {
57891                 reject(error);
57892             });
57893         });
57894     };
57895     /**
57896      * Move close to given latitude and longitude.
57897      *
57898      * @description Because the method propagates IO errors, these potential errors
57899      * need to be handled by the method caller (see example).
57900      *
57901      * @param {Number} lat - Latitude, in degrees.
57902      * @param {Number} lon - Longitude, in degrees.
57903      * @returns {Promise<Node>} Promise to the node that was navigated to.
57904      * @throws {Error} If no nodes exist close to provided latitude
57905      * longitude.
57906      * @throws {Error} Propagates any IO errors to the caller.
57907      * @throws {Error} When viewer is not navigable.
57908      * @throws  {@link AbortMapillaryError} When a subsequent move request is made
57909      * before the move close to call has completed.
57910      *
57911      * @example
57912      * ```
57913      * viewer.moveCloseTo(0, 0).then(
57914      *     (n) => { console.log(n); },
57915      *     (e) => { console.error(e); });
57916      * ```
57917      */
57918     Viewer.prototype.moveCloseTo = function (lat, lon) {
57919         var moveCloseTo$ = this.isNavigable ?
57920             this._navigator.moveCloseTo$(lat, lon) :
57921             rxjs_1.throwError(new Error("Calling moveCloseTo is not supported when viewer is not navigable."));
57922         return when.promise(function (resolve, reject) {
57923             moveCloseTo$.subscribe(function (node) {
57924                 resolve(node);
57925             }, function (error) {
57926                 reject(error);
57927             });
57928         });
57929     };
57930     /**
57931      * Navigate in a given direction.
57932      *
57933      * @description This method has to be called through EdgeDirection enumeration as in the example.
57934      *
57935      * @param {EdgeDirection} dir - Direction in which which to move.
57936      * @returns {Promise<Node>} Promise to the node that was navigated to.
57937      * @throws {Error} If the current node does not have the edge direction
57938      * or the edges has not yet been cached.
57939      * @throws {Error} Propagates any IO errors to the caller.
57940      * @throws {Error} When viewer is not navigable.
57941      * @throws  {@link AbortMapillaryError} When a subsequent move request is made
57942      * before the move dir call has completed.
57943      *
57944      * @example
57945      * ```
57946      * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
57947      *     (n) => { console.log(n); },
57948      *     (e) => { console.error(e); });
57949      * ```
57950      */
57951     Viewer.prototype.moveDir = function (dir) {
57952         var moveDir$ = this.isNavigable ?
57953             this._navigator.moveDir$(dir) :
57954             rxjs_1.throwError(new Error("Calling moveDir is not supported when viewer is not navigable."));
57955         return when.promise(function (resolve, reject) {
57956             moveDir$.subscribe(function (node) {
57957                 resolve(node);
57958             }, function (error) {
57959                 reject(error);
57960             });
57961         });
57962     };
57963     /**
57964      * Navigate to a given image key.
57965      *
57966      * @param {string} key - A valid Mapillary image key.
57967      * @returns {Promise<Node>} Promise to the node that was navigated to.
57968      * @throws {Error} Propagates any IO errors to the caller.
57969      * @throws {Error} When viewer is not navigable.
57970      * @throws  {@link AbortMapillaryError} When a subsequent move request is made
57971      * before the move to key call has completed.
57972      *
57973      * @example
57974      * ```
57975      * viewer.moveToKey("<my key>").then(
57976      *     (n) => { console.log(n); },
57977      *     (e) => { console.error(e); });
57978      * ```
57979      */
57980     Viewer.prototype.moveToKey = function (key) {
57981         var moveToKey$ = this.isNavigable ?
57982             this._navigator.moveToKey$(key) :
57983             rxjs_1.throwError(new Error("Calling moveToKey is not supported when viewer is not navigable."));
57984         return when.promise(function (resolve, reject) {
57985             moveToKey$.subscribe(function (node) {
57986                 resolve(node);
57987             }, function (error) {
57988                 reject(error);
57989             });
57990         });
57991     };
57992     /**
57993      * Project an ILatLon representing geographicalcoordinates to
57994      * canvas pixel coordinates.
57995      *
57996      * @description The geographical coordinates may not always correspond to pixel
57997      * coordinates, e.g. if the geographical coordinates have a position behind the
57998      * viewer camera. In the case of no correspondence the returned value will
57999      * be `null`.
58000      *
58001      * If the distance from the viewer camera position to the provided lat-lon
58002      * is more than 1000 meters `null` will be returned.
58003      *
58004      * The projection is performed from the ground plane, i.e.
58005      * the altitude with respect to the ground plane for the geographical
58006      * point is zero.
58007      *
58008      * Note that whenever the camera moves, the result of the method will be
58009      * different.
58010      *
58011      * @param {ILatLon} latLon - Geographical coordinates to project.
58012      * @returns {Promise<Array<number>>} Promise to the pixel coordinates corresponding
58013      * to the latLon.
58014      *
58015      * @example
58016      * ```
58017      * viewer.project({ lat: 0, lon: 0 })
58018      *     .then((pixelPoint) => {
58019      *          if (!pixelPoint) {
58020      *              console.log("no correspondence");
58021      *          }
58022      *
58023      *          console.log(pixelPoint);
58024      *     });
58025      * ```
58026      */
58027     Viewer.prototype.project = function (latLon) {
58028         var _this = this;
58029         return when.promise(function (resolve, reject) {
58030             _this._observer.project$(latLon)
58031                 .subscribe(function (pixelPoint) {
58032                 resolve(pixelPoint);
58033             }, function (error) {
58034                 reject(error);
58035             });
58036         });
58037     };
58038     /**
58039      * Project basic image coordinates for the current node to canvas pixel
58040      * coordinates.
58041      *
58042      * @description The basic image coordinates may not always correspond to a
58043      * pixel point that lies in the visible area of the viewer container. In the
58044      * case of no correspondence the returned value can be `null`.
58045      *
58046      *
58047      * @param {Array<number>} basicPoint - Basic images coordinates to project.
58048      * @returns {Promise<Array<number>>} Promise to the pixel coordinates corresponding
58049      * to the basic image point.
58050      *
58051      * @example
58052      * ```
58053      * viewer.projectFromBasic([0.3, 0.7])
58054      *     .then((pixelPoint) => { console.log(pixelPoint); });
58055      * ```
58056      */
58057     Viewer.prototype.projectFromBasic = function (basicPoint) {
58058         var _this = this;
58059         return when.promise(function (resolve, reject) {
58060             _this._observer.projectBasic$(basicPoint)
58061                 .subscribe(function (pixelPoint) {
58062                 resolve(pixelPoint);
58063             }, function (error) {
58064                 reject(error);
58065             });
58066         });
58067     };
58068     /**
58069      * Detect the viewer's new width and height and resize it.
58070      *
58071      * @description The components will also detect the viewer's
58072      * new size and resize their rendered elements if needed.
58073      *
58074      * @example
58075      * ```
58076      * viewer.resize();
58077      * ```
58078      */
58079     Viewer.prototype.resize = function () {
58080         this._container.renderService.resize$.next(null);
58081     };
58082     /**
58083      * Set a bearer token for authenticated API requests of
58084      * protected resources.
58085      *
58086      * @description When the supplied token is null or undefined,
58087      * any previously set bearer token will be cleared and the
58088      * viewer will make unauthenticated requests.
58089      *
58090      * Calling setAuthToken aborts all outstanding move requests.
58091      * The promises of those move requests will be rejected with a
58092      * {@link AbortMapillaryError} the rejections need to be caught.
58093      *
58094      * Calling setAuthToken also resets the complete viewer cache
58095      * so it should not be called repeatedly.
58096      *
58097      * @param {string} [token] token - Bearer token.
58098      * @returns {Promise<void>} Promise that resolves after token
58099      * is set.
58100      *
58101      * @throws {Error} When viewer is not navigable.
58102      *
58103      * @example
58104      * ```
58105      * viewer.setAuthToken("<my token>")
58106      *     .then(() => { console.log("token set"); });
58107      * ```
58108      */
58109     Viewer.prototype.setAuthToken = function (token) {
58110         var setToken$ = this.isNavigable ?
58111             this._navigator.setToken$(token) :
58112             rxjs_1.throwError(new Error("Calling setAuthToken is not supported when viewer is not navigable."));
58113         return when.promise(function (resolve, reject) {
58114             setToken$
58115                 .subscribe(function () {
58116                 resolve(undefined);
58117             }, function (error) {
58118                 reject(error);
58119             });
58120         });
58121     };
58122     /**
58123      * Set the basic coordinates of the current image to be in the
58124      * center of the viewport.
58125      *
58126      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
58127      * and has the origin point, (0, 0), at the top left corner and the
58128      * maximum value, (1, 1), at the bottom right corner of the original
58129      * image.
58130      *
58131      * @param {number[]} The basic coordinates of the current
58132      * image to be at the center for the viewport.
58133      *
58134      * @example
58135      * ```
58136      * viewer.setCenter([0.5, 0.5]);
58137      * ```
58138      */
58139     Viewer.prototype.setCenter = function (center) {
58140         this._navigator.stateService.setCenter(center);
58141     };
58142     /**
58143      * Set the filter selecting nodes to use when calculating
58144      * the spatial edges.
58145      *
58146      * @description The following filter types are supported:
58147      *
58148      * Comparison
58149      *
58150      * `["==", key, value]` equality: `node[key] = value`
58151      *
58152      * `["!=", key, value]` inequality: `node[key] â‰  value`
58153      *
58154      * `["<", key, value]` less than: `node[key] < value`
58155      *
58156      * `["<=", key, value]` less than or equal: `node[key] â‰¤ value`
58157      *
58158      * `[">", key, value]` greater than: `node[key] > value`
58159      *
58160      * `[">=", key, value]` greater than or equal: `node[key] â‰¥ value`
58161      *
58162      * Set membership
58163      *
58164      * `["in", key, v0, ..., vn]` set inclusion: `node[key] âˆˆ {v0, ..., vn}`
58165      *
58166      * `["!in", key, v0, ..., vn]` set exclusion: `node[key] âˆ‰ {v0, ..., vn}`
58167      *
58168      * Combining
58169      *
58170      * `["all", f0, ..., fn]` logical `AND`: `f0 âˆ§ ... âˆ§ fn`
58171      *
58172      * A key must be a string that identifies a property name of a
58173      * simple {@link Node} property. A value must be a string, number, or
58174      * boolean. Strictly-typed comparisons are used. The values
58175      * `f0, ..., fn` of the combining filter must be filter expressions.
58176      *
58177      * Clear the filter by setting it to null or empty array.
58178      *
58179      * Commonly used filter properties (see the {@link Node} class
58180      * documentation for a full list of properties that can be used
58181      * in a filter) and common use cases:
58182      *
58183      * ```
58184      * fullPano        // Show only full 360 panoramas or not
58185      * organizationKey // Show images from one or several organizations
58186      * sequenceKey     // Show images from one or several sequences
58187      * userKey         // Show images from one or several users
58188      * capturedAt      // Show images from a certain time interval
58189      * ```
58190      *
58191      * @param {FilterExpression} filter - The filter expression.
58192      * @returns {Promise<void>} Promise that resolves after filter is applied.
58193      *
58194      * @example
58195      * ```
58196      * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
58197      *
58198      * // Other examples
58199      * // viewer.setFilter(["==", "organizationKey", "<my organization key>"]);
58200      * // viewer.setFilter(["in", "userKey", "<my user key #1>", "<my user key #2>"]);
58201      * // viewer.setFilter(["==", "fullPano", true]);
58202      * // viewer.setFilter([">=", "capturedAt", <my time stamp>]);
58203      * ```
58204      */
58205     Viewer.prototype.setFilter = function (filter) {
58206         var _this = this;
58207         return when.promise(function (resolve, reject) {
58208             _this._navigator.setFilter$(filter)
58209                 .subscribe(function () {
58210                 resolve(undefined);
58211             }, function (error) {
58212                 reject(error);
58213             });
58214         });
58215     };
58216     /**
58217      * Set the viewer's current vertical field of view.
58218      *
58219      * @description Sets the vertical field of view rendered
58220      * on the viewer canvas measured in degrees. The value
58221      * will be clamped to be able to set a valid zoom level
58222      * based on the projection model of the current image and
58223      * the viewer's current render mode.
58224      *
58225      * @param {number} fov - Vertical field of view in degrees.
58226      *
58227      * @example
58228      * ```
58229      * viewer.setFieldOfView(45);
58230      * ```
58231      */
58232     Viewer.prototype.setFieldOfView = function (fov) {
58233         var _this = this;
58234         this._container.renderService.renderCamera$.pipe(operators_1.first())
58235             .subscribe(function (rc) {
58236             var zoom = rc.fovToZoom(fov);
58237             _this._navigator.stateService.setZoom(zoom);
58238         });
58239     };
58240     /**
58241      * Set the viewer's render mode.
58242      *
58243      * @param {RenderMode} renderMode - Render mode.
58244      *
58245      * @example
58246      * ```
58247      * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
58248      * ```
58249      */
58250     Viewer.prototype.setRenderMode = function (renderMode) {
58251         this._container.renderService.renderMode$.next(renderMode);
58252     };
58253     /**
58254      * Set the viewer's transition mode.
58255      *
58256      * @param {TransitionMode} transitionMode - Transition mode.
58257      *
58258      * @example
58259      * ```
58260      * viewer.setTransitionMode(Mapillary.TransitionMode.Instantaneous);
58261      * ```
58262      */
58263     Viewer.prototype.setTransitionMode = function (transitionMode) {
58264         this._navigator.stateService.setTransitionMode(transitionMode);
58265     };
58266     /**
58267      * Set the image's current zoom level.
58268      *
58269      * @description Possible zoom level values are on the [0, 3] interval.
58270      * Zero means zooming out to fit the image to the view whereas three
58271      * shows the highest level of detail.
58272      *
58273      * @param {number} The image's current zoom level.
58274      *
58275      * @example
58276      * ```
58277      * viewer.setZoom(2);
58278      * ```
58279      */
58280     Viewer.prototype.setZoom = function (zoom) {
58281         this._navigator.stateService.setZoom(zoom);
58282     };
58283     /**
58284      * Unproject canvas pixel coordinates to an ILatLon representing geographical
58285      * coordinates.
58286      *
58287      * @description The pixel point may not always correspond to geographical
58288      * coordinates. In the case of no correspondence the returned value will
58289      * be `null`.
58290      *
58291      * The unprojection to a latLon will be performed towards the ground plane, i.e.
58292      * the altitude with respect to the ground plane for the returned latLon is zero.
58293      *
58294      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
58295      * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
58296      *
58297      * @example
58298      * ```
58299      * viewer.unproject([100, 100])
58300      *     .then((latLon) => { console.log(latLon); });
58301      * ```
58302      */
58303     Viewer.prototype.unproject = function (pixelPoint) {
58304         var _this = this;
58305         return when.promise(function (resolve, reject) {
58306             _this._observer.unproject$(pixelPoint)
58307                 .subscribe(function (latLon) {
58308                 resolve(latLon);
58309             }, function (error) {
58310                 reject(error);
58311             });
58312         });
58313     };
58314     /**
58315      * Unproject canvas pixel coordinates to basic image coordinates for the
58316      * current node.
58317      *
58318      * @description The pixel point may not always correspond to basic image
58319      * coordinates. In the case of no correspondence the returned value will
58320      * be `null`.
58321      *
58322      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
58323      * @returns {Promise<ILatLon>} Promise to the basic coordinates corresponding
58324      * to the pixel point.
58325      *
58326      * @example
58327      * ```
58328      * viewer.unprojectToBasic([100, 100])
58329      *     .then((basicPoint) => { console.log(basicPoint); });
58330      * ```
58331      */
58332     Viewer.prototype.unprojectToBasic = function (pixelPoint) {
58333         var _this = this;
58334         return when.promise(function (resolve, reject) {
58335             _this._observer.unprojectBasic$(pixelPoint)
58336                 .subscribe(function (basicPoint) {
58337                 resolve(basicPoint);
58338             }, function (error) {
58339                 reject(error);
58340             });
58341         });
58342     };
58343     /**
58344      * Fired when the viewing direction of the camera changes.
58345      *
58346      * @description Related to the computed compass angle
58347      * ({@link Node.computedCA}) from SfM, not the original EXIF compass
58348      * angle.
58349      *
58350      * @event
58351      * @type {number} bearing - Value indicating the current bearing
58352      * measured in degrees clockwise with respect to north.
58353      */
58354     Viewer.bearingchanged = "bearingchanged";
58355     /**
58356      * Fired when a pointing device (usually a mouse) is pressed and released at
58357      * the same point in the viewer.
58358      * @event
58359      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
58360      */
58361     Viewer.click = "click";
58362     /**
58363      * Fired when the right button of the mouse is clicked within the viewer.
58364      * @event
58365      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
58366      */
58367     Viewer.contextmenu = "contextmenu";
58368     /**
58369      * Fired when a pointing device (usually a mouse) is clicked twice at
58370      * the same point in the viewer.
58371      * @event
58372      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
58373      */
58374     Viewer.dblclick = "dblclick";
58375     /**
58376      * Fired when the viewer's vertical field of view changes.
58377      *
58378      * @event
58379      * @type  {@link IViewerEvent} event - The event object.
58380      */
58381     Viewer.fovchanged = "fovchanged";
58382     /**
58383      * Fired when the viewer is loading more data.
58384      * @event
58385      * @type {boolean} loading - Boolean indicating whether the viewer is loading.
58386      */
58387     Viewer.loadingchanged = "loadingchanged";
58388     /**
58389      * Fired when a pointing device (usually a mouse) is pressed within the viewer.
58390      * @event
58391      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
58392      */
58393     Viewer.mousedown = "mousedown";
58394     /**
58395      * Fired when a pointing device (usually a mouse) is moved within the viewer.
58396      * @description Will not fire when the mouse is actively used, e.g. for drag pan.
58397      * @event
58398      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
58399      */
58400     Viewer.mousemove = "mousemove";
58401     /**
58402      * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
58403      * @event
58404      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
58405      */
58406     Viewer.mouseout = "mouseout";
58407     /**
58408      * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
58409      * @event
58410      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
58411      */
58412     Viewer.mouseover = "mouseover";
58413     /**
58414      * Fired when a pointing device (usually a mouse) is released within the viewer.
58415      * @event
58416      * @type  {@link IViewerMouseEvent} event - Viewer mouse event data.
58417      */
58418     Viewer.mouseup = "mouseup";
58419     /**
58420      * Fired when the viewer motion stops and it is in a fixed
58421      * position with a fixed point of view.
58422      * @event
58423      */
58424     Viewer.moveend = "moveend";
58425     /**
58426      * Fired when the motion from one view to another start,
58427      * either by changing the position (e.g. when changing node) or
58428      * when changing point of view (e.g. by interaction such as pan and zoom).
58429      * @event
58430      */
58431     Viewer.movestart = "movestart";
58432     /**
58433      * Fired when the navigable state of the viewer changes.
58434      *
58435      * @description The navigable state indicates if the viewer supports
58436      * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
58437      * methods. The viewer will not be in a navigable state if the cover
58438      * is activated and the viewer has been supplied a key. When the cover
58439      * is deactivated or activated without being supplied a key it will
58440      * be navigable.
58441      *
58442      * @event
58443      * @type {boolean} navigable - Boolean indicating whether the viewer is navigable.
58444      */
58445     Viewer.navigablechanged = "navigablechanged";
58446     /**
58447      * Fired every time the viewer navigates to a new node.
58448      *
58449      * @event
58450      * @type  {@link Node} node - Current node.
58451      */
58452     Viewer.nodechanged = "nodechanged";
58453     /**
58454      * Fired when the viewer's position changes.
58455      *
58456      * @description The viewer's position changes when transitioning
58457      * between nodes.
58458      *
58459      * @event
58460      * @type  {@link IViewerEvent} event - The event object.
58461      */
58462     Viewer.positionchanged = "positionchanged";
58463     /**
58464      * Fired when the viewer's point of view changes. The point of view changes
58465      * when the bearing, or tilt changes.
58466      *
58467      * @event
58468      * @type  {@link IViewerEvent} event - The event object.
58469      */
58470     Viewer.povchanged = "povchanged";
58471     /**
58472      * Fired every time the sequence edges of the current node changes.
58473      * @event
58474      * @type  {@link IEdgeStatus} status - The edge status object.
58475      */
58476     Viewer.sequenceedgeschanged = "sequenceedgeschanged";
58477     /**
58478      * Fired every time the spatial edges of the current node changes.
58479      * @event
58480      * @type  {@link IEdgeStatus} status - The edge status object.
58481      */
58482     Viewer.spatialedgeschanged = "spatialedgeschanged";
58483     return Viewer;
58484 }(Utils_1.EventEmitter));
58485 exports.Viewer = Viewer;
58486
58487 },{"../Utils":301,"../Viewer":302,"rxjs":43,"rxjs/operators":241,"when":288}]},{},[296])(296)
58488 });
58489 //# sourceMappingURL=mapillary.js.map